@fungi.computer/grove 0.17.0 → 0.18.0
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/assets/{base-face-CsIbc1by.js → base-face-9ObbS-xX.js} +1 -1
- package/dist/assets/burger-DSUbtFiC.js +1 -0
- package/dist/assets/cat-Ti7rU0E2.js +1 -0
- package/dist/assets/conversation-toast-BxemDtnQ.js +56 -0
- package/dist/assets/document-Cfd1McDA.js +1 -0
- package/dist/assets/document-DZTTyAQ6.js +76 -0
- package/dist/assets/index-CQm9LO8C.js +25 -0
- package/dist/assets/index-D8R4KIKC.css +1 -0
- package/dist/assets/{mushroom-FKArpulr.js → mushroom-CXyBHPQt.js} +1 -1
- package/dist/assets/parakeet-BzQn0axB.js +35 -0
- package/dist/assets/parakeet-conversation-O1gOP0dj.js +4 -0
- package/dist/assets/renderer-HJftscjc.js +1 -0
- package/dist/assets/rolldown-runtime-CbXtAM7H.js +1 -0
- package/dist/assets/website-conversation-c3fqmIxA.js +1 -0
- package/dist/index.html +7 -12
- package/package.json +14 -7
- package/dist/assets/Effect-pxRavrBh.js +0 -76
- package/dist/assets/abort-signals-joV34wzR.js +0 -1
- package/dist/assets/anthropic-messages-CkLFXbme.js +0 -19
- package/dist/assets/azure-openai-responses-BjItkyTn.js +0 -1
- package/dist/assets/burger-BgftDtiM.js +0 -1
- package/dist/assets/cat-CfNEurUg.js +0 -1
- package/dist/assets/classifier-shared-JiMD88Sh.js +0 -1
- package/dist/assets/cloudflare-workers-ai-system-one-tEpgPfLW.js +0 -1
- package/dist/assets/compat-CxZajpXB.js +0 -2
- package/dist/assets/conversation-toast-DUFOMoQ9.js +0 -33
- package/dist/assets/diagnostics-CxvqSC4Q.js +0 -1
- package/dist/assets/document-BBvRlLC3.js +0 -1
- package/dist/assets/document-Bpcy9TTA.js +0 -1
- package/dist/assets/error-BTdmRKoB.js +0 -1
- package/dist/assets/error-body-C7MTmn8e.js +0 -1
- package/dist/assets/estimate-DElUjJag.js +0 -1
- package/dist/assets/extension-hook-Da3ATgkY.js +0 -890
- package/dist/assets/extensions-D2Z9guoO.js +0 -1
- package/dist/assets/github-copilot-headers-DRgtIyTm.js +0 -1
- package/dist/assets/google-generative-ai-DJB3dC5c.js +0 -1
- package/dist/assets/google-shared-DVq-_IDX.js +0 -8
- package/dist/assets/google-vertex-CYm5wNps.js +0 -1
- package/dist/assets/hash-yQufAZII.js +0 -1
- package/dist/assets/headers-FK4rgixo.js +0 -1
- package/dist/assets/index-BaCEAFz2.js +0 -117
- package/dist/assets/index-CIiuRnlU.css +0 -1
- package/dist/assets/mistral-conversations-DDg7eeLe.js +0 -4
- package/dist/assets/node.browser-CdLsHXpS.js +0 -1
- package/dist/assets/node.browser-HQ5SKBOf.js +0 -1
- package/dist/assets/openai-Cpe0uoXQ.js +0 -19
- package/dist/assets/openai-codex-responses-H7WhI66H.js +0 -9
- package/dist/assets/openai-codex.models-DXmil0i7.js +0 -1
- package/dist/assets/openai-completions-CkqQ2fFp.js +0 -5
- package/dist/assets/openai-decisions-DMV8tZy4.js +0 -2
- package/dist/assets/openai-prompt-cache-DXo9f3w5.js +0 -1
- package/dist/assets/openai-responses-Csql8sEY.js +0 -1
- package/dist/assets/openai-responses-shared-DAZ5Qapp.js +0 -13
- package/dist/assets/openrouter-cost-DOxSGpgH.js +0 -1
- package/dist/assets/openrouter-images-DFWtFOvI.js +0 -1
- package/dist/assets/parakeet-BUkzxkvS.js +0 -35
- package/dist/assets/parakeet-conversation-D8vRtIjX.js +0 -4
- package/dist/assets/pi-messages-DoPiztqV.js +0 -7
- package/dist/assets/preload-helper-CfILh1TC.js +0 -3
- package/dist/assets/provider-env-CcCbsTJq.js +0 -1
- package/dist/assets/provider-retry-RVfYd5Vz.js +0 -1
- package/dist/assets/renderer-BVZdPJB6.js +0 -1
- package/dist/assets/rolldown-runtime-hePW80VL.js +0 -1
- package/dist/assets/runtime-core-U8lOfyYX.js +0 -40
- package/dist/assets/sanitize-unicode-DmIE6hZJ.js +0 -1
- package/dist/assets/session-resources-CTNtT8Oa.js +0 -1
- package/dist/assets/streaming-json-Dg-jk7Sx.js +0 -6
- package/dist/assets/system-one-shared-D7AS4c2W.js +0 -1
- package/dist/assets/text-_WthCHzw.js +0 -6
- package/dist/assets/transform-messages-CCZNew0k.js +0 -1
- package/dist/assets/typesafe-system-one-Cl52u7Mq.js +0 -1
- package/dist/assets/website-conversation-CpPJ8N_o.js +0 -1
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/runtime-core-U8lOfyYX.js","assets/rolldown-runtime-hePW80VL.js","assets/Effect-pxRavrBh.js","assets/extension-hook-Da3ATgkY.js","assets/preload-helper-CfILh1TC.js","assets/text-_WthCHzw.js","assets/extensions-D2Z9guoO.js","assets/estimate-DElUjJag.js","assets/website-conversation-CpPJ8N_o.js","assets/conversation-toast-DUFOMoQ9.js","assets/document-BBvRlLC3.js","assets/parakeet-BUkzxkvS.js","assets/openai-codex.models-DXmil0i7.js","assets/parakeet-conversation-D8vRtIjX.js","assets/parakeet-conversation-COndlivb.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{$ as n,$i as r,$n as i,$r as a,$t as o,A as s,Ai as c,An as l,Ar as u,B as d,Bi as f,Bn as p,Br as m,C as h,Ca as g,Ci as _,Cn as v,Cr as y,D as b,Di as x,Dn as S,Dr as C,E as w,Ea as T,En as E,Er as D,F as O,Fn as k,Fr as A,Ft as j,G as M,Gi as N,Gn as ee,Gr as te,Gt as ne,H as P,Hi as F,Hn as re,Hr as I,I as L,Ii as R,In as z,Ir as ie,It as ae,J as oe,Ji as se,Jn as B,Jr as ce,Jt as le,K as ue,Ki as V,Kn as de,Kr as H,Kt as fe,L as pe,Li as me,Ln as he,Lr as ge,M as _e,Mi as U,Mn as ve,Mr as ye,N as be,Ni as W,Nn as xe,Nr as Se,O as Ce,Oi as we,On as Te,Or as Ee,P as De,Pi as Oe,Pn as ke,Pr as Ae,Pt as je,Q as Me,Qi as Ne,Qn as Pe,Qr as Fe,Qt as Ie,R as Le,Ri as Re,Rn as ze,Rr as Be,S as Ve,Sa as He,Sn as Ue,Sr as We,T as Ge,Ta as Ke,Ti as qe,Tn as Je,Tr as Ye,U as Xe,Ui as Ze,Un as Qe,Ur as $e,V as et,Vi as tt,Vn as nt,Vr as rt,W as it,Wi as at,Wn as ot,Wr as st,Wt as ct,X as lt,Xi as ut,Xn as dt,Xr as ft,Xt as pt,Y as mt,Yi as ht,Yn as gt,Yr as _t,Yt as vt,Z as yt,Zi as bt,Zn as xt,Zr as St,Zt as Ct,_ as wt,_a as Tt,_i as Et,_n as Dt,_r as Ot,_t as kt,a as At,aa as jt,ai as Mt,an as Nt,ar as Pt,b as Ft,ba as It,bi as Lt,bn as Rt,br as zt,ca as Bt,ci as Vt,cn as Ht,cr as Ut,d as Wt,da as Gt,di as Kt,dn as qt,dr as Jt,ea as Yt,ei as Xt,en as Zt,er as Qt,et as $t,fa as en,fi as tn,fn as nn,fr as rn,g as an,ga as on,gi as sn,gn as cn,gr as ln,h as un,ha as dn,hi as fn,hn as pn,hr as mn,i as hn,ia as gn,ii as _n,in as vn,ir as yn,j as bn,ji as xn,jn as Sn,jr as Cn,k as wn,ki as Tn,kn as En,kr as Dn,la as On,li as kn,ln as An,lr as jn,m as Mn,ma as Nn,mi as Pn,mn as Fn,mr as In,n as Ln,na as Rn,ni as zn,nn as Bn,nr as Vn,nt as Hn,o as Un,oa as Wn,oi as Gn,on as Kn,or as qn,ot as Jn,p as Yn,pa as Xn,pi as Zn,pn as Qn,pr as $n,q as er,qn as tr,qr as nr,qt as rr,r as ir,ra as ar,rn as or,rr as sr,rt as cr,sa as lr,si as ur,sn as dr,sr as fr,t as pr,ta as mr,tn as hr,tr as gr,tt as _r,ua as vr,un as yr,ur as br,v as xr,va as Sr,vi as Cr,vn as wr,vr as Tr,vt as Er,wa as Dr,wi as Or,wn as kr,wr as Ar,x as jr,xa as Mr,xn as Nr,y as Pr,ya as Fr,yi as Ir,yn as Lr,yr as Rr,yt as zr,z as Br,zi as Vr,zn as Hr,zr as Ur}from"./conversation-toast-DUFOMoQ9.js";import{Aa as Wr,Bi as Gr,Ct as Kr,E as qr,Ei as Jr,F as Yr,Fa as Xr,Gi as Zr,Hi as Qr,I as $r,Ji as ei,K as ti,Ki as ni,La as ri,Ma as ii,Oa as ai,Ri as oi,St as si,Ta as ci,Ui as li,V as ui,Vi as di,Wi as fi,Xi as pi,Y as mi,Yi as hi,Z as gi,Zi as _i,_ as vi,_a as yi,a as bi,ar as xi,ba as Si,bt as Ci,ca as wi,d as Ti,da as Ei,fa as Di,fr as Oi,g as ki,ga as Ai,gi as ji,gt as Mi,h as Ni,ht as Pi,i as Fi,ir as Ii,it as Li,j as Ri,ja as zi,l as Bi,lr as Vi,m as Hi,ma as Ui,mt as Wi,oa as Gi,pa as Ki,pt as qi,qi as Ji,ra as Yi,rr as Xi,s as Zi,sr as Qi,t as $i,tt as ea,ur as ta,wt as na,xa as ra,xi as ia,xt as aa,y as oa,ya as sa,za as ca,zi as la}from"./Effect-pxRavrBh.js";import{$a as ua,$i as da,$n as fa,Ai as pa,Ar as ma,Bi as ha,Bo as ga,Ci as _a,Co as va,Fi as G,Fo as ya,Ga as ba,Gi as K,Hi as q,Io as xa,Jo as Sa,Ka as Ca,Ki as wa,La as Ta,Li as Ea,Mi as Da,Mo as Oa,Mr as ka,Na as J,Ni as Aa,No as ja,Pi as Y,Po as Ma,Qi as Na,Qo as Pa,Ri as Fa,Si as Ia,Ta as La,Ti as Ra,Ui as za,Va as Ba,Vo as Va,Wa as Ha,Wi as Ua,Xi as Wa,Xo as Ga,Xr as Ka,Za as qa,Zi as Ja,_a as Ya,_o as Xa,ai as Za,ao as Qa,bi as $a,ca as eo,ci as to,co as no,cs as ro,d as io,do as ao,ea as oo,ei as so,f as co,fo as lo,gi as uo,go as fo,hi as po,ho as mo,ia as ho,ii as go,io as _o,ji as vo,jr as yo,ka as bo,kr as xo,la as So,lo as Co,ls as wo,m as To,mi as Eo,mo as Do,no as Oo,oa as ko,oi as Ao,oo as jo,p as Mo,pi as No,po as Po,qa as Fo,qi as Io,ri as Lo,ro as Ro,sa as zo,si as Bo,ti as Vo,to as Ho,uo as Uo,us as Wo,va as Go,vi as Ko,vo as qo,wi as X,wo as Jo,xa as Yo,xi as Xo,yo as Zo,zo as Qo,zr as $o}from"./extension-hook-Da3ATgkY.js";import{$ as es,A as ts,B as ns,C as rs,D as is,E as as,F as os,G as ss,H as cs,I as ls,J as us,K as ds,L as fs,M as ps,N as ms,O as hs,P as gs,Q as _s,R as vs,S as ys,T as bs,U as xs,V as Ss,W as Cs,X as ws,Y as Ts,Z as Es,_ as Ds,_t as Os,at as ks,b as As,bt as Z,c as js,ct as Ms,dt as Ns,et as Ps,f as Fs,ft as Is,g as Ls,gt as Rs,h as zs,ht as Bs,i as Vs,it as Hs,j as Us,k as Ws,l as Gs,lt as Ks,m as qs,mt as Js,nt as Ys,ot as Xs,p as Zs,pt as Qs,q as $s,rt as ec,s as tc,st as nc,tt as rc,u as ic,ut as ac,v as oc,vt as sc,w as cc,x as lc,y as uc,yt as dc,z as fc}from"./extensions-D2Z9guoO.js";import{i as pc}from"./document-BBvRlLC3.js";import{t as mc}from"./preload-helper-CfILh1TC.js";import{t as hc}from"./document-Bpcy9TTA.js";import{a as gc,i as _c,n as vc,r as yc,t as bc}from"./base-face-CsIbc1by.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Q=e(T(),1),xc=new WeakMap;function Sc(e,t){let n=!1,r=[];for(let i of t){let{availability:t,handler:a,...o}=i,s=a,c=t===void 0?o:{...o,availability:t()},l=xc.get(e)??new Map;xc.set(e,l);let u=l.get(i.id),d=()=>e.register(c,async({arguments:e,origin:t,signal:n})=>{let r=await s(e===void 0?{origin:t,signal:n}:{arguments:e,origin:t,signal:n});return r===void 0?void 0:Wo(r)}),f=(u?u.then(d):d()).then(e=>{n?e():r.push(e)},e=>{console.warn(`App command ${i.id} was not registered`,e)});l.set(i.id,f),f.finally(()=>{l.get(i.id)===f&&l.delete(i.id)})}return()=>{if(!n){n=!0;for(let e of r.splice(0))e()}}}_i(`light.dark.latte.mocha.readout.readout-night.field-guide.field-guide-night.embed.embed-dark.phosphor.codec.paper.ember.tide.tape.sunrise.pirate-radio.pirate-radio-night.consulting.consulting-ink.consulting-night.consulting-night-ink.consulting-riso-latte.consulting-riso-latte-ink.consulting-riso-glomzy.consulting-riso-glomzy-ink.vishnu.coin.coin-night.chamfer`.split(`.`));var Cc=`data-theme`;function wc(e){return e||(globalThis.document?.documentElement??null)}function Tc(e){let t=e.trim();if(t.length===0)throw TypeError(`Theme must be a non-empty string`);return t}function Ec(e,t){let n=Tc(e),r=wc(t);r&&r.setAttribute(Cc,n)}function Dc(e){return wc(e)?.getAttribute(Cc)??null}function Oc(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var kc=class extends on{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,dn.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!Fr(e,n)});!o&&!s||(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(Oc(e,n).forEach(e=>{e.destroy()}),Oc(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=Sr(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new Nn(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&dn.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},Ac=Q.createContext(!1),jc=()=>Q.useContext(Ac);Ac.Provider;var $=g();function Mc(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Nc=Q.createContext(Mc()),Pc=()=>Q.useContext(Nc),Fc=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?It(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Ic=e=>{Q.useEffect(()=>{e.clearReset()},[e])},Lc=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||It(n,[e.error,r])),Rc=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},zc=(e,t)=>e?.suspense&&t.isPending,Bc=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Vc({queries:e,...t},n){let r=He(n),i=jc(),a=Pc(),o=t.subscribed!==!1,s=Q.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:o?`optimistic`:void 0,t}),[e,r,i,o]);s.forEach(e=>{Rc(e);let t=r.getQueryCache().get(e.queryHash);Fc(e,a,t)}),Ic(a);let[c]=Q.useState(()=>new kc(r,s,t)),[l,u,d]=c.getOptimisticResult(s,t.combine),f=!i&&o;Q.useSyncExternalStore(Q.useCallback(e=>f?c.subscribe(dn.batchCalls(e)):Tt,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),Q.useEffect(()=>{c.setQueries(s,t)},[s,t,c]);let p=l.some((e,t)=>zc(s[t],e))?l.flatMap((e,t)=>{let n=s[t];return n&&zc(n,e)?Bc(n,new Nn(r,n),a):[]}):[];if(p.length>0)throw Promise.all(p);let m=l.find((e,t)=>{let n=s[t];return n&&Lc({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(m)throw m.error;return u(d())}function Hc(e,t,n){let r=jc(),i=Pc(),a=He(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Rc(o),Fc(o,i,s),Ic(i);let[l]=Q.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(Q.useSyncExternalStore(Q.useCallback(e=>{let t=d?l.subscribe(dn.batchCalls(e)):Tt;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Q.useEffect(()=>{l.setOptions(o)},[o,l]),zc(o,u))throw Bc(o,l,i);if(Lc({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function Uc(e,t){return Hc(e,Nn,t)}function Wc(e,t){let n=He(t),[r]=Q.useState(()=>new Xn(n,e));Q.useEffect(()=>{r.setOptions(e)},[r,e]);let i=Q.useSyncExternalStore(Q.useCallback(e=>r.subscribe(dn.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=Q.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(Tt)},[r]);if(i.error&&It(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var Gc=t((e=>{var t=On();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot}))();function Kc(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid keymap token: token cannot be empty`);return t}function qc(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid key name: key name cannot be empty`);return t}function Jc(e){return{name:qc(e.name),ctrl:e.ctrl??!1,shift:e.shift??!1,meta:e.meta??!1,super:e.super??!1,hyper:e.hyper||void 0}}function Yc(e){return{name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super,hyper:e.hyper||void 0}}function Xc(e,t){let n=Yc(Jc(e));return{stroke:n,display:t?.display??il(n),match:t?.match??el(n),tokenName:t?.tokenName?Kc(t.tokenName):void 0}}function Zc(e){return{stroke:Yc(e.stroke),display:e.display,match:e.match,tokenName:e.tokenName,patternName:e.patternName,payloadKey:e.payloadKey}}function Qc(e){return e.map(e=>Zc(e))}function $c(e){return`match`in e?e.match:`stroke`in e?el(e.stroke):el(e)}function el(e){return`key:${al(Jc(e))}`}function tl(e){let t=e.trim();if(!t)throw Error(`Invalid keymap match id: id cannot be empty`);return`text:${t}`}function nl(e,t){return`stroke`in e?t?.preferDisplay&&e.display?e.display:il(e.stroke):il(Jc(e))}function rl(e,t){return e.map(e=>nl(e,t)).join(t?.separator??``)}function il(e){let t=[];return e.ctrl&&t.push(`ctrl`),e.shift&&t.push(`shift`),e.meta&&t.push(`meta`),e.super&&t.push(`super`),e.hyper&&t.push(`hyper`),t.push(e.name===`return`?`enter`:e.name),t.join(`+`)}function al(e){return`${e.name}:${+!!e.ctrl}:${+!!e.shift}:${+!!e.meta}:${+!!e.super}:${+!!e.hyper}`}var ol=Symbol(`keymap-extension-context`);function sl(e){return e.isDestroyed?null:e.getFocusedTarget()}function cl(e,t,n){let r=t??e.rootTarget,i=t!==null;for(;r;){if(n(r,i)===!1)return;r=e.getParentTarget(r),i=!1}}function ll(e,t){let n=new Set;return cl(e,t,e=>{n.add(e)}),n}function ul(e,t,n){let r=[],i=ll(t,n),a=Array.isArray(e)?e:dl(e);for(let e of a)fl(t,e,n,i)&&r.push(e);return r}function dl(e){return[...e].sort((e,t)=>t.priority-e.priority||t.order-e.order)}function fl(e,t,n,r=ll(e,n)){let i=t.target;return i?e.isTargetDestroyed(i)?!1:t.targetMode===`focus`?i===n:r.has(i):!0}function pl(e){let t=e.binding.sequence[e.index];if(!t?.patternName)return 0;let n=e.patterns?.at(-1);return n?.name===t.patternName?n.values.length:0}function ml(e,t,n=!0){let r=e.binding.sequence[e.index];if(!r?.patternName)return!0;let i=t.get(r.patternName);return i?pl(e)>=i.min:n}function hl(e,t,n=!0){let r=e.binding.sequence[e.index];if(r?.patternName){let n=t.get(r.patternName);if(n&&pl(e)<n.max)return!0}return ml(e,t,n)&&e.index+1<e.binding.sequence.length}function gl(e,t){return e.index===e.binding.sequence.length-1&&ml(e,t,!1)}function _l(e,t,n,r){return{parent:e,depth:e?e.depth+1:0,stroke:t,match:n,pattern:r,children:new Map,patternChildren:[],bindings:[],reachableBindings:[]}}function vl(e,t){let n=_l(null,null,null);for(let r of e){if(r.event!==`press`)continue;let e=n;for(let n of r.sequence){let i;if(n.patternName){let r=t.get(n.patternName);i=e.patternChildren.find(e=>e.pattern?.name===n.patternName),i||(i=_l(e,n.stroke,n.match,r),e.patternChildren.push(i))}else i=e.children.get(n.match),i||(i=_l(e,n.stroke,n.match),e.children.set(n.match,i));i.reachableBindings.push(r),e=i}e.bindings.push(r)}return n}function yl(e,t){let n=[];for(let r of e){if(!ml(r,t))continue;let e=r.index+1,i=r.binding.sequence[e];i&&n.push({part:i,binding:r.binding,index:e,exact:e===r.binding.sequence.length-1,continues:e<r.binding.sequence.length-1})}return n}function bl(e,t,n,r){let i=n.patternName;if(!i)return{...e,index:t};let a=[...e.patterns??[]],o=a.at(-1);return o?.name===i?a[a.length-1]={...o,values:[...o.values,r],parts:[...o.parts,n]}:a.push({name:i,payloadKey:n.payloadKey??i,values:[r],parts:[n]}),{layer:e.layer,binding:e.binding,index:t,parts:[...e.parts,n],patterns:a}}function xl(e,t){let n=e.parts.at(-1);if(!n||n.patternName)return t.length;let r=t.indexOf(n.match);return r===-1?t.length:r}function Sl(e,t,n,r,i,a,o,s,c){let l=t.sequence[n];if(l){if(l.patternName){let a=s(l.patternName,o);if(!a)return;let u=c(o,l.patternName,a);return bl({layer:e,binding:t,index:n,parts:r,patterns:i},n,u,a.value??o.name)}if(a.includes(l.match))return{layer:e,binding:t,index:n,parts:[...r,l],patterns:i}}}function Cl(e,t,n,r,i,a){let o=e.binding.sequence[e.index];if(o?.patternName){let s=r.get(o.patternName);if(s&&pl(e)<s.max){let t=i(s.name,n);if(t){let r=a(n,s.name,t);return bl(e,e.index,r,t.value??n.name)}}return ml(e,r,!1)?Sl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a):void 0}return Sl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a)}function wl(e,t,n,r,i){let a=[],o=1/0;for(let s of e.bindings){if(s.event!==`press`)continue;let c=Sl(e,s,0,[],void 0,t,n,r,i);if(!c)continue;let l=xl(c,t);l<o&&(o=l,a.length=0),l===o&&a.push(c)}return a}import.meta.require;function Tl(e){let t=Object.create(null),n=(e,n)=>{let r=t[e];if(!r)return;let i=r.filter(e=>e!==n);i.length===0?delete t[e]:i.length!==r.length&&(t[e]=i)};return{hook(e,r){return t[e]=[...t[e]??[],r],()=>n(e,r)},has(e){return(t[e]?.length??0)>0},emit(n,...r){let i=t[n];if(i)for(let t of i)try{r.length===0?t():t(r[0])}catch(t){e(n,t)}}}}function El(){let e=[];return{get:()=>e,set:t=>{e=t},remove(t){e=e.filter(e=>e!==t)},has:()=>e.length>0,clear:()=>{e=[]}}}function Dl(){let e=El();return{append(t){return e.set([...e.get(),t]),()=>e.remove(t)},prepend(t){return e.set([t,...e.get()]),()=>e.remove(t)},values:e.get,has:e.has,clear:e.clear}}function Ol(){let e=El(),t=0;return{register(n,r){let i={...r,listener:n,order:t++};return e.set([...e.get(),i].sort((e,t)=>t.priority-e.priority||e.order-t.order)),()=>e.remove(i)},entries:e.get,has:e.has,clear:e.clear}}function kl(e){return typeof e==`string`||!!e&&typeof e==`object`&&!Array.isArray(e)}function Al(e){if(!Array.isArray(e))return{ok:!1,reason:`Invalid keymap bindings: expected an array of binding objects`};for(let[t,n]of e.entries()){if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected a binding object`};if(!kl(n.key))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected "key" to be a string or keystroke object`}}return{ok:!0}}function jl(e){let t=Al(e);if(!t.ok)throw Error(t.reason);return e.map(e=>({...e,key:typeof e.key==`string`?e.key:{...e.key}}))}function Ml(e){return{...e,sequence:Qc(e.sequence)}}function Nl(e,t){let n=Dl();return{prependLayerAnalyzer(e){return n.prepend(e)},appendLayerAnalyzer(e){return n.append(e)},clearLayerAnalyzers(){n.clear()},analyzeLayer(r){let i=n.values();if(i.length===0)return;let a=Pl(r.bindings),o={target:r.target,order:r.order,sourceBindings:r.sourceBindings,bindings:a,hasTokenBindings:r.hasTokenBindings,checkCommandResolution(e){return t.getCommandResolutionStatus(e,r.commands)},warn(t,n,r){e.emitWarning(t,n,r)},warnOnce(t,n,r,i){e.warnOnce(t,n,r,i)},error(t,n,r){e.emitError(t,n,r)}};for(let t of i)try{t(o)}catch(t){e.emitError(`layer-analyzer-error`,t,`[Keymap] Error in layer analyzer:`)}}}}function Pl(e){return e.map(t=>({sequence:Qc(t.sequence),command:t.command,attrs:t.attrs,event:t.event,preventDefault:t.preventDefault,fallthrough:t.fallthrough,parsedBinding:Ml(t.parsedBinding),sourceTarget:t.sourceTarget,sourceLayerOrder:t.sourceLayerOrder,bindingIndex:t.bindingIndex,hasCommandAtSequence:e.some(e=>e.event===`press`&&e.command!==void 0&&Fl(e,t)),hasContinuations:e.some(e=>e.event===`press`&&Il(t,e))}))}function Fl(e,t){return e.sequence.length===t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function Il(e,t){return e.sequence.length<t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function Ll(){return{version:-1,notifyVersion:-1,focused:void 0,value:[],targets:new WeakMap}}function Rl(){return{plain:Ll(),bindings:Ll(),metadata:Ll(),bindingsAndMetadata:Ll()}}function zl(e,t){if(t===void 0)return e.plain;let n=t.includeBindings===!0,r=t.includeMetadata===!0;return n?r?e.bindingsAndMetadata:e.bindings:r?e.metadata:e.plain}function Bl(e,t,n){let r=n?e.targets.get(n):e.nullTarget;return r?.version===t?r:void 0}function Vl(e,t,n,r){let i={version:t,value:r};n?e.targets.set(n,i):e.nullTarget=i}function Hl(e,t){if(e===t)return!0;if(!e||!t||e.captures.length!==t.captures.length)return!1;for(let n=0;n<e.captures.length;n+=1){let r=e.captures[n],i=t.captures[n];if(!r||!i||r.layer!==i.layer||r.binding!==i.binding||r.index!==i.index||r.parts.length!==i.parts.length)return!1;for(let e=0;e<r.parts.length;e+=1)if(r.parts[e]?.match!==i.parts[e]?.match)return!1;let a=r.patterns??[],o=i.patterns??[];if(a.length!==o.length)return!1;for(let e=0;e<a.length;e+=1){let t=a[e],n=o[e];if(!t||!n||t.name!==n.name||t.values.length!==n.values.length)return!1;for(let e=0;e<t.values.length;e+=1)if(!Object.is(t.values[e],n.values[e]))return!1}}return!0}function Ul(e){let t=e.parts.at(-1);if(!t||e.parts.length<=1)return;let n=e.index-1,r=e.patterns;if(t.patternName){let i=r?.at(-1);i?.name===t.patternName&&(i.values.length>1?(n=e.index,r=[...(r??[]).slice(0,-1),{...i,values:i.values.slice(0,-1),parts:i.parts.slice(0,-1)}]):r=(r??[]).slice(0,-1))}return{layer:e.layer,binding:e.binding,index:n,parts:e.parts.slice(0,-1),patterns:r}}function Wl(e){let t=e.captures[0];if(!t||t.parts.length===0)return[];let n=[];for(let r=0;r<t.parts.length;r+=1){let i=t.parts[r];if(!i)continue;let a,o,s=!1,c=!1;for(let t of e.captures){let e=t.parts[r];if(e){if(a===void 0){a=e.display,o=e.tokenName;continue}!s&&a!==e.display&&(s=!0),!c&&o!==e.tokenName&&(c=!0)}}(a===void 0||s)&&(a=nl(i.stroke)),c&&(o=void 0),n.push(Xc(i.stroke,{display:a,match:i.match,tokenName:o}))}return n}function Gl(e){if(e.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);return e}function Kl(e,t,n,r,i,a,o={}){let s=Rl(),c=-1,l=[],u=()=>Gl(t).getFocusedTarget(),d=()=>sl(t),f=t=>{let n=e.pending;Hl(n,t)||(e.pending=t,o.onPendingSequenceChanged?.(n,t),ae(),r.queueStateChange())},p=()=>{let t=e.pending;if(!t)return;let n=u(),r=a.getActiveCommandView(n),o=t.captures.filter(t=>e.layers.has(t.layer)&&C(t.layer,n)&&i.matchesConditions(t.layer)&&D(t.binding,n,r)&&hl(t,e.patterns));if(o.length===0){f(null);return}return o.length!==t.captures.length&&f({captures:o}),e.pending??void 0},m=()=>{t.isDestroyed||!e.pending||p()},h=()=>!t.isDestroyed&&e.pending!==null,g=()=>{if(c===e.cacheVersion)return l;let t=p(),n=t?Wl(t):[];return(!t||T())&&(c=e.cacheVersion,l=n),n},_=()=>{let e=p();if(!e)return!1;let t=e.captures[0];if(!t||t.parts.length<=1)return f(null),!0;let n=[];for(let t of e.captures){let e=Ul(t);e&&n.push(e)}return n.length===0?(f(null),!0):(f({captures:n}),!0)},v=t=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=zl(s,t);return i.notifyVersion===e.derivedVersion?i.value:y(i,n,r)},y=(n,r,i)=>{t.isDestroyed&&Gl(t);let o=u(),s=Bl(n,e.cacheVersion,o);if(s)return n.notifyVersion=e.derivedVersion,n.version=e.cacheVersion,n.focused=o,n.value=s.value,s.value;let c=a.getActiveCommandView(o),l=p(),d=l?[]:S(o),f=l?te(l.captures,r,i,o,c):j(d,r,i,o,c);return(l?T():w(d))&&(n.version=e.cacheVersion,n.notifyVersion=e.derivedVersion,n.focused=o,n.value=f,Vl(n,e.cacheVersion,o,f)),f},b=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=u(),o=a.getActiveCommandView(i);return te(e,n,r,i,o)},x=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=e===d()?p():void 0,o=a.getActiveCommandView(e);return i?te(i.captures,n,r,e,o):j(S(e),n,r,e,o)},S=n=>e.activeLayersCacheVersion===e.cacheVersion&&e.activeLayersCacheFocused===n?e.activeLayersCache:(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=n,e.activeLayersCache=ul(e.sortedLayers,t,n),e.activeLayersCache),C=(e,n)=>fl(t,e,n),w=t=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,T=()=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,E=(e,t,n)=>{let r=[];for(let o of e)i.matchesConditions(o)&&a.isBindingVisible(o,t,n)&&r.push(o);return r},D=(e,t,n)=>i.matchesConditions(e)&&a.isBindingVisible(e,t,n),O=(e,t)=>{let n,r,i=!1,a=!1;for(let o of e){let e=o.sequence[t];if(e){if(n===void 0){n=e.display,r=e.tokenName;continue}!i&&n!==e.display&&(i=!0),!a&&r!==e.tokenName&&(a=!0)}}if(n===void 0||i){let r=e[0]?.sequence[t]?.stroke;n=r?nl(r):``}return a&&(r=void 0),{display:n,tokenName:r}},k=(e,t,n)=>({sequence:e.sequence,command:e.command,commandAttrs:a.getBindingCommandAttrs(e,t,n),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),A=(e,t,n)=>e.map(e=>k(e,t,n)),j=(e,t,n,r,a)=>{let o=new Map,s=new Set;for(let n of e)n.root.children.size===0&&n.root.patternChildren.length===0||!i.matchesConditions(n)||(M(n.root.children.values(),o,s,t,r,a),M(n.root.patternChildren,o,s,t,r,a));return F(o,t,n,r,a)},M=(e,t,n,r,i,a)=>{for(let o of e){let e=o.match;if(!e||n.has(e)||!o.stroke)continue;let s=N(o,r,i,a);if(!s)continue;let c=t.get(e);c?z(c,s,r):t.set(e,R(o.stroke,s,r)),s.stop&&n.add(e)}},N=(e,t,n,r)=>{if(!(e.children.size>0||e.patternChildren.length>0)){let i=L(ee(e)?E(e.bindings,n,r):e.bindings,n,r);if(!i)return;let a=O(i.bindings,e.depth-1);return{display:a.display,tokenName:a.tokenName,continues:!1,firstBinding:i.bindings[0],commandBinding:i.commandBinding,bindings:t?[...i.bindings]:void 0,stop:i.stop}}let i=E(e.reachableBindings,n,r);if(i.length===0)return;let a=L(e.bindings,n,r),o=O(i,e.depth-1);return{display:o.display,tokenName:o.tokenName,continues:!0,firstBinding:a?.bindings[0],commandBinding:a?.commandBinding,bindings:t&&a?[...a.bindings]:void 0,stop:!0}},ee=t=>{if(e.commandResolvers.has())return!0;for(let e of t.bindings)if(e.matchers.length>0)return!0;return!1},te=(t,n,r,i,a)=>{let o=new Map,s=new Set;return ne(yl(t,e.patterns),o,s,n,i,a),F(o,n,r,i,a)},ne=(e,t,n,r,i,a)=>{let o=new Set;for(let s of e)o.has(s.part.match)||(o.add(s.part.match),P(s,e,t,n,r,i,a))},P=(e,t,n,r,i,a,o)=>{let s=e.part.match;if(r.has(s))return;let c=re(e,t,i,a,o);if(!c)return;let l=n.get(s);l?z(l,c,i):n.set(s,R(e.part.stroke,c,i)),c.stop&&r.add(s)},F=(e,t,n,r,i)=>{let a=[];for(let o of e.values()){let e=ie(o,t,n,r,i);e&&a.push(e)}return a},re=(e,t,n,r,i)=>{let a=t.filter(t=>t.part.match===e.part.match),o=a.filter(e=>e.exact).map(e=>e.binding),s=L(o,r,i),c=a.some(e=>e.continues);if(!c&&!s)return;let l=I(a);return{display:l.display,tokenName:l.tokenName,continues:c,firstBinding:s?.bindings[0],commandBinding:s?.commandBinding,bindings:n&&s?[...s.bindings]:void 0,stop:c||s?.stop===!0}},I=e=>{let t,n,r=!1,i=!1;for(let a of e){let e=a.part;if(t===void 0){t=e.display,n=e.tokenName;continue}!r&&t!==e.display&&(r=!0),!i&&n!==e.tokenName&&(i=!0)}let a=e[0]?.part;return(t===void 0||r)&&(t=a?nl(a.stroke):``),i&&(n=void 0),{display:t,tokenName:n}},L=(e,t,n)=>{let r=[],o;for(let s of e)if(!(!i.matchesConditions(s)||!a.isBindingVisible(s,t,n))&&(r.push(s),s.command!==void 0&&(o??=s,!s.fallthrough)))return{bindings:r,commandBinding:o,stop:!0};if(r.length!==0)return{bindings:r,commandBinding:o,stop:!1}},R=(e,t,n)=>({stroke:e,display:t.display,tokenName:t.tokenName,continues:t.continues,firstBinding:t.firstBinding,commandBinding:t.commandBinding,bindings:n&&t.bindings?[...t.bindings]:void 0}),z=(e,t,n)=>{if(!e.firstBinding&&t.firstBinding&&(e.firstBinding=t.firstBinding),!e.commandBinding&&t.commandBinding&&(e.commandBinding=t.commandBinding),t.continues&&(e.continues=!0),!(!n||!t.bindings||t.bindings.length===0)){if(!e.bindings){e.bindings=[...t.bindings];return}e.bindings.push(...t.bindings)}},ie=(e,t,n,r,i)=>{if(!e.commandBinding&&!e.continues)return;let o={stroke:Yc(e.stroke),display:e.display,continues:e.continues};if(e.tokenName&&(o.tokenName=e.tokenName),e.commandBinding&&(o.command=e.commandBinding.command),t&&e.bindings&&e.bindings.length>0&&(o.bindings=e.bindings.length===1?[k(e.bindings[0],r,i)]:A(e.bindings,r,i)),n){e.firstBinding?.attrs&&(o.bindingAttrs=e.firstBinding.attrs);let t=e.commandBinding?a.getBindingCommandAttrs(e.commandBinding,r,i):void 0;t&&(o.commandAttrs=t)}return o},ae=()=>{n.has(`pendingSequence`)&&n.emit(`pendingSequence`,e.pending?Wl(e.pending):[])};return{getFocusedTarget:u,getFocusedTargetIfAvailable:d,setPendingSequence:f,ensureValidPendingSequence:p,revalidatePendingSequenceIfNeeded:m,hasPendingSequenceState:h,getPendingSequence:g,popPendingSequence:_,getActiveKeys:v,getActiveKeysForCaptures:b,getActiveKeysForFocused:x,getActiveLayers:S,isLayerActiveForFocused:C,collectSequencePartsFromPending:Wl,collectMatchingBindings:E,collectActiveBindings:A}}var ql=new Set([`name`,`run`,`fields`,`attrs`,`rejectedResult`]),Jl=new Set([`key`,`cmd`,`event`,`preventDefault`,`fallthrough`]),Yl=new Set([`target`,`targetMode`,`priority`,`bindings`,`commands`]);function Xl(e){if(e===void 0||typeof e==`function`)return e;let t=e.trim();if(!t)throw Error(`Invalid keymap command: command cannot be empty`);return t}function Zl(e){let t=e.trim();if(!t)throw Error(`Invalid keymap command name: name cannot be empty`);if(/\s/.test(t))throw Error(`Invalid keymap command name "${e}": command names cannot contain whitespace`);return t}function Ql(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function $l(e){let t=[],n=new Map;for(let r of e.layers)for(let e of r.commands){let i={layer:r,commandState:e};t.push(i),Ql(n,e.command.name,i)}return{entries:t,chainsByName:n}}function eu(e,t,n){let r=[],i=[],a=new Map,o=new Map;for(let s of e)if(s.commands.length!==0&&!(n&&!t.matchesConditions(s)))for(let e of s.commands){if(!t.matchesConditions(e))continue;let n={layer:s,commandState:e};r.push(n),Ql(o,e.command.name,n),a.has(e.command.name)||(a.set(e.command.name,n),i.push(n))}return{layers:e,entries:r,reachable:i,reachableByName:a,chainsByName:o}}function tu(e,t,n,r){return(e.activeLayersCacheVersion!==e.cacheVersion||e.activeLayersCacheFocused!==r)&&(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=r,e.activeLayersCache=ul(e.sortedLayers,t,r)),eu(e.activeLayersCache,n,!0)}function nu(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap requirement for "${t}" from ${r}`);e[t]=n}function ru(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap attribute for "${t}" from ${r}`);e[t]=n}function iu(e){let t=`field ${e.fieldName}`;return{require(n,r){nu(e.requirements,n,r,t)},attr(n,r){if(!e.attrs)throw Error(`Keymap ${t} cannot publish attrs`);ru(e.attrs,n,r,t)},activeWhen(n){e.matchers.push(e.conditions.buildRuntimeMatcher(n,t))}}}function au(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ou(e,t){return e instanceof Error&&e.message?e.message:t}function su(e){return!e||typeof e!=`object`&&typeof e!=`function`?!1:typeof e.then==`function`}function cu(e,t){let n=t?.deep===!0,r=t?.freeze===!0,i=t?.preserveNonPlainObjects===!0;if(Array.isArray(e)){let i=n?e.map(e=>cu(e,t)):[...e];return r?Object.freeze(i):i}if(e&&typeof e==`object`){if(i&&!au(e))return e;let a={};for(let[r,i]of Object.entries(e))a[r]=n?cu(i,t):i;return r?Object.freeze(a):a}return e}var lu=[`name`],uu=Object.freeze({}),du=new WeakMap;function fu(e,t,n,r,i){let a=-1,o,s=-1,c,l,u=-1,d,f,p=-1,m,h=-1,g=new Map,_=t=>mu({commands:t,commandFields:e.commandFields,conditions:r,onError:(e,t,r)=>{n.emitError(e,t,r)}}),v=t=>F(()=>e.commandResolvers.prepend(t),t),y=t=>F(()=>e.commandResolvers.append(t),t),b=()=>{e.commandResolvers.has()&&n.runWithStateChangeBatch(()=>{e.commandResolvers.clear(),i.onCommandResolversChanged(),n.queueStateChange()})},x=e=>se(e).map(e=>pu(e.commandState)),S=e=>{let t=oe(e),n=se(e,t);if(n.length===0)return[];let r=n.map(e=>({entry:e,command:pu(e.commandState),commandAttrs:e.commandState.attrs,bindings:[]})),i=new Map;for(let[e,t]of r.entries()){let n=i.get(t.command.name);n?n.push(e):i.set(t.command.name,[e])}return i.size>0&&B(r,i,t),r.map(e=>({command:e.command,bindings:e.bindings}))},C=t=>{if(t.visibility===`registered`&&u===e.derivedVersion&&d===t.commands&&f)return f;let n=new Map;for(let e of t.commands)n.has(e)||n.set(e,[]);return n.size===0?n:(ce(n,oe(t)),t.visibility===`registered`&&(u=e.derivedVersion,d=t.commands,f=n),n)},w=(e,t,n)=>{let r=M(t);if(n){let i=[],a=r.chainsByName.get(e);if(a)for(let e of a)i.push({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs,payload:n.payload});let o=fe(e,t,{mode:`active`,execution:n});return o.resolved&&i.push(o.resolved),{entries:i.length>0?i:void 0,hadError:o.hadError}}let i=[];for(let t of r.chainsByName.get(e)??[])i.push({target:t.layer.target,command:t.commandState.command,attrs:t.commandState.attrs});let a=fe(e,t,{mode:`active`});return a.resolved&&i.push(a.resolved),{entries:i.length>0?i:void 0,hadError:a.hadError}},T=t=>{if(h!==e.derivedVersion&&(h=e.derivedVersion,g=new Map),g.has(t))return g.get(t)??void 0;let n=R(L(t));return g.set(t,n??null),n},E=(e,t)=>R(M(t).chainsByName.get(e)),D=(e,t)=>fe(e,null,{mode:`registered`,execution:t}),O=(e,t,n)=>fe(e,t,{mode:`active`,execution:n}),k=(e,t)=>re(e,t)?.command,A=e=>I(e)?.commandState.command,j=(e,n,i)=>{let a=N().chainsByName.get(e);if(!a||a.length===0)return;let o,s;for(let e of a){if(!fl(t,e.layer,n)){o??=e;continue}(!r.matchesConditions(e.layer)||!r.matchesConditions(e.commandState))&&(s??=e)}let c=s??o;if(c)return{reason:s?`disabled`:`inactive`,command:i?c.commandState.command:void 0}},M=n=>{if(s===e.derivedVersion&&c===n&&l)return l;let i=tu(e,t,r,n);return ee()&&(s=e.derivedVersion,c=n,l=i),i},N=()=>a===e.derivedVersion&&o?o:(a=e.derivedVersion,o=$l(e),o),ee=()=>e.activeCommandViewCacheBlockers===0,te=(e,t,n)=>e.command===void 0||e.run?!0:typeof e.command==`string`?n.reachableByName.has(e.command)?!0:z(e.command,t,`active`)!==void 0:!1,ne=(e,t,n)=>{if(typeof e.command!=`string`)return;let r=n.reachableByName.get(e.command);return r?r.commandState.attrs:z(e.command,t,`active`)?.attrs},P=(e,n)=>{if(n?.some(t=>t.command.name===e)||N().chainsByName.has(e))return`resolved`;let r=fe(e,sl(t));return r.resolved||r.hadError?r.resolved?`resolved`:`error`:`unresolved`},F=(t,r)=>n.runWithStateChangeBatch(()=>{let a=t();return i.onCommandResolversChanged(),n.queueStateChange(),()=>{n.runWithStateChangeBatch(()=>{a(),!e.commandResolvers.values().includes(r)&&(i.onCommandResolversChanged(),n.queueStateChange())})}}),re=(e,t)=>{let n=M(t).reachableByName.get(e);return n?{target:n.layer.target,command:n.commandState.command,attrs:n.commandState.attrs}:z(e,t,`active`)},I=e=>L(e)?.[0],L=t=>{let n=[];for(let r of e.sortedLayers)for(let e of r.commands)e.command.name===t&&n.push({layer:r,commandState:e});return n.length>0?n:void 0},R=e=>{if(e?.length)return e.map(e=>({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs}))},z=(e,t,n)=>fe(e,t,{mode:n}).resolved,ie=()=>N().entries,ae=()=>{if(p===e.derivedVersion&&m)return m;let t=new Map;for(let n of e.layers)for(let e of n.bindings){if(typeof e.command!=`string`)continue;let n=t.get(e.command);n?n.push(e):t.set(e.command,[e])}return p=e.derivedVersion,m=t,t},oe=e=>{let n=e?.visibility??`reachable`,r=e&&Object.prototype.hasOwnProperty.call(e,`focused`)?e.focused??null:sl(t);return n===`registered`?{visibility:n,focused:r}:{visibility:n,focused:r,activeView:M(r)}},se=(e,t=oe(e))=>{let r;return r=t.visibility===`registered`?ie():t.visibility===`active`?t.activeView?.entries??[]:t.activeView?.reachable??[],yu({entries:r,query:e,getCommand:e=>pu(e),onFilterError:e=>{n.emitError(`command-query-filter-error`,e,`[Keymap] Error in command query filter:`)}})},B=(e,t,n)=>{le(n,n=>{ue(e,t,n)})},ce=(e,t)=>{if(t.visibility===`registered`){let t=ae();for(let[n,r]of e){let e=N().chainsByName.get(n)?.[0]?.commandState.attrs;for(let i of t.get(n)??[])r.push(de(i,e))}return}le(t,n=>{V(e,n,t)})},le=(t,n)=>{if(t.visibility===`registered`){for(let t of e.layers)for(let e of t.bindings)n(e);return}let i=t.activeView;if(i){for(let e of i.layers)if(!(e.bindings.length===0||!r.matchesConditions(e)))for(let a of e.bindings)r.matchesConditions(a)&&te(a,t.focused,i)&&n(a)}},ue=(e,t,n)=>{if(typeof n.command!=`string`)return;let r=t.get(n.command);if(!(!r||r.length===0))for(let t of r){let r=e[t];r&&r.bindings.push(de(n,r.commandAttrs))}},V=(e,t,n)=>{if(typeof t.command!=`string`)return;let r=e.get(t.command);r&&r.push(de(t,H(t,n)))},de=(e,t)=>({sequence:e.sequence,command:e.command,commandAttrs:t,attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),H=(e,t)=>{if(typeof e.command!=`string`)return;if(t.visibility===`registered`)return N().chainsByName.get(e.command)?.[0]?.commandState.attrs;let n=t.activeView;if(n)return ne(e,t.focused,n)},fe=(t,r,i)=>{let a=i?.mode??`active`,o=i?.execution??{input:t},s=hu(t,e.commandResolvers.values(),()=>he(r,a,o),e=>{n.emitError(`command-resolver-error`,e,`[Keymap] Error in command resolver for "${t}":`)}),c=s.resolved;if(c){let e=me(c.command.name,r,a);e?.commandState.command===c.command&&c.target===void 0&&(c={...c,target:e.layer.target},s.resolved=c)}if(c&&!c.attrs){let e=pe(c.command.name,r,a)??vu(c.command);e&&(s.resolved={...c,attrs:e})}return s},pe=(e,t,n)=>n===`registered`?I(e)?.commandState.attrs:M(t).reachableByName.get(e)?.commandState.attrs,me=(e,t,n)=>n===`registered`?I(e):M(t).reachableByName.get(e),he=(e,t,n)=>{let r=n.input,i=n.payload;return{context:{get input(){return r},get payload(){return i},setInput(e){r=e},setPayload(e){i=e},getCommand:n=>t===`registered`?A(n):k(n,e)},getExecutionFields(){return{input:r,payload:i}}}};return{normalizeCommands:_,prependCommandResolver:v,appendCommandResolver:y,clearCommandResolvers:b,getCommands:x,getCommandEntries:S,getCommandBindings:C,getResolvedCommandChain:w,getRegisteredResolvedEntries:T,getActiveRegisteredResolvedEntries:E,resolveRegisteredResolverFallback:D,resolveActiveResolverFallback:O,getTopCommand:k,getDispatchUnavailableCommandState:j,getActiveCommandView:M,isBindingVisible:te,getBindingCommandAttrs:ne,getCommandResolutionStatus:P}}function pu(e){return e.command}function mu(e){let t=[],n=new Set;for(let r of e.commands)try{let i={},a=[],o=Zl(r.name),s=gu(r),c={};if(n.has(o)){e.onError(`duplicate-command`,{command:o},`Duplicate keymap command "${o}" in the same layer`);continue}r.name=o;for(let[t,n]of Object.entries(s)){if(n===void 0)continue;let r=e.commandFields.get(t);r&&r(n,iu({fieldName:t,conditions:e.conditions,requirements:i,matchers:a,attrs:c}))}let l={command:r,fields:s,attrs:Object.keys(c).length===0?void 0:c,requires:Object.entries(i),matchers:a};n.add(l.command.name),t.push(l)}catch(t){e.onError(`register-command-failed`,t,ou(t,`Failed to register keymap command "${String(r.name)}"`));continue}return t}function hu(e,t,n,r){if(t.length===0)return{hadError:!1};let i=!1;for(let a of t){let t,o=n();try{t=a(e,o.context)}catch(e){i=!0,r(e);continue}if(t)return{hadError:i,resolved:_u(t,o.getExecutionFields())}}return{hadError:i}}function gu(e){let t={};for(let[n,r]of Object.entries(e))!ql.has(n)&&r!==void 0&&(t[n]=r);return Object.keys(t).length===0?uu:t}function _u(e,t){return{command:e,input:t.input,payload:t.payload}}function vu(e){let t=gu(e);return t===uu?void 0:t}function yu(e){let t=e.query?.namespace,n=bu(e.query?.limit);if(n===0)return[];let r=e.query?.search?.trim().toLowerCase()??``,i=lu;e.query?.searchIn&&e.query.searchIn.length>0&&(i=e.query.searchIn);let a=e.query?.filter,o,s,c;if(typeof a==`function`)s=a;else if(a){let e=Object.entries(a),t=[];for(let[n,r]of e){if(n===`name`){if(typeof r==`string`){c=new Set([r]);continue}if(Array.isArray(r)){let e=new Set;for(let t of r)typeof t==`string`&&e.add(t);c=e;continue}}t.push([n,r])}o=t.length>0?t:void 0}let l=[];for(let a of e.entries){let u=a.commandState;if(Su(u,t)&&xu(u,r,i)&&!(c&&!c.has(u.command.name))&&Cu(u,o,e)){if(s){let t=!1;try{t=s(e.getCommand(u))}catch(t){e.onFilterError(t);continue}if(!t)continue}if(l.push(a),n!==void 0&&l.length>=n)break}}return l}function bu(e){if(e===void 0)return;let t=Math.floor(Number(e));return!Number.isFinite(t)||t<=0?0:t}function xu(e,t,n){if(!t)return!0;for(let r of n)if(wu(e,r,t))return!0;return!1}function Su(e,t){if(t===void 0)return!0;let n=e.fields;return Object.prototype.hasOwnProperty.call(n,`namespace`)?ju(n.namespace,t):!1}function Cu(e,t,n){if(!t)return!0;for(let[r,i]of t)if(!Ou(e,r,i,n))return!1;return!0}function wu(e,t,n){return Tu(e,t)?.includes(n)===!0}function Tu(e,t){let n=du.get(e);if(n||(n=new Map,du.set(e,n)),n.has(t))return n.get(t);let r=e.fields,i=e.attrs,a;t===`name`?a=e.command.name:Object.prototype.hasOwnProperty.call(r,t)?a=r[t]:i&&Object.prototype.hasOwnProperty.call(i,t)&&(a=i[t]);let o=Eu(a);return n.set(t,o),o}function Eu(e){if(Array.isArray(e)){let t=[];for(let n of e){let e=Eu(n);e!==void 0&&t.push(e)}return t.length>0?t.join(`\0`):void 0}if(typeof e==`string`)return e.toLowerCase();if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e).toLowerCase()}function Du(e,t,n,r){try{return e(t,n)}catch(e){return r(e),!1}}function Ou(e,t,n,r){return typeof n==`function`?ku(e,t,n,r):Au(e,t,n)}function ku(e,t,n,r){let i=e.command,a=e.fields,o=e.attrs,s,c=!1,l=()=>s??=r.getCommand(e);return t===`name`&&(c=!0,Du(n,i.name,l(),r.onFilterError))||Object.prototype.hasOwnProperty.call(a,t)&&(c=!0,Du(n,a[t],l(),r.onFilterError))||o&&Object.prototype.hasOwnProperty.call(o,t)&&(c=!0,Du(n,o[t],l(),r.onFilterError))?!0:!c&&Du(n,void 0,l(),r.onFilterError)}function Au(e,t,n){let r=e.command,i=e.fields,a=e.attrs;return t===`name`&&ju(r.name,n)||Object.prototype.hasOwnProperty.call(i,t)&&ju(i[t],n)?!0:!!a&&Object.prototype.hasOwnProperty.call(a,t)&&ju(a[t],n)}function ju(e,t){return Array.isArray(t)?t.some(t=>Mu(e,t)):Mu(e,t)}function Mu(e,t){return Array.isArray(e)?e.some(e=>Mu(e,t)):Object.is(e,t)}function Nu(e,t,n,r,i){let a=(e,t,n,r,a,o)=>({keymap:i.keymap,event:e,focused:t,target:n,data:r,input:a,payload:o}),o=(t,n,r,i)=>{let a=typeof n==`function`?void 0:n,o=typeof n==`function`?n:n.run,s=i?a:void 0,c;try{c=o(a?{...r,command:a}:r)}catch(n){return e.emitError(`command-execution-error`,n,`[Keymap] Error running command "${t}":`),{status:`error`,result:s?{ok:!1,reason:`error`,command:s}:{ok:!1,reason:`error`}}}if(su(c))return c.catch(n=>{e.emitError(`async-command-error`,n,`[Keymap] Async error in command "${t}":`)}),{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}};if(Pu(c)){let e=c;return(!c.ok&&c.reason!==`not-found`&&i&&a&&!c.command||c.ok&&i&&a&&!c.command)&&(e={...c,command:a}),{status:c.ok?`handled`:`rejected`,result:e}}return c===!1?{status:`rejected`,result:s?{ok:!1,reason:`rejected`,command:s}:{ok:!1,reason:`rejected`}}:{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}}},s=(e,t,n,r,i,s,c,l)=>{let u;for(let d of t??[]){let t=o(e,d.command,a(n,r,i??d.target??null,s,e,c),l);if(t.status===`handled`||t.status===`error`)return[t.result,u];u=t.result}return[void 0,u]},c=(e,c,l)=>{let u;try{u=Xl(e)}catch{return{ok:!1,reason:`invalid-args`}}if(typeof u!=`string`)return{ok:!1,reason:`not-found`};let d=c?.includeCommand===!0,f=c?.focused??n.getFocusedTargetIfAvailable(),p=c?.event??i.createCommandEvent(),m=t.getReadonlyData(),h=c?.payload,g=l===`registered`?r.getRegisteredResolvedEntries(u):r.getActiveRegisteredResolvedEntries(u,f),[_,v]=s(u,g,p,f,c?.target,m,h,d);if(_)return _;let y=v,b=l===`registered`?r.resolveRegisteredResolverFallback(u,{input:u,payload:h}):r.resolveActiveResolverFallback(u,f,{input:u,payload:h});if(b.resolved){let e=o(u,b.resolved.command,a(p,f,c?.target??b.resolved.target??null,m,b.resolved.input??u,b.resolved.payload),d);if(e.status===`handled`||e.status===`error`)return e.result;y=e.result}if(b.hadError)return{ok:!1,reason:`error`};if(l===`active`){let e=r.getDispatchUnavailableCommandState(u,f,d);if(e)return e.command?{ok:!1,reason:e.reason,command:e.command}:{ok:!1,reason:e.reason}}return y??{ok:!1,reason:`not-found`}};return{runCommand(e,t){return c(e,t,`registered`)},dispatchCommand(e,t){return c(e,t,`active`)},runBinding(e,n,i,s,c){let l=t.getReadonlyData();if(n.run)return o(typeof n.command==`string`?n.command:`<function>`,n.run,a(i,s,e.target??null,l,typeof n.command==`string`?n.command:`<function>`,c),!1).status!==`rejected`&&(Fu(n,i),!0);if(typeof n.command!=`string`)return!1;let u=r.getResolvedCommandChain(n.command,s,c===void 0?void 0:{input:n.command,payload:c}).entries;for(let t of u??[])if(o(n.command,t.command,a(i,s,t.target??e.target??null,l,t.input??n.command,t.payload),!1).status!==`rejected`)return Fu(n,i),!0;return!1}}}function Pu(e){return typeof e==`object`&&!!e&&`ok`in e}function Fu(e,t){e.preventDefault&&(t.preventDefault(),t.stopPropagation())}var Iu=Object.freeze({}),Lu=[],Ru=[];function zu(e){if(Object.keys(e).length!==0)return cu(e,{freeze:!0})}function Bu(e,t,n,r){let i=t=>Ku(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:Iu,parseObjectKey:(e,t)=>c(e,t)}),a=t=>{if(typeof t!=`string`)return[c(t)];let n=Gu(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:Iu,parseObjectKey:(e,t)=>c(e,t)});for(let e of n.unknownTokens)r.warnUnknownToken(e,t);return n.unknownTokens.length>0?[]:n.parts},o=(e,t)=>rl(a(e),t),s=(i,a,o,s,d)=>{let f=[],p=!1,m=e.bindingExpanders.values(),h=e.bindingParsers.values(),g=e.bindingFields,_=e.disambiguationResolvers.has(),v=r.warnUnknownField,y=r.warnUnknownToken;for(let[r,b]of i.entries()){let i;try{i=Uu(b.key,m,{layer:d})}catch(e){t.emitError(`binding-expand-error`,e,ou(e,`Failed to expand keymap binding`));continue}for(let m of i){let i=m.key,x;try{x=typeof i==`string`?Gu(i,h,{tokens:a,patterns:e.patterns,layer:d,parseObjectKey:(e,t)=>c(e,t)}):{parts:[c(i)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1},x=Wu(x,m)}catch(e){t.emitError(`binding-parse-error`,e,ou(e,`Failed to parse keymap binding`));continue}let S=x.parts;p||=x.hasTokenBindings;for(let e of x.unknownTokens)y(e,typeof i==`string`?i:String(i.name));if(!(x.unknownTokens.length>0))for(let i of u(b,S,a,h,d))try{let t=l(i.event),a=i.sequence,c={},u={},d=[];for(let e in i){if(e===`sequence`||Jl.has(e))continue;let t=i[e];if(t===void 0)continue;let r=g.get(e);if(!r){v(`binding`,e);continue}r(t,iu({fieldName:e,conditions:n,requirements:c,matchers:d,attrs:u}))}let p=Object.keys(u).length>0?zu(u):void 0,m=Xl(i.cmd),h={binding:b,sequence:a,command:m,event:t,parsedBinding:Ml(i),sourceTarget:o,sourceLayerOrder:s,bindingIndex:r,requires:Object.keys(c).length>0?Object.entries(c):Lu,matchers:d.length>0?d:Ru,preventDefault:i.preventDefault!==!1,fallthrough:i.fallthrough??!1};if(p&&(h.attrs=p),typeof m==`function`&&(h.run=m),a.length===0)continue;if(t===`release`&&a.length>1)throw Error(`Keymap release bindings only support a single key stroke`);let y=a.at(-1);if(y?.patternName){let t=e.patterns.get(y.patternName);if(t&&t.max!==t.min)throw Error(`Keymap unbounded sequence patterns must be followed by a concrete continuation`)}t===`press`&&!_&&Hu(f,h),f.push(h)}catch(e){t.emitError(`binding-compile-error`,e,ou(e,`Failed to compile keymap binding`))}}}return{bindings:f,hasTokenBindings:p}},c=(e,t)=>Xc(e,t),l=e=>{if(e===void 0||e===`press`)return`press`;if(e===`release`)return`release`;throw Error(`Invalid keymap binding event "${String(e)}": expected "press" or "release"`)},u=(n,r,i,a,o)=>{let s=e.bindingTransformers.values();if(s.length===0)return[{...n,sequence:Qc(r)}];let l={...n,sequence:Qc(r)},u=[],d=!0,f=o??Iu;for(let n of s)try{n(l,{layer:f,parseKey:t=>Ku(t,a,{tokens:i,patterns:e.patterns,layer:f,parseObjectKey:(e,t)=>c(e,t)}),add:e=>{u.push(Ml(e))},skipOriginal:()=>{d=!1}})}catch(e){t.emitError(`binding-transformer-error`,e,`[Keymap] Error in binding transformer:`)}return d?u.length===0?[l]:[l,...u]:u};return{parseTokenKey:i,parseKeySequence:a,formatKey:o,compileBindings:s}}function Vu(e,t){if(e.length>=t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}function Hu(e,t){for(let n of e)if(n.event===`press`&&(n.command!==void 0&&Vu(n.sequence,t.sequence)||t.command!==void 0&&Vu(t.sequence,n.sequence)))throw Error(`Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer`)}function Uu(e,t,n){if(typeof e!=`string`||t.length===0)return[{key:e}];let r=n?.layer??Iu,i=[{key:e}];for(let e of t){let t=[];for(let n of i){let i=e({input:n.key,displays:n.displays,layer:r});if(!i){t.push(n);continue}if(i.length===0)throw Error(`Keymap binding expander must return at least one key sequence for "${n.key}"`);for(let e of i){if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.key!=`string`)throw Error(`Keymap binding expander must return expansion objects with string keys for "${n.key}"`);if(e.displays!==void 0){if(!Array.isArray(e.displays))throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`);for(let t of e.displays)if(typeof t!=`string`)throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`)}t.push(e)}}i=t}return i}function Wu(e,t){if(!t.displays)return e;if(t.displays.length!==e.parts.length)throw Error(`Keymap binding expansion displays length must match parsed sequence length for "${String(t.key)}"`);return{...e,parts:e.parts.map((e,n)=>({...e,display:t.displays[n]}))}}function Gu(e,t,n){if(e.length===0)throw Error(`Invalid key sequence: sequence cannot be empty`);if(t.length===0)throw Error(`No keymap binding parsers are registered`);let r=n.tokens??new Map,i=n.patterns??new Map,a=n.layer??Iu,o=n.parseObjectKey,s=[],c=new Set,l=new Set,u=0;for(;u<e.length;){let n=!1;for(let d of t){let t=d({input:e,index:u,layer:a,tokens:r,patterns:i,normalizeTokenName:Kc,createMatch:tl,parseObjectKey:o});if(t){if(t.nextIndex<=u||t.nextIndex>e.length)throw Error(`Keymap binding parser must advance the input for "${e}" at index ${u}`);s.push(...t.parts);for(let e of t.usedTokens??[])c.add(e);for(let e of t.unknownTokens??[])l.add(e);u=t.nextIndex,n=!0;break}}if(!n)throw Error(`No keymap binding parser handled input at index ${u} in "${e}"`)}return{parts:s,usedTokens:[...c],unknownTokens:[...l],hasTokenBindings:c.size>0||l.size>0}}function Ku(e,t,n){if(typeof e!=`string`)return n.parseObjectKey(e);let{parts:r}=Gu(e,t,n),[i]=r;if(!i||r.length!==1)throw Error(`Invalid key "${String(e)}": expected a single key stroke`);return i}function qu(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.get==`function`&&typeof t.subscribe==`function`}function Ju(e,t){let n=e=>e.requires.length===0&&e.matchers.length===0,r=e=>{try{return e.match()}catch(n){return t.emitError(`runtime-matcher-error`,n,`[Keymap] Error evaluating runtime matcher from ${e.source}:`),!1}},i=e=>{if(e.matchers.length===0)return!0;if(e.matchers.length===1){let[t]=e.matchers;return!t||r(t)}for(let t of e.matchers)if(!r(t))return!1;return!0},a=t=>{if(t.length===0)return!0;for(let[n,r]of t)if(!Object.is(e.data[n],r))return!1;return!0};return{buildRuntimeMatcher(e,t){if(typeof e==`function`)return{source:t,match:e};if(qu(e))return{source:t,match:()=>e.get(),subscribe:t=>e.subscribe(t)};throw Error(`Keymap ${t} expected a function or a reactive matcher`)},matchesConditions:e=>n(e)||a(e.requires)&&i(e)}}var Yu=Symbol(`keymap-disambiguation-decision`),Xu=Symbol(`keymap-deferred-disambiguation-decision`);function Zu(e,t){return{[Yu]:!0,action:e,handler:t}}function Qu(e){return{[Xu]:!0,action:e}}function $u(e){return!!e&&typeof e==`object`&&e[Yu]===!0}function ed(e){return!!e&&typeof e==`object`&&e[Xu]===!0}function td(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener(`abort`,i),n(!0)},Math.max(0,e)),i=()=>{clearTimeout(r),t.removeEventListener(`abort`,i),n(!1)};t.addEventListener(`abort`,i,{once:!0})})}function nd(e,t,n,r){let i=e.get(n);if(i)try{return i.matcher(r)}catch(e){t.emitError(`sequence-pattern-match-error`,e,`[Keymap] Error matching sequence pattern "${i.name}":`);return}}function rd(e,t,n,r){let i=e.get(n)?.payloadKey??n;return{...Xc({name:t.name,ctrl:t.ctrl,shift:t.shift,meta:t.meta,super:t.super??!1,hyper:t.hyper||void 0},{display:r.display??String(r.value??t.name)}),patternName:n,payloadKey:i}}function id(e,t,n){if(!n?.patterns||n.patterns.length===0)return;let r={},i=!1;for(let a of n.patterns){let n=e.get(a.name),o;try{o=n?.finalize?n.finalize(a.values):a.values.length===1?a.values[0]:[...a.values]}catch(e){t.emitError(`sequence-pattern-finalize-error`,e,`[Keymap] Error finalizing sequence pattern "${a.name}":`);continue}let s=r[a.payloadKey];s===void 0?(r[a.payloadKey]=o,i=!0):Array.isArray(s)?s.push(o):r[a.payloadKey]=[s,o]}return i?r:void 0}function ad(e,t,n,r,i,a,o,s,c,l){let u={resolveKey:e=>o.parseTokenKey(e).match},d=null,f=0;function p(t,n,r){if(t===`key`){let t=r;return e.keyHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}if(t===`key:after`){let t=r;return e.keyAfterHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}let i=r;return e.rawHooks.register(n,{priority:i?.priority??0})}function m(t){return e.eventMatchResolvers.prepend(t)}function h(t){return e.eventMatchResolvers.append(t)}function g(){e.eventMatchResolvers.clear()}function _(t){return P(()=>e.disambiguationResolvers.prepend(t),t)}function v(t){return P(()=>e.disambiguationResolvers.append(t),t)}function y(){e.disambiguationResolvers.has()&&t.runWithStateChangeBatch(()=>{e.disambiguationResolvers.clear(),c.recompileBindings()})}function b(e,t){d&&de()}function x(n){let r=e.rawHooks.entries();if(r.length===0)return!1;let i=!1,a={sequence:n,stop(){i=!0}};for(let e of r){try{e.listener(a)}catch(e){t.emitError(`raw-intercept-error`,e,`[Keymap] Error in raw intercept listener:`)}if(i)return!0}return!1}function S(e,t){return{sequence:Qc(e.sequence),command:e.command,commandAttrs:s.getBindingCommandAttrs(e,t,s.getActiveCommandView(t)),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough,sourceLayerOrder:e.sourceLayerOrder,bindingIndex:e.bindingIndex}}function C(e){l.has(`dispatch`)&&l.emit(`dispatch`,e)}function w(e,t,n,r){l.has(`dispatch`)&&C({phase:e,event:n.event,focused:r,layer:{order:t.order,priority:t.priority,target:t.target,targetMode:t.targetMode},binding:S(n,r),sequence:Qc(n.sequence),command:n.command})}function T(e,t,n){if(!l.has(`dispatch`))return;let i=t[0],a=t.length>0?r.collectSequencePartsFromPending({captures:t}):[];C({phase:e,event:`press`,focused:n,layer:i?{order:i.layer.order,priority:i.layer.priority,target:i.layer.target,targetMode:i.layer.targetMode}:void 0,sequence:a})}function E(t){let n=e.keyAfterHooks.entries();for(let e of n)if(e.release===t)return n}function D(e){return e.sequence?Qc(e.sequence):e.captures?r.collectSequencePartsFromPending({captures:e.captures}):[]}function O(e,t){return{handled:e!==`sequence-miss`,reason:e,captures:t}}function k(e,t){return{handled:t,reason:t?`binding-handled`:`binding-rejected`,sequence:e.sequence}}function A(e,t){return t.handled||e.reason===`no-match`?t:e}function j(e,i,a,o,s){let c={event:i,eventType:a?`release`:`press`,focused:o,handled:s.handled,reason:s.reason,sequence:D(s),pendingSequence:r.getPendingSequence(),setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let n of e)if(n.release===a)try{n.listener(c)}catch(e){t.emitError(`key-after-intercept-error`,e,`[Keymap] Error in key:after intercept listener:`)}}function M(){return{handled:!1,reason:`no-match`}}function N(e){e.preventDefault(),e.stopPropagation()}function ee(e,t,n,i){r.setPendingSequence({captures:t});let a=O(`sequence-pending`,t);return T(e,t,n),N(i),a}function te(e,t,n,i){let a=O(e,t);return T(`sequence-clear`,t,n),r.setPendingSequence(null),N(i),a}function ne(i,a){a||de();let o=E(a),s=o?r.getFocusedTarget():null,c=e.keyHooks.entries(),l={event:i,setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let e of c)if(e.release===a){try{e.listener(l)}catch(e){t.emitError(`key-intercept-error`,e,`[Keymap] Error in key intercept listener:`)}if(i.propagationStopped){o&&j(o,i,a,s,{handled:!0,reason:`intercept-consumed`,sequence:[]});return}}if(a){let e=F(i);o&&j(o,i,a,s,e);return}let u=re(i);o&&j(o,i,a,s,u)}function P(n,r){return t.runWithStateChangeBatch(()=>{let i=e.disambiguationResolvers.has(),a=n();return!i&&e.disambiguationResolvers.has()&&c.recompileBindings(),()=>{t.runWithStateChangeBatch(()=>{let t=e.disambiguationResolvers.has();a(),!e.disambiguationResolvers.values().includes(r)&&t&&!e.disambiguationResolvers.has()&&c.recompileBindings()})}})}function F(e){let t=r.getFocusedTarget(),n=r.getActiveLayers(t),a=ge(e),o=M();for(let r of a)layerLoop:for(let a of n){if(a.bindings.length===0||!i.matchesConditions(a))continue;let n=_e(a,r,e,t);if(o=A(o,n.outcome),n.handled){if(n.stop)return o;continue layerLoop}}return o}function re(e){let t=r.getFocusedTarget(),n=r.ensureValidPendingSequence(),i=ge(e);if(n)return I(n,i,e,t);let a=r.getActiveLayers(t),o=M();for(let n of i){let r=R(a,[n],e,t);if(o=A(o,r),r.handled)return o}return o}function I(t,n,i,a){let o=s.getActiveCommandView(a),c=[];for(let r of t.captures){let t=Cl(r,n,i,e.patterns,U,ve);t&&c.push(t)}let l=c.reduce((e,t)=>Math.min(e,xl(t,n)),1/0),u=c.filter(e=>xl(e,n)===l);if(u.length===0||!u.some(e=>xe(e,a,o))){let e=O(`sequence-miss`,t.captures);return T(`sequence-clear`,t.captures,a),r.setPendingSequence(null),e}return L(u,0,!1,i,a)}function L(t,n,i,a,o){let s=i,c=M(),l=new Set;for(let i=n;i<t.length;i+=1){let n=t[i];if(!n||l.has(n))continue;let u=me(t,i,n);if(u.length>0){if(s)continue;let e=he(t,n);return ae(t,i,u,e,a,o,s)||ee(`sequence-advance`,u,o,a)}if(!gl(n,e.patterns))continue;let d=he(t,n);for(let e of d)l.add(e);let f=Se(n.layer,d,a,o);if(c=A(c,f.outcome),f.handled&&(s=!0,f.stop))return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}function R(e,t,n,r){return z(e,0,t,n,r)}function z(t,n,r,a,o){let c=s.getActiveCommandView(o),l=M();for(let s=n;s<t.length;s+=1){let n=t[s];if(!n||!i.matchesConditions(n))continue;let u=ye(n,r,a,o,c);if(u.length===0)continue;if(u.filter(t=>hl(t,e.patterns,!1)).length>0){let n=u.filter(t=>gl(t,e.patterns)),i=pe(t,s,r,a,o);return ie(t,s,r,i,n,a,o)||ee(`sequence-start`,i,o,a)}let d=Se(n,u.filter(t=>gl(t,e.patterns)),a,o);if(l=A(l,d.outcome),d.handled&&d.stop)return l}return l}function ie(e,t,n,i,a,o,s){return oe({event:o,focused:s,continuationCaptures:i,exactBindingsSource:a.map(e=>e.binding),sequencePhase:`sequence-start`,runExact:()=>{r.setPendingSequence(null);let i=a[0]?.layer;if(!i)return M();let c=Se(i,a,o,s);return c.stop?c.outcome:A(c.outcome,z(e,t+1,n,o,s))}})}function ae(e,t,n,i,a,o,s){return oe({event:a,focused:o,continuationCaptures:n,exactBindingsSource:i.map(e=>e.binding),sequencePhase:`sequence-advance`,runExact:()=>{r.setPendingSequence(null);let n=i[0]?.layer;if(!n)return M();let c=Se(n,i,a,o);return c.stop?c.outcome:A(c.outcome,L(e,t+1,s||c.handled,a,o))}})}function oe(t){let{event:n,focused:i,continuationCaptures:a,exactBindingsSource:o,sequencePhase:c,runExact:l}=t;if(!e.disambiguationResolvers.has()||a.length===0)return;let u=s.getActiveCommandView(i),d=r.collectMatchingBindings(o,i,u);if(!d.some(e=>e.command!==void 0))return;let f=()=>ee(c,a,i,n),p=()=>te(`sequence-cleared`,a,i,n),m,h=()=>(m??=r.collectSequencePartsFromPending({captures:a}),m),g=B({event:n,focused:i,getSequence:h,exactBindings:d,continuationCaptures:a,activeView:u});return g?se(g,a,l,f,p,i,h):(fe(h()),f())}function se(e,t,n,r,i,a,o){if(e.action===`run-exact`)return n();if(e.action===`continue-sequence`)return r();if(e.action===`clear`)return i();let s=r();return ce(t,e.handler,a,o(),e=>{if(e){if(e.action===`run-exact`){n();return}if(e.action===`continue-sequence`){r();return}i()}}),s}function B(i){let a,o,s,c,l={event:i.event,focused:i.focused,get sequence(){return a??=Qc(i.getSequence()),a},get stroke(){let e=i.getSequence().at(-1);if(!e)throw Error(`Disambiguation context expected a non-empty sequence`);return c??={...e,stroke:Yc(e.stroke)},c},get exact(){return o??=r.collectActiveBindings(i.exactBindings,i.focused,i.activeView).map(e=>({...e,sequence:Qc(e.sequence)})),o},get continuations(){return s??=r.getActiveKeysForCaptures(i.continuationCaptures,{includeBindings:!0,includeMetadata:!0}),s},getData:e=>n.getData(e),setData:(e,t)=>{n.setData(e,t)},runExact:()=>Zu(`run-exact`),continueSequence:()=>Zu(`continue-sequence`),clear:()=>Zu(`clear`),defer:e=>Zu(`defer`,e)};for(let n of e.disambiguationResolvers.values()){let e;try{e=n(l)}catch(e){t.emitError(`disambiguation-resolver-error`,e,`[Keymap] Error in disambiguation resolver:`);continue}if(e!==void 0){if(su(e)){t.emitError(`invalid-disambiguation-resolver-return`,e,`[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling`);continue}if(!$u(e)){t.emitError(`invalid-disambiguation-decision`,e,`[Keymap] Invalid disambiguation decision returned by resolver:`);continue}return e}}}function ce(e,t,n,r,i){de();let a=new AbortController,o={id:f++,controller:a,captures:e,apply:i};d=o,queueMicrotask(()=>{le(o,t,n,r)})}function le(e,n,r,i){if(!H(e))return;let a={signal:e.controller.signal,sequence:Qc(i),focused:r,sleep:t=>td(t,e.controller.signal),runExact:()=>Qu(`run-exact`),continueSequence:()=>Qu(`continue-sequence`),clear:()=>Qu(`clear`)},o;try{o=n(a)}catch(n){H(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),V(e));return}if(su(o)){o.then(t=>{ue(e,t)}).catch(n=>{H(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),V(e))});return}ue(e,o)}function ue(e,n){if(H(e)){if(n!==void 0&&!ed(n)){t.emitError(`invalid-deferred-disambiguation-decision`,n,`[Keymap] Invalid deferred disambiguation decision returned by handler:`),V(e);return}V(e),e.apply(n)}}function V(e){H(e)&&(d=null)}function de(){let e=d;e&&(d=null,e.controller.abort())}function H(e){return d===e}function fe(e){let n=rl(e,{preferDisplay:!0});t.warnOnce(`unresolved-disambiguation:${n}`,`unresolved-disambiguation`,{sequence:n},`[Keymap] Ambiguous exact/prefix sequence "${n}" fell back to prefix handling because no disambiguation resolver resolved it`)}function pe(t,n,r,a,o){let c=[],l=s.getActiveCommandView(o);for(let s=n;s<t.length;s+=1){let n=t[s];if(n&&i.matchesConditions(n))for(let t of ye(n,r,a,o,l))hl(t,e.patterns,!1)&&c.push(t)}return c}function me(t,n,r){return t.filter((t,i)=>i>=n&&hl(t,e.patterns,!1)&&sd(t.parts,r.parts))}function he(t,n){return t.filter(t=>t.layer===n.layer&&gl(t,e.patterns)&&sd(t.parts,n.parts))}function ge(n){let r=e.eventMatchResolvers.values();if(r.length===0)return[];if(r.length===1)return od(r[0],n,u,t);let i=[],a=new Set;for(let e of r){let r;try{r=e(n,u)}catch(e){t.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`);continue}if(!(!r||r.length===0))for(let e of r){if(typeof e!=`string`){t.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}a.has(e)||(a.add(e),i.push(e))}}return i}function _e(e,t,n,r){let o=!1,s=M();for(let c of e.bindings){if(c.event!==`release`)continue;let l=c.sequence[0];if(!l||l.match!==t||!i.matchesConditions(c))continue;let u=a.runBinding(e,c,n,r);if(s=A(s,k(c,u)),!u){w(`binding-reject`,e,c,r);continue}if(w(`binding-execute`,e,c,r),o=!0,!c.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}function U(n,r){return nd(e.patterns,t,n,r)}function ve(t,n,r){return rd(e.patterns,t,n,r)}function ye(e,t,n,r,i){let a=wl(e,t,n,U,ve);return a.some(e=>xe(e,r,i))?a:[]}function be(n){return id(e.patterns,t,n)}function W(e,t,n){return i.matchesConditions(e)&&s.isBindingVisible(e,t,n)}function xe(e,t,n){return W(e.binding,t,n)}function Se(e,t,n,r){let o=!1,s=M();for(let c of t){let t=c.binding;if(!i.matchesConditions(t))continue;let l=a.runBinding(e,t,n,r,be(c));if(s=A(s,k(t,l)),!l){w(`binding-reject`,e,t,r);continue}if(w(`binding-execute`,e,t,r),o=!0,!t.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}return{intercept:p,prependEventMatchResolver:m,appendEventMatchResolver:h,clearEventMatchResolvers:g,prependDisambiguationResolver:_,appendDisambiguationResolver:v,clearDisambiguationResolvers:y,handlePendingSequenceChange:b,handleRawSequence:x,handleKeyEvent:ne}}function od(e,t,n,r){let i;try{i=e(t,n)}catch(e){return r.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`),[]}if(!i||i.length===0)return[];if(i.length===1){let[e]=i;return typeof e==`string`?[e]:(r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`),[])}let a=[],o=new Set;for(let e of i){if(typeof e!=`string`){r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}o.has(e)||(o.add(e),a.push(e))}return a}function sd(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}var cd=()=>{};function ld(e,t,n,r){if(n===void 0)return r;if(typeof n!=`number`||!Number.isInteger(n)||n<0)throw Error(`Keymap sequence pattern "${e}" ${t} must be a non-negative integer`);return n}function ud(e,t){let{kind:n,reservedFields:r,registeredFields:i,emitError:a}=t,o=Object.entries(e),s=[];for(let[e,t]of o){if(r.has(e)){a(`reserved-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is reserved`);continue}if(i.has(e)){a(`duplicate-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is already registered`);continue}i.set(e,t),s.push([e,t])}return()=>{for(let[e,t]of s)i.get(e)===t&&i.delete(e)}}function dd(e,t,n,r,i){let a;try{a=Kc(i.name)}catch(e){return t.emitError(`token-name-normalize-error`,e,ou(e,`Failed to register keymap token`)),cd}if(e.tokens.has(a)||e.patterns.has(a))return t.emitError(`duplicate-token`,{token:a},`Keymap token "${a}" is already registered`),cd;let o;try{if(o=n.parseTokenKey(i.key),o.patternName)throw Error(`Invalid key "${String(i.key)}": expected a concrete key stroke`)}catch(e){return t.emitError(`token-parse-error`,e,ou(e,`Failed to register keymap token "${a}"`)),cd}let s={stroke:o.stroke,match:o.match},c=new Map(e.tokens);c.set(a,s);try{r.applyTokenState(c)}catch(e){return t.emitError(`token-register-error`,e,ou(e,`Failed to register keymap token "${a}"`)),cd}return()=>{if(e.tokens.get(a)!==s)return;let n=new Map(e.tokens);n.delete(a);try{r.applyTokenState(n)}catch(e){t.emitError(`token-unregister-error`,e,ou(e,`Failed to unregister keymap token "${a}"`))}}}function fd(e,t,n,r){let i,a;try{i=Kc(r.name);let e=ld(i,`min`,r.min,1),t=ld(i,`max`,r.max,2**53-1);if(t<e)throw Error(`Keymap sequence pattern "${i}" max must be greater than or equal to min`);a={name:i,display:r.display,payloadKey:r.payloadKey??i,match:tl(`pattern:${i}`),min:e,max:t,matcher:e=>r.match(e),finalize:r.finalize}}catch(e){return t.emitError(`sequence-pattern-register-error`,e,ou(e,`Failed to register keymap sequence pattern`)),cd}return e.tokens.has(i)||e.patterns.has(i)?(t.emitError(`duplicate-sequence-pattern`,{pattern:i},`Keymap sequence pattern "${i}" is already registered`),cd):(e.patterns.set(i,a),n.recompileBindings(),()=>{e.patterns.get(i)===a&&(e.patterns.delete(i),n.recompileBindings())})}function pd(e,t,n,r){return ud(r,{kind:n,reservedFields:n===`layer`?Yl:n===`binding`?Jl:ql,registeredFields:n===`layer`?e.layerFields:n===`binding`?e.bindingFields:e.commandFields,emitError:(e,n,r)=>t.emitError(e,n,r)})}var md=()=>{};function hd(e,t){return t.priority-e.priority||t.order-e.order}function gd(e){if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;for(let t of e.bindings)if(t.matchers.length>0)return!0;return!1}function _d(e){if(e.commands.length===0)return!1;if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;return!1}function vd(e,t,n,r,i){let a=n=>t.runWithStateChangeBatch(()=>{let a=n.target;if(a&&i.host.isTargetDestroyed(a))return t.emitError(`destroyed-layer-target`,{target:a},`Cannot register a keymap layer for a destroyed keymap target`),md;let o,s,c,p,m,v,y;try{y=l(n),o=u(jl(n.bindings??[]),n);let e=d(n.commands??[],n);v=e.length===0?[]:i.commands.normalizeCommands(e),{requires:s,matchers:c,fields:p,attrs:m}=f(n)}catch(e){return t.emitError(`register-layer-failed`,e,ou(e,`Failed to register keymap layer`)),md}let b=e.order++,x=i.compiler.compileBindings(o,e.tokens,a,b,p);if(x.bindings.length===0&&!x.hasTokenBindings&&v.length===0)return md;i.diagnostics?.analyzeLayer({target:a,order:b,commands:v,sourceBindings:o,bindings:x.bindings,hasTokenBindings:x.hasTokenBindings});let S={order:b,target:a,targetMode:y,priority:n.priority??0,requires:s,matchers:c,fields:p,attrs:m,commands:v,sourceBindings:o,bindings:x.bindings,root:vl(x.bindings,e.patterns),hasTokenBindings:x.hasTokenBindings,activeKeyCacheBlocked:!1,activeCommandViewCacheBlocked:!1};_(S),e.layers.add(S),e.sortedLayers=[...e.sortedLayers,S].sort(hd),g(S);for(let e of S.commands)g(e);for(let e of S.bindings)g(e);return a&&(S.offTargetDestroy=i.host.onTargetDestroy(a,()=>{h(S)})),S.commands.length>0&&r.ensureValidPendingSequence(),t.queueStateChange(),()=>{h(S)}}),o=n=>{t.runWithStateChangeBatch(()=>{let i=new Map;for(let t of e.layers)t.hasTokenBindings&&i.set(t,p(t,n));e.tokens=n;let a=!1;for(let[e,t]of i)m(e,t)&&(a=!0);a&&r.setPendingSequence(null),i.size>0&&t.queueStateChange()})},s=()=>{t.runWithStateChangeBatch(()=>{let n=0,i=!1;for(let t of e.layers){if(t.sourceBindings.length===0)continue;let r=p(t,e.tokens);m(t,r)&&(i=!0),n+=1}i&&r.setPendingSequence(null),n>0&&t.queueStateChange()})},c=()=>{for(let t of e.layers){y(t);for(let e of t.commands)y(e);for(let e of t.bindings)y(e);t.offTargetDestroy?.(),t.offTargetDestroy=void 0}},l=e=>{if(e.targetMode){if(!e.target)throw Error(`Keymap targetMode "${e.targetMode}" requires a target`);return e.targetMode}return e.target?`focus-within`:void 0},u=(t,n)=>{let r=e.layerBindingsTransformers.values();if(r.length===0)return t;let i=t;for(let e of r){let t=e(i,{layer:n,validateBindings:e=>Al(e)});t&&(i=jl(t))}return i},d=(n,r)=>{let i=e.commandTransformers.values();if(n.length===0||i.length===0)return n;let a=[];for(let e of n){let n={...e},o=[],s=!0;for(let e of i)try{e(n,{layer:r,add(e){o.push({...e})},skipOriginal(){s=!1}})}catch(e){t.emitError(`command-transformer-error`,e,`[Keymap] Error in command transformer:`)}s&&a.push(n),a.push(...o)}return a},f=t=>{let r={},a=[],o=Object.create(null),s={};for(let[c,l]of Object.entries(t)){if(Yl.has(c)||l===void 0)continue;o[c]=cu(l);let t=e.layerFields.get(c);if(!t){i.warnUnknownField(`layer`,c);continue}t(l,iu({fieldName:c,conditions:n,requirements:r,matchers:a,attrs:s}))}return{requires:Object.entries(r),matchers:a,fields:Object.keys(o).length>0?Object.freeze(o):void 0,attrs:Object.keys(s).length>0?cu(s,{freeze:!0}):void 0}},p=(e,t)=>i.compiler.compileBindings(e.sourceBindings,t,e.target,e.order,e.fields),m=(t,n)=>{i.diagnostics?.analyzeLayer({target:t.target,order:t.order,commands:t.commands,sourceBindings:t.sourceBindings,bindings:n.bindings,hasTokenBindings:n.hasTokenBindings}),v(t);for(let e of t.bindings)y(e);t.bindings=n.bindings,t.root=vl(n.bindings,e.patterns),t.hasTokenBindings=n.hasTokenBindings,_(t);for(let e of t.bindings)g(e);return e.pending?.captures.some(e=>e.layer===t)??!1},h=n=>{t.runWithStateChangeBatch(()=>{if(e.layers.delete(n)){e.sortedLayers=e.sortedLayers.filter(e=>e!==n),v(n),y(n);for(let e of n.commands)y(e);for(let e of n.bindings)y(e);n.offTargetDestroy?.(),n.offTargetDestroy=void 0,e.pending?.captures.some(e=>e.layer===n)?r.setPendingSequence(null):n.commands.length>0&&!i.host.isDestroyed&&r.ensureValidPendingSequence(),t.queueStateChange()}})},g=e=>{for(let n of e.matchers)if(n.subscribe)try{n.dispose=n.subscribe(()=>{if(!r.hasPendingSequenceState()){t.queueStateChange();return}t.runWithStateChangeBatch(()=>{r.revalidatePendingSequenceIfNeeded(),t.queueStateChange()})})}catch(e){t.emitError(`reactive-matcher-subscribe-error`,e,ou(e,`Failed to subscribe to reactive matcher from ${n.source}`))}},_=t=>{let n=gd(t),r=_d(t);t.activeKeyCacheBlocked=n,t.activeCommandViewCacheBlocked=r,n&&(e.activeKeyCacheBlockers+=1),r&&(e.activeCommandViewCacheBlockers+=1)},v=t=>{t.activeKeyCacheBlocked&&=(--e.activeKeyCacheBlockers,!1),t.activeCommandViewCacheBlocked&&=(--e.activeCommandViewCacheBlockers,!1)},y=e=>{for(let n of e.matchers)if(n.dispose){try{n.dispose()}catch(e){t.emitError(`reactive-matcher-dispose-error`,e,ou(e,`Failed to dispose reactive matcher from ${n.source}`))}n.dispose=void 0}};return{registerLayer:a,applyTokenState:o,recompileBindings:s,cleanup:c}}var yd=1e3;function bd(e,t,n){let r=(e,n,r)=>{if(!t.has(`warning`)){let t=`[${e}] ${r}`;n instanceof Error?console.warn(t,n):console.warn(t);return}t.emit(`warning`,{code:e,message:r,warning:n})},i=(e,n,r)=>{if(!t.has(`error`)){let t=`[${e}] ${r}`;n instanceof Error?console.error(t,n):console.error(t);return}t.emit(`error`,{code:e,message:r,error:n})},a=()=>{if(!(!e.stateChangePending||e.stateChangeDepth>0||e.flushingStateChange)){e.flushingStateChange=!0;try{let t=0;for(;e.stateChangePending&&e.stateChangeDepth===0;){if(t>=yd){e.stateChangePending=!1,i(`state-change-feedback-loop`,{iterations:yd},`[Keymap] Possible infinite state listener feedback loop detected after ${yd} iterations; pending state notifications were dropped`);break}t+=1,e.stateChangePending=!1,n.emit(`state`)}}finally{e.flushingStateChange=!1}}};return{runWithStateChangeBatch(t){e.stateChangeDepth+=1;try{return t()}finally{--e.stateChangeDepth,e.stateChangeDepth===0&&a()}},queueStateChange(t){e.derivedVersion+=1,t?.invalidateCaches!==!1&&(e.cacheVersion+=1),n.has(`state`)&&(e.stateChangePending=!0,e.stateChangeDepth===0&&!e.flushingStateChange&&a())},emitWarning:r,emitError:i,reportListenerError(e,t){if(e===`state`){i(`state-listener-error`,t,`[Keymap] Error in state listener:`);return}if(e===`pendingSequence`){i(`pending-sequence-listener-error`,t,`[Keymap] Error in pending sequence listener:`);return}e===`dispatch`&&i(`dispatch-listener-error`,t,`[Keymap] Error in dispatch listener:`)},warnOnce(t,n,i,a){e.usedWarningKeys.has(t)||(e.usedWarningKeys.add(t),r(n,i,a))}}}function xd(e,t,n){return{getData(t){return e.data[t]},setData(r,i){t.runWithStateChangeBatch(()=>{if(i===void 0){if(!(r in e.data))return;delete e.data[r],e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange();return}Object.is(e.data[r],i)||(e.data[r]=i,e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange())})},getReadonlyData(){return e.readonlyDataVersion===e.dataVersion?e.readonlyData:(e.readonlyData=Object.freeze({...e.data}),e.readonlyDataVersion=e.dataVersion,e.readonlyData)}}}var Sd=Object.freeze({});function Cd(){return{order:0,tokens:new Map,patterns:new Map,layerFields:new Map,layerBindingsTransformers:Dl(),bindingExpanders:Dl(),bindingParsers:Dl(),bindingTransformers:Dl(),bindingFields:new Map,commandTransformers:Dl(),commandFields:new Map,eventMatchResolvers:Dl(),disambiguationResolvers:Dl(),keyHooks:Ol(),keyAfterHooks:Ol(),rawHooks:Ol(),layers:new Set,sortedLayers:[],activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],activeKeyCacheBlockers:0,activeCommandViewCacheBlockers:0,commandResolvers:Dl(),pending:null,data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:Sd,cacheVersion:0,derivedVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}function wd(e){return $c(e)}var Td=class{#e=Cd();#t=!1;#n=new Map;#r=[];#i=Tl(()=>{});#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;getPendingSequence;getActiveKeys;constructor(e){if(this.#b=e,e.isDestroyed)throw Error(`Cannot create a keymap for a destroyed host`);this.#a=Tl((e,t)=>{this.#o.reportListenerError(e,t)}),this.#o=bd(this.#e,this.#i,this.#a),this.#l=Ju(this.#e,this.#o),this.#u=fu(this.#e,this.#b,this.#o,this.#l,{onCommandResolversChanged:()=>{this.#s.ensureValidPendingSequence()}}),this.#s=Kl(this.#e,this.#b,this.#a,this.#o,this.#l,this.#u,{onPendingSequenceChanged:(e,t)=>{this.#p?.handlePendingSequenceChange(e,t)}}),this.#c=xd(this.#e,this.#o,this.#s),this.#d=Nu(this.#o,this.#c,this.#s,this.#u,{keymap:this,createCommandEvent:()=>this.#b.createCommandEvent()}),this.#f=Bu(this.#e,this.#o,this.#l,{warnUnknownField:(e,t)=>{this.#C(e,t)},warnUnknownToken:(e,t)=>{this.#w(e,t)}}),this.#h=Nl(this.#o,this.#u),this.#m=vd(this.#e,this.#o,this.#l,this.#s,{compiler:this.#f,commands:this.#u,host:this.#b,diagnostics:this.#h,warnUnknownField:(e,t)=>{this.#C(e,t)}}),this.#p=ad(this.#e,this.#o,this.#c,this.#s,this.#l,this.#d,this.#f,this.#u,this.#m,this.#a),this.getPendingSequence=this.#s.getPendingSequence,this.getActiveKeys=this.#s.getActiveKeys,this.#g=e=>{this.#p.handleKeyEvent(e,!1)},this.#_=e=>{this.#p.handleKeyEvent(e,!0)},this.#v=e=>this.#p.handleRawSequence(e),this.#y=e=>{this.#S(e)},this.#r.push(this.#b.onKeyPress(this.#g)),this.#r.push(this.#b.onKeyRelease(this.#_)),this.#b.onRawInput&&this.#r.push(this.#b.onRawInput(this.#v)),this.#r.push(this.#b.onFocusChange(this.#y)),this.#b.onDestroy&&this.#r.push(this.#b.onDestroy(()=>{this.#x()}))}[ol](){return{state:this.#e,host:this.#b,conditions:this.#l,catalog:this.#u,activation:this.#s}}#x(){if(!this.#t){this.#t=!0,this.#s.setPendingSequence(null);for(let e of this.#n.values())e.dispose();this.#n.clear(),this.#m.cleanup();for(let e of this.#r.splice(0))e()}}setData(e,t){this.#c.setData(e,t)}getData(e){return this.#c.getData(e)}getHostMetadata(){return this.#b.metadata}hasPendingSequence(){return this.#s.ensureValidPendingSequence()!==void 0}createKeyMatcher(e){let t=this.#f.parseTokenKey(e).match;return e=>e?wd(e)===t:!1}parseKeySequence(e){return this.#f.parseKeySequence(e)}formatKey(e,t){return this.#f.formatKey(e,t)}clearPendingSequence(){this.#s.setPendingSequence(null)}popPendingSequence(){return this.#s.popPendingSequence()}getCommands(e){return this.#u.getCommands(e)}getCommandEntries(e){return this.#u.getCommandEntries(e)}getCommandBindings(e){return this.#u.getCommandBindings(e)}acquireResource(e,t){if(this.#t||this.#b.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);let n=this.#n.get(e);if(n)return n.count+=1,()=>{this.#T(e,n)};let r={count:1,dispose:t()};return this.#n.set(e,r),()=>{this.#T(e,r)}}runCommand(e,t){return this.#d.runCommand(e,t)}dispatchCommand(e,t){return this.#d.dispatchCommand(e,t)}on(e,t){return e===`warning`||e===`error`?this.#i.hook(e,t):this.#a.hook(e,t)}intercept(e,t,n){return this.#p.intercept(e,t,n)}registerLayer(e){return this.#m.registerLayer(e)}registerLayerFields(e){return pd(this.#e,this.#o,`layer`,e)}prependLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.prepend(e)}appendLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.append(e)}clearLayerBindingsTransformers(){this.#e.layerBindingsTransformers.clear()}prependBindingTransformer(e){return this.#e.bindingTransformers.prepend(e)}appendBindingTransformer(e){return this.#e.bindingTransformers.append(e)}clearBindingTransformers(){this.#e.bindingTransformers.clear()}prependCommandTransformer(e){return this.#e.commandTransformers.prepend(e)}appendCommandTransformer(e){return this.#e.commandTransformers.append(e)}clearCommandTransformers(){this.#e.commandTransformers.clear()}prependBindingParser(e){return this.#e.bindingParsers.prepend(e)}appendBindingParser(e){return this.#e.bindingParsers.append(e)}clearBindingParsers(){this.#e.bindingParsers.clear()}registerToken(e){return dd(this.#e,this.#o,this.#f,this.#m,e)}registerSequencePattern(e){return fd(this.#e,this.#o,this.#m,e)}prependBindingExpander(e){return this.#e.bindingExpanders.prepend(e)}appendBindingExpander(e){return this.#e.bindingExpanders.append(e)}clearBindingExpanders(){this.#e.bindingExpanders.clear()}registerBindingFields(e){return pd(this.#e,this.#o,`binding`,e)}registerCommandFields(e){return pd(this.#e,this.#o,`command`,e)}prependCommandResolver(e){return this.#u.prependCommandResolver(e)}appendCommandResolver(e){return this.#u.appendCommandResolver(e)}clearCommandResolvers(){this.#u.clearCommandResolvers()}prependLayerAnalyzer(e){return this.#h.prependLayerAnalyzer(e)}appendLayerAnalyzer(e){return this.#h.appendLayerAnalyzer(e)}clearLayerAnalyzers(){this.#h.clearLayerAnalyzers()}prependEventMatchResolver(e){return this.#p.prependEventMatchResolver(e)}appendEventMatchResolver(e){return this.#p.appendEventMatchResolver(e)}clearEventMatchResolvers(){this.#p.clearEventMatchResolvers()}prependDisambiguationResolver(e){return this.#p.prependDisambiguationResolver(e)}appendDisambiguationResolver(e){return this.#p.appendDisambiguationResolver(e)}clearDisambiguationResolvers(){this.#p.clearDisambiguationResolvers()}#S(e){this.#o.runWithStateChangeBatch(()=>{this.#s.setPendingSequence(null),this.#o.queueStateChange({invalidateCaches:!1})})}#C(e,t){this.#o.warnOnce(`${e}:${t}`,`unknown-${e}-field`,{field:t,kind:e},`[Keymap] Unknown ${e} field "${t}" was ignored`)}#w(e,t){this.#o.warnOnce(`token:${e}`,`unknown-token`,{token:e,sequence:t},`[Keymap] Unknown token "${e}" in key sequence "${t}"; binding was skipped until the token is registered`)}#T(e,t){this.#n.get(e)===t&&(--t.count,!(t.count>0)&&(t.dispose(),this.#n.delete(e)))}},Ed=new Set(`up.down.left.right.clear.escape.return.linefeed.enter.tab.backspace.delete.insert.home.end.pageup.pagedown.space.lt.gt.plus.minus.equal.comma.period.slash.backslash.semicolon.quote.backquote.leftbracket.rightbracket.capslock.numlock.scrolllock.printscreen.pause.menu.apps.kp0.kp1.kp2.kp3.kp4.kp5.kp6.kp7.kp8.kp9.kpdecimal.kpdivide.kpmultiply.kpminus.kpplus.kpenter.kpequal.kpseparator.kpleft.kpright.kpup.kpdown.kppageup.kppagedown.kphome.kpend.kpinsert.kpdelete.mediaplay.mediapause.mediaplaypause.mediareverse.mediastop.mediafastforward.mediarewind.medianext.mediaprev.mediarecord.volumedown.volumeup.mute.leftshift.leftctrl.leftalt.leftsuper.lefthyper.leftmeta.rightshift.rightctrl.rightalt.rightsuper.righthyper.rightmeta.iso_level3_shift.iso_level5_shift.option.alt.meta.super.hyper.control.ctrl.shift`.split(`.`)),Dd=new Set([`ctrl`,`control`,`shift`,`meta`,`alt`,`option`,`super`,`hyper`]),Od=Ad(Ed),kd=Ad(Dd);function Ad(e){let t=new Map;for(let n of e){let e=n.charCodeAt(0);if(Number.isNaN(e))continue;let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n)}for(let e of t.values())e.sort((e,t)=>t.length-e.length);return t}function jd(e){return e>=65&&e<=90?e+32:e}function Md(e){return e>=48&&e<=57}function Nd(e,t,n){if(e.startsWith(t,n))return!0;if(n+t.length>e.length)return!1;for(let r=0;r<t.length;r+=1)if(jd(e.charCodeAt(n+r))!==t.charCodeAt(r))return!1;return!0}function Pd(e,t,n){let r=t.charCodeAt(n);if(Number.isNaN(r))return;let i=e.get(jd(r));if(i){for(let e of i)if(Nd(t,e,n))return e}}function Fd(e,t,n,r,i){return e.parseObjectKey(t,{display:n,match:r,tokenName:i})}function Id(e,t){if(e===` `)return t.parseObjectKey({name:`space`},{display:`space`});if(e===`+`)return t.parseObjectKey({name:`+`},{display:`+`});let n=e.split(`+`),r=``,i=``,a=!1,o=!1,s=!1,c=!1,l=!1;for(let t of n){let n=t.trim();if(!n)continue;let u=n.toLowerCase();if(u===`ctrl`||u===`control`){a=!0;continue}if(u===`shift`){o=!0;continue}if(u===`meta`||u===`alt`||u===`option`){s=!0;continue}if(u===`super`){c=!0;continue}if(u===`hyper`){l=!0;continue}if(r)throw Error(`Invalid key "${e}": multiple key names are not supported`);r=n,i=u}if(!r)throw Error(`Invalid key "${e}": missing key name`);let u=[];return a&&u.push(`ctrl`),o&&u.push(`shift`),s&&u.push(`meta`),c&&u.push(`super`),l&&u.push(`hyper`),u.push(i),t.parseObjectKey({name:r,ctrl:a,shift:o,meta:s,super:c,hyper:l||void 0},{display:u.join(`+`)})}function Ld(e,t){let n=e.trim().toLowerCase();return t.parseObjectKey({name:n},{display:n})}function Rd(e,t){let n=Pd(Od,e,t);if(n)return n;if(jd(e.charCodeAt(t))!==102||!Md(e.charCodeAt(t+1)))return;let r=Md(e.charCodeAt(t+2))?t+3:t+2;return e.slice(t,r).toLowerCase()}function zd(e,t){return Pd(kd,e,t)}function Bd(e,t,n){let r=t,i=!1,a=!1,o=!1,s=!1,c=!1;for(;r<e.length;){let t=zd(e,r);if(!t)break;let n=r+t.length;if(e[n]!==`+`)break;t===`ctrl`||t===`control`?i=!0:t===`shift`?a=!0:t===`meta`||t===`alt`||t===`option`?o=!0:t===`super`?s=!0:t===`hyper`&&(c=!0),r=n+1}if(r===t)return;let l=e[r];if(l===void 0)throw Error(`Invalid key "${e.slice(t)}": missing key name`);let u=Rd(e,r)??l,d=u===` `?`space`:u===`+`?`+`:u.toLowerCase(),f=[];return i&&f.push(`ctrl`),a&&f.push(`shift`),o&&f.push(`meta`),s&&f.push(`super`),c&&f.push(`hyper`),f.push(d),{part:n.parseObjectKey({name:u===` `?`space`:u,ctrl:i,shift:a,meta:o,super:s,hyper:c||void 0},{display:f.join(`+`)}),nextIndex:r+u.length}}var Vd=e=>{let{input:t,index:n,tokens:r,normalizeTokenName:i}=e;if(n===0&&t.includes(`+`)&&/\s/.test(t))return{parts:[Id(t,e)],nextIndex:t.length};let a=t[n];if(a===void 0)return;if(a===`<`){let o=t.indexOf(`>`,n);if(o===-1)return{parts:[Id(a,e)],nextIndex:n+1};let s=i(t.slice(n+1,o)),c=r.get(s);return c?{parts:[Fd(e,c.stroke,`<${s}>`,c.match,s)],nextIndex:o+1,usedTokens:[s]}:{parts:[],nextIndex:o+1,unknownTokens:[s]}}if(a===`{`){let r=t.indexOf(`}`,n);if(r===-1)return{parts:[Id(a,e)],nextIndex:n+1};let o=i(t.slice(n+1,r)),s=e.patterns.get(o);return s?{parts:[{...e.parseObjectKey({name:o,ctrl:!1,shift:!1,meta:!1,super:!1},{display:s.display??`{${o}}`,match:s.match}),patternName:s.name,payloadKey:s.payloadKey}],nextIndex:r+1,usedTokens:[o]}:{parts:[],nextIndex:r+1,unknownTokens:[o]}}let o=Bd(t,n,e);if(o)return{parts:[o.part],nextIndex:o.nextIndex};let s=Rd(t,n);return s?{parts:[Ld(s,e)],nextIndex:n+s.length}:{parts:[Id(a,e)],nextIndex:n+1}},Hd=(e,t)=>[t.resolveKey({name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0})];function Ud(e){return e.appendBindingParser(e=>Vd(e))}function Wd(e){return e.appendEventMatchResolver((e,t)=>Hd(e,t))}function Gd(e){let t=Ud(e),n=Wd(e);return()=>{n(),t()}}var Kd=Symbol(`keymap:mod-bindings`),qd=/(^|[+,\s])mod(?=\s*\+)/i,Jd=/(^|[+,\s])mod(?=\s*\+)/gi;function Yd(e){let t=e.primaryModifier;return(t===`ctrl`||t===`super`)&&e.modifiers[t]!==`unsupported`?t:e.modifiers.ctrl===`unsupported`?`super`:`ctrl`}function Xd(e){if(e.includes(`,`))return[e];let t=e.trim();return t.includes(` `)?t.split(/\s+/):[e]}function Zd(e){return e.acquireResource(Kd,()=>e.appendBindingExpander(({input:t,displays:n})=>{if(!qd.test(t))return;let r=Yd(e.getHostMetadata());return[{key:t.replace(Jd,(e,t)=>`${t}${r}`),displays:n??Xd(t)}]}))}var Qd=new Map([[` `,`space`],[`Spacebar`,`space`],[`ArrowUp`,`up`],[`ArrowDown`,`down`],[`ArrowLeft`,`left`],[`ArrowRight`,`right`],[`Escape`,`escape`],[`Esc`,`escape`],[`Enter`,`return`],[`Backspace`,`backspace`],[`Delete`,`delete`],[`Tab`,`tab`],[`Home`,`home`],[`End`,`end`],[`PageUp`,`pageup`],[`PageDown`,`pagedown`],[`Insert`,`insert`],[`CapsLock`,`capslock`],[`NumLock`,`numlock`],[`ScrollLock`,`scrolllock`],[`ContextMenu`,`menu`],[`Meta`,`super`],[`OS`,`super`],[`Alt`,`alt`],[`Control`,`control`],[`Shift`,`shift`]]);function $d(e){let t=e?.trim().toLowerCase();return t?t.includes(`mac`)||t.includes(`darwin`)?`macos`:t.includes(`win`)?`windows`:t.includes(`linux`)||t.includes(`x11`)?`linux`:`unknown`:`unknown`}function ef(){let e=globalThis.navigator,t=e?.userAgentData?.platform,n=$d(t);return n===`unknown`?$d(e?.platform??e?.userAgent):n}function tf(){let e=ef();return{platform:e,primaryModifier:e===`macos`?`super`:e===`unknown`?`unknown`:`ctrl`,modifiers:{ctrl:`supported`,shift:`supported`,meta:`supported`,super:`supported`,hyper:`unsupported`}}}function nf(e){return e.length===1&&!/^[a-z0-9]$/i.test(e)}function rf(e){let t={name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0};return!t.shift||!nf(t.name)?[t]:[t,{...t,shift:!1}]}var af=class{name;ctrl;shift;meta;superKey;originalEvent;propagationStopped=!1;constructor(e,t,n,r,i,a){this.name=e,this.ctrl=t,this.shift=n,this.meta=r,this.superKey=i,this.originalEvent=a}get super(){return this.superKey}preventDefault(){this.originalEvent?.preventDefault()}stopPropagation(){this.propagationStopped=!0,this.originalEvent?.stopPropagation()}};function of(){return globalThis.MutationObserver}function sf(e){return Qd.get(e)||(/^F\d{1,2}$/i.test(e)||e.length===1?e.toLowerCase():e.trim().toLowerCase().replace(/\s+/g,``))}function cf(e){if(!e)return new af(`command`,!1,!1,!1,!1);let t=globalThis.KeyboardEvent;return new af(sf(e.key),e.ctrlKey,e.shiftKey,e.altKey,e.metaKey,t&&e instanceof t?e:void 0)}var lf=class{metadata=tf();rootTarget;isDestroyed=!1;observer;targetDestroyListeners=new Map;constructor(e){this.rootTarget=e}getFocusedTarget(){let e=this.rootTarget.ownerDocument.activeElement;return!e||typeof e!=`object`?null:e===this.rootTarget||this.rootTarget.contains(e)?e:null}getParentTarget(e){return e.parentElement}isTargetDestroyed(e){return e===this.rootTarget?!1:!e.isConnected||!this.rootTarget.contains(e)}onKeyPress(e){let t=t=>{e(cf(t))};return this.rootTarget.addEventListener(`keydown`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keydown`,t,{capture:!0})}}onKeyRelease(e){let t=t=>{e(cf(t))};return this.rootTarget.addEventListener(`keyup`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keyup`,t,{capture:!0})}}onFocusChange(e){let t=()=>{queueMicrotask(()=>{e(this.getFocusedTarget())})};return this.rootTarget.addEventListener(`focusin`,t,{capture:!0}),this.rootTarget.addEventListener(`focusout`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`focusin`,t,{capture:!0}),this.rootTarget.removeEventListener(`focusout`,t,{capture:!0})}}onTargetDestroy(e,t){let n=this.targetDestroyListeners.get(e);return n||(n=new Set,this.targetDestroyListeners.set(e,n)),n.add(t),this.ensureObserver(),this.flushDisconnectedTargets(),()=>{let n=this.targetDestroyListeners.get(e);n&&(n.delete(t),n.size===0&&this.targetDestroyListeners.delete(e),this.targetDestroyListeners.size===0&&this.disconnectObserver())}}createCommandEvent(){return cf()}ensureObserver(){if(this.observer||this.targetDestroyListeners.size===0)return;let e=of();e&&(this.observer=new e(()=>{this.flushDisconnectedTargets()}),this.observer.observe(this.rootTarget,{childList:!0,subtree:!0}))}disconnectObserver(){this.observer&&=(this.observer.disconnect(),void 0)}flushDisconnectedTargets(){for(let[e,t]of this.targetDestroyListeners)if(this.isTargetDestroyed(e)){this.targetDestroyListeners.delete(e);for(let e of[...t])e()}this.targetDestroyListeners.size===0&&this.disconnectObserver()}};function uf(e){return new lf(e)}var df=(e,t)=>rf(e).map(e=>t.resolveKey(e));function ff(e){return e instanceof Z?{code:e.code,message:mf(e.message),retryable:e.retryable,...e.need!==void 0&&{need:e.need}}:{code:`HOST_FAILURE`,message:`Host operation failed`,retryable:!1}}function pf(e){try{let t=Cs(e);return new Z(t.message,{code:t.code,retryable:t.retryable,...t.need!==void 0&&{need:t.need}})}catch(e){return new Z(`The host returned a malformed error`,{cause:e,code:`PROTOCOL`,retryable:!1})}}function mf(e){return e.trim().slice(0,512)||`Host operation failed`}var hf=e=>({ok:!0,value:e}),gf=e=>({error:ff(e),ok:!1});async function _f(e,t){let n,r=new Set;try{return n=await e,vf(t(n))}catch(e){throw yf(e)&&bf(e,r),e instanceof Z?e:new Z(`The remote operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}finally{n!==e&&yf(n)&&bf(n,r)}}function vf(e){if(e.ok)return e.value;throw pf(e.error)}function yf(e){return ia(e)&&Symbol.dispose in e&&ji(e[Symbol.dispose])}function bf(e,t){if(!t.has(e)){t.add(e);try{e[Symbol.dispose]()}catch(e){console.warn(`RPC result disposal failed`,e)}}}function xf(){let e=[],t=new Set;return{get:()=>e,subscribe:e=>(t.add(e),()=>t.delete(e)),update:n=>{e=n;for(let e of Array.from(t))try{e()}catch(e){console.warn(`App binding subscriber failed`,e)}}}}function Sf(e){let t=ec(e),n=new Set;return{get:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e)),update:e=>{t=ec(e);for(let e of Array.from(n))try{e()}catch(e){console.warn(`Reserved chord subscriber failed`,e)}}}}function Cf(e){let t=!0,n,r=e.window.document.querySelector(`html`);if(!r)return()=>{t=!1};let i=uf(r),a=new Td(i);Gd(a),Zd(a),a.prependEventMatchResolver(df);let o=Tf(e.onBroken),s=kf(a,e.chords,e.remote,o),c=wf(e,o,()=>t,e=>{n=e},()=>n),l=i.onFocusChange(()=>{queueMicrotask(c)}),u=()=>{queueMicrotask(c)};e.window.addEventListener(`focus`,u),e.window.addEventListener(`blur`,u);let d=e.bindings,f=()=>Ef(e.window.document,e.identity.surfaceId).editing,p=d===void 0?()=>void 0:Df(a,d,f),m=d===void 0?()=>void 0:d.subscribe(()=>{p(),p=Df(a,d,f)}),h=e.chords.subscribe(()=>{s(),s=kf(a,e.chords,e.remote,o)});return queueMicrotask(c),()=>{t&&(t=!1,l(),e.window.removeEventListener(`focus`,u),e.window.removeEventListener(`blur`,u),h(),s(),m(),p())}}function wf(e,t,n,r,i){return()=>{if(!n())return;let a=Ef(e.window.document,e.identity.surfaceId),o=i();(a.editing!==o?.editing||a.surface!==o.surface)&&(r(a),t(()=>e.remote.reportFocus(a)))}}function Tf(e){return t=>{try{_f(t(),ac).catch(t=>{dc(`browser-bridge.host-call`,t),e(t)})}catch(t){dc(`browser-bridge.host-call`,t),e(t)}}}function Ef(e,t){let n=e.activeElement;return ds({editing:!!(n?.matches(`input, textarea, select, [contenteditable='true']`)===!0||n?.closest(`[contenteditable='true']`)),surface:e.hasFocus()?t:null})}function Df(e,t,n){let r=t.get();return e.registerLayer({bindings:r.map((e,t)=>({cmd:`app/${String(t)}`,key:e.key})),commands:r.map((e,t)=>({name:`app/${String(t)}`,run:t=>{let r=t.event.originalEvent;if(r?.defaultPrevented||r?.isComposing||Of(e.key)&&n())return!1;e.run()}})),priority:500})}function Of(e){return!/(?:^|\+)(?:ctrl|control|super|meta|cmd|alt|option|mod)\+/iu.test(e)}function kf(e,t,n,r){let i=t.get();return e.registerLayer({bindings:i.map(e=>({cmd:`reserved/${e.id}`,key:{ctrl:e.ctrlKey,meta:e.altKey,name:sf(e.key),shift:e.shiftKey,super:e.metaKey}})),commands:i.map(e=>({name:`reserved/${e.id}`,run:t=>{let i=t.event.originalEvent;if(i?.defaultPrevented||i?.isComposing)return!1;r(()=>n.invokeReservedChord(e.id,i?.repeat??!1))}})),priority:1e3})}function Af(e){let t=t=>{if(t.defaultPrevented||t.isComposing)return;let n=Nf(t,e.mac);n!==null&&(t.preventDefault(),!t.repeat&&(n===`back`&&e.canGoBack()&&e.back(),n===`forward`&&e.canGoForward()&&e.forward()))},n=t=>{let n=Mf(t.button);if(n===null)return;let r=t.defaultPrevented;t.preventDefault(),!(t.type!==`mouseup`||r)&&(n===`back`&&e.canGoBack()&&e.back(),n===`forward`&&e.canGoForward()&&e.forward())};e.window.addEventListener(`keydown`,t);for(let t of jf)e.window.addEventListener(t,n);return()=>{e.window.removeEventListener(`keydown`,t);for(let t of jf)e.window.removeEventListener(t,n)}}var jf=[`mousedown`,`mouseup`,`auxclick`];function Mf(e){return e===3?`back`:e===4?`forward`:null}function Nf(e,t){return e.shiftKey||e.ctrlKey?null:t?!e.metaKey||e.altKey?null:e.key===`[`?`back`:e.key===`]`?`forward`:Pf(e.target)?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null:!e.altKey||e.metaKey?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null}function Pf(e){return e instanceof HTMLElement?e.isContentEditable||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement:!1}function Ff(){return!Jr(globalThis.navigator)&&/Mac|iPhone|iPad/u.test(globalThis.navigator.userAgent)}var If=class extends Os{#e=!0;#t;#n=new Map;constructor(e){super(),this.#t=e}cancel(e){try{return this.#n.get(fc(e))?.abort(),Promise.resolve(hf(void 0))}catch(e){return Promise.resolve(gf(e))}}dispose(){if(this.#e){this.#e=!1;for(let e of this.#n.values())e.abort();this.#n.clear()}}async invoke(e){try{if(!this.#e)throw new Z(`The command is disposed`,{code:`DISCONNECTED`,retryable:!0});let t=ns(e);if(this.#n.has(t.requestId))throw new Z(`Duplicate command request`,{code:`PROTOCOL`,retryable:!1});if(this.#n.size>=64)throw new Z(`Too many command requests`,{code:`HOST_FAILURE`,retryable:!0});let n=new AbortController;this.#n.set(t.requestId,n);try{let e=await this.#t(ms(t,n.signal)),r=Ss(e);return hf(r===void 0?{status:`handled`}:{status:`handled`,result:r})}finally{this.#n.delete(t.requestId)}}catch(e){if(e instanceof Dr)try{let t={code:e.code,message:e.message,details:e.details};return hf({status:`failed`,error:ro(t)})}catch(e){return gf(e)}return gf(e)}}[Symbol.dispose](){this.dispose()}};function Lf(e){let t=[];for(let n of e.values()){let{commandId:e,definition:r,target:i}=n;if(e===void 0)continue;let a=r.availability?.status!==`unavailable`;for(let n of r.projections?.bindings?.values??[])n.trim().includes(` `)||n.startsWith(`<`)||t.push({key:n,run:()=>{a&&Promise.resolve().then(async()=>{let t=vf(await i.invoke({commandId:e,origin:`keyboard`,requestId:No()}));if(t.status===`failed`)throw new Dr(t.error.code,t.error.message,t.error.details)}).catch(e=>{console.warn(`App key command failed`,e)})}})}return t}function Rf(e,t,n,r){let i=new Map,a=!1,o=()=>{r?.update(a?[]:Lf(i))},s=e=>{try{n()}catch(t){console.warn(`App command failure callback failed`,t,e)}},c=e=>{try{_f(e(),ac).catch(e=>{s(e)})}catch(e){console.warn(`App command RPC supervision failed`,e),s(e)}};return{commands:Bf(e,t,i,()=>a,t=>{let n=i.get(t);if(!n)return;i.delete(t),n.target.dispose(),o();let r=n.commandId;!a&&r!==void 0&&c(()=>e.unregisterCommand(r))},o),dispose(){if(!a){a=!0;for(let e of i.values())e.target[Symbol.dispose]();i.clear(),o()}}}}function zf(e,t,n){let r=t.id;if(e.size>=128||e.has(r))throw n.dispose(),new Z(`Command registration is unavailable`,{code:`INVALID_ARGUMENT`,retryable:!1});let i={commandId:void 0,definition:t,target:n};e.set(r,i);let a=!1;return{commit(e){a||(i.commandId=e)},release(){a||(a=!0,e.get(r)===i&&e.delete(r),n.dispose())},target:n}}function Bf(e,t,n,r,i,a){return Object.freeze({async register(o,s){if(t(),!ji(s))throw new Z(`Command handler must be a function`,{code:`INVALID_ARGUMENT`,retryable:!1});let c=vs(o),l=new If(s),u=zf(n,c,l);try{let t=await Vf(e,c,u.target);r()&&await Hf(e,t.commandId,l),u.commit(t.commandId),a()}catch(e){throw u.release(),e}let d=!0;return()=>{d&&(d=!1,i(c.id))}}})}async function Vf(e,t,n){return _f(e.registerCommand(t,n),Ys)}async function Hf(e,t,n){throw n.dispose(),await _f(e.unregisterCommand(t),ac),new Z(`The command controller is disposed`,{code:`DISCONNECTED`,retryable:!0})}var Uf=wa(e=>e instanceof Rs),Wf=class extends Os{#e=!1;#t;constructor(e){super(),this.#t=e}disconnect(e){try{if(this.#e)throw tp();let t=e===void 0?void 0:Cs(e);return setTimeout(()=>this.#t.disconnect?.(t??ap()),0),Promise.resolve(hf(void 0))}catch(e){return Promise.resolve(gf(e))}}async requestClose(){try{if(this.#e)throw tp();return hf(await(this.#t.beforeClose?.()??!0))}catch(e){return gf(e)}}async requestBack(){try{if(this.#e)throw tp();return hf(await(this.#t.back?.()??!1))}catch(e){return gf(e)}}async requestForward(){try{if(this.#e)throw tp();return hf(await(this.#t.forward?.()??!1))}catch(e){return gf(e)}}async activateNavigation(e){try{if(this.#e)throw tp();let t=Es(e);return Js(this.#t.navigation,t)?hf(await(this.#t.activate?.(t)??!1)):hf(!1)}catch(e){return gf(e)}}async activateStatus(e){try{if(this.#e)throw tp();let t=Xs(e);return Bs(this.#t.statusItems,t)?hf(await(this.#t.statusAction?.(t)??!1)):hf(!1)}catch(e){return gf(e)}}[Symbol.dispose](){this.#e=!0}async updateContext(e){return this.#e?gf(tp()):this.#n(e,`context`,xs,e=>{this.#t.context.update(e)})}reconfigure(e){let t=[];try{if(this.#e)throw tp();let n=$s(e);if(n.context.version<=this.#t.versions.context)return Promise.resolve(hf(void 0));for(let e of n.capabilities)t.push({...e,handle:oo(Uf)(e.handle).dup()});if(!this.#t.capabilities)throw tp();return this.#t.capabilities.replace(t),t=[],this.#t.versions.context=n.context.version,this.#t.context.update(n.context.value),Promise.resolve(hf(void 0))}catch(e){for(let e of t)Us(e.handle);return Promise.resolve(gf(e))}}updateLifecycle(e){try{if(this.#e)throw tp();let t=ss(Ts)(e);if(t.version<=this.#t.versions.lifecycle)return Promise.resolve(hf(void 0));if(!op(this.#t.lifecycle.get(),t.value))throw new Z(`The host sent an invalid lifecycle transition`,{code:`PROTOCOL`,retryable:!1});return this.#t.versions.lifecycle=t.version,this.#t.lifecycle.update(t.value),Promise.resolve(hf(void 0))}catch(e){return Promise.resolve(gf(e))}}async updateReservedChords(e){return this.#e?gf(tp()):this.#n(e,`chords`,ec,e=>{this.#t.chords.update(e)})}async updateTheme(e){return this.#e?gf(tp()):this.#n(e,`theme`,Ms,e=>{this.#t.theme.update(e)})}#n(e,t,n,r){try{let i=ss(n)(e);return i.version>this.#t.versions[t]&&(this.#t.versions[t]=i.version,r(i.value)),Promise.resolve(hf(void 0))}catch(e){return Promise.resolve(gf(e))}}};async function Gf(e){let t=Yf(),n=new Wf(t),r=sc(e.port,n),i,a=Jf(r);try{performance.mark(`fungi.app-open.agar-rpc-connect-start`);let o=await Promise.race([r.connect({epoch:e.epoch,protocolVersion:e.protocolVersion}),a]);performance.mark(`fungi.app-open.agar-rpc-connect-ready`),i=o;let s=vf(os(o));if(!e.isActive())throw qf();let c=Xf({bootstrap:s,bootstrapOwner:i,options:e,remote:r,state:t,target:n});return performance.mark(`fungi.app-open.agar-root-created`),i=void 0,c}catch(t){return cp(t,e,n,r,i)}}function Kf(e,t){e.context.update(t.context.value),e.theme.update(t.theme.value),e.lifecycle.update(t.lifecycle.value),e.chords.update(t.chords.value),e.versions.context=t.context.version,e.versions.theme=t.theme.version,e.versions.lifecycle=t.lifecycle.version,e.versions.chords=t.chords.version}function qf(){return new Z(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function Jf(e){let t,n=new Promise((e,n)=>{t=n});return n.catch(e=>{dc(`app-session.rpc-disconnect`,e)}),e.onRpcBroken(()=>t?.(new Z(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0}))),n}function Yf(){return{statusItems:[],navigation:{canGoBack:!1,canGoForward:!1},bindings:xf(),chords:Sf([]),context:ps({computerId:null,focus:{editing:!1,surface:null},openRequest:null,visibility:`hidden`}),lifecycle:ps(`connecting`),theme:ps(`default`),canGoBack:!1,canGoForward:!1,versions:{chords:-1,context:-1,lifecycle:-1,theme:-1}}}function Xf(e){let t=us(e.bootstrap.identity),n=sp(e.bootstrap);Kf(e.state,n);let r=ts(e.bootstrap.capabilities);return e.state.capabilities=r,Qf(e,t,r)}function Zf(e,t,n){return Cf({bindings:e.state.bindings,chords:e.state.chords,identity:t,onBroken:e=>{n({code:`DISCONNECTED`,message:e instanceof Z?e.message:`The app host rejected a browser bridge operation`,retryable:!0})},remote:e.remote,window:e.options.window})}function Qf(e,t,n){let r=!1,i=t=>{r||(r=!0,rp([()=>{t&&e.state.lifecycle.update(`disconnected`)},()=>{e.state.lifecycle.update(`disposing`)},l,u,()=>{o.dispose()},()=>{e.state.beforeClose=void 0,e.state.back=void 0,e.state.forward=void 0,e.state.activate=void 0,e.state.statusAction=void 0},()=>{n.disconnect()},()=>{e.target[Symbol.dispose]()},()=>{Us(e.bootstrapOwner)},()=>{Us(e.remote)},()=>{e.options.port.close()},()=>{e.state.lifecycle.update(`disposed`)},e.options.onDisposed],`app connection disposal`))},a=()=>{if(r)throw new Z(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})},o=Rf(e.remote,a,()=>{i({code:`DISCONNECTED`,message:`The app host rejected a terminal command operation`,retryable:!0})},e.state.bindings),s=ep(e.remote,a,e.state),c=$f(e.state,e.remote,a),l=Zf(e,t,i),u=Af({window:e.options.window,mac:Ff(),canGoBack:()=>e.state.canGoBack&&e.state.back!==void 0,back:()=>{let t=e.state.back;t&&Promise.resolve().then(t).catch(e=>{dc(`app-window.back-input`,e)})},canGoForward:()=>e.state.canGoForward&&e.state.forward!==void 0,forward:()=>{let t=e.state.forward;t&&Promise.resolve().then(t).catch(e=>{dc(`app-window.forward-input`,e)})}});return e.state.disconnect=i,e.remote.onRpcBroken(()=>{np(i)}),ip({capabilities:n.directory,commands:o.commands,context:e.state.context,dispose:i,identity:t,lifecycle:e.state.lifecycle,theme:e.state.theme,ui:s,window:c})}function $f(e,t,n){let r=Object.freeze({async publish(r){n();let i=es(r);e.canGoBack=i.canGoBack,e.canGoForward=i.canGoForward,e.navigation=_s(i),await _f(t.reportNavigation(i),ac)},onActivate(t){if(n(),e.activate!==void 0)throw new Z(`The App already owns navigation activations`,{code:`INVALID_ARGUMENT`,retryable:!1});e.activate=t;let r=!1;return()=>{r||(r=!0,e.activate===t&&(e.activate=void 0))}},onForward(t){if(n(),e.forward!==void 0)throw new Z(`The App already owns Forward requests`,{code:`INVALID_ARGUMENT`,retryable:!1});e.forward=t;let r=!1;return()=>{r||(r=!0,e.forward===t&&(e.forward=void 0))}},onBack(t){if(n(),e.back!==void 0)throw new Z(`The App already owns Back requests`,{code:`INVALID_ARGUMENT`,retryable:!1});e.back=t;let r=!1;return()=>{r||(r=!0,e.back===t&&(e.back=void 0))}}});return Object.freeze({navigation:r,onBeforeClose(t){if(n(),e.beforeClose!==void 0)throw new Z(`The App already owns a close consultation`,{code:`INVALID_ARGUMENT`,retryable:!1});e.beforeClose=t;let r=!1;return()=>{r||(r=!0,e.beforeClose===t&&(e.beforeClose=void 0))}}})}function ep(e,t,n){return Object.freeze({async requestComputerChoice(){t(),await _f(e.requestComputerChoice(),ac)},async requestBrowserAction(n){t();let r=ls(n);return r.kind===`refused`?r:await _f(e.requestBrowserAction(r),fs)},onStatusAction(e){if(t(),n.statusAction!==void 0)throw new Z(`The App already owns its status actions`,{code:`INVALID_ARGUMENT`,retryable:!1});n.statusAction=e;let r=!1;return()=>{r||(r=!0,n.statusAction===e&&(n.statusAction=void 0))}},async requestAppPermissions(n){return t(),await _f(e.requestAppPermissions(rc(n)),Ps)},async openDesktopSettings(){t(),await _f(e.openDesktopSettings(),ac)},async openSetup(n){return t(),await _f(e.openSetup(Hs(n)),ks)},async openTeamBilling(){t(),await _f(e.openTeamBilling(),ac)},async openNavigation(n){t(),await _f(e.openNavigation(ws(n)),ac)},async reportStatus(r){t();let i=nc(r);n.statusItems=i,await _f(e.reportStatus(i),ac)},async reportAgentSessionSelection(n){t(),await _f(e.reportAgentSessionSelection(gs(n)),ac)},async showToast(n){t(),await _f(e.showToast(Ks(n)),ac)}})}function tp(){return new Z(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})}function np(e){e({code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!0})}function rp(e,t){for(let n of e)try{n()}catch(e){console.warn(`${t} cleanup failed`,e)}}function ip(e){return Object.freeze(e)}function ap(){return{code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!1}}function op(e,t){return e===t||e===`connected`&&t===`suspended`||e===`suspended`&&t===`connected`}function sp(e){let t=ss(xs)(e.context),n=ss(Ms)(e.theme),r=ss(Ts)(e.lifecycle),i=ss(ec)(e.reservedChords);if(r.value!==`connected`&&r.value!==`suspended`)throw new Z(`The bootstrap lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return{chords:i,context:t,lifecycle:r,theme:n}}function cp(e,t,n,r,i){throw rp([()=>{n[Symbol.dispose]()},()=>{i&&Us(i)},()=>{Us(r)},()=>{t.port.close()},t.onDisposed],`app connection rejection`),e instanceof Z?e:new Z(`Unable to establish the app RPC session`,{cause:e,code:`PROTOCOL`,retryable:!1})}var lp=!1,up=class{options;#e;#t;#n=!1;#r;#i;constructor(e){this.options=e,this.#e=globalThis.window}start(){performance.mark(`fungi.app-open.agar-connect-start`);let e=this.#l();return e?Promise.reject(e):(lp=!0,this.#a())}#a(){return new Promise((e,t)=>{let n=(n,a)=>{this.#o(n,a,i,r,e,t)},r=()=>{n(fp())},i=e=>{this.#s(e,n,i)};this.#e.addEventListener(`message`,i),this.options.signal?.addEventListener(`abort`,r,{once:!0});let a=()=>{try{performance.mark(`fungi.app-open.agar-ready-sent`),this.#e.parent.postMessage({protocolVersion:3,type:Is},`*`),this.#e.parent.postMessage({protocolVersion:2,type:Qs},`*`)}catch(e){dc(`connect.notify-host`,e),n(vp(e))}};this.#r=setInterval(a,200),this.#i=setTimeout(()=>{n(mp())},1e4),a()})}#o(e,t,n,r,i,a){if(!this.#n){if(this.#n=!0,this.#c(),this.#e.removeEventListener(`message`,n),this.options.signal?.removeEventListener(`abort`,r),e||!t){this.#t?.close(),lp=!1,a(e??mp());return}i(t)}}#s(e,t,n){if(!_p(e.data))return;if(performance.mark(`fungi.app-open.agar-connect-received`),e.source!==this.#e.parent||hp(e.origin)===void 0){t(gp());return}let r=yp(e,t);if(!r)return;let i=e.ports.length===1?e.ports[0]:void 0;if(!i){t(bp(`The app host did not transfer exactly one port`));return}this.#t=i,this.#c(),this.#e.removeEventListener(`message`,n),Gf({epoch:r.epoch,protocolVersion:r.protocolVersion,isActive:()=>!this.#n,onDisposed:()=>{lp=!1},port:i,window:this.#e}).then(e=>{performance.mark(`fungi.app-open.agar-root-ready`),t(void 0,e)},e=>{t(pp(e))})}#c(){clearInterval(this.#r),clearTimeout(this.#i),this.#r=void 0,this.#i=void 0}#l(){if(this.options.signal?.aborted)return fp();if(lp)return new Z(`An app connection is already live`,{code:`IDENTITY`,retryable:!1});if(Jr(globalThis.window)||this.#e.parent===this.#e)return new Z(`The app host is unavailable`,{code:`DISCONNECTED`,retryable:!0})}};function dp(e){return new up(e).start()}function fp(){return new Z(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function pp(e){return e instanceof Z?e:new Z(`Unable to connect to the app host`,{cause:e,code:`PROTOCOL`,retryable:!1})}function mp(){return new Z(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0})}function hp(e){if(!URL.canParse(e))return;let t=new URL(e).origin;return t===e?t:void 0}function gp(){return new Z(`The app connection identity is invalid`,{code:`IDENTITY`,retryable:!1})}var _p=eo(G({type:X(Ns)}));function vp(e){return new Z(`Unable to notify the app host`,{cause:e,code:`DISCONNECTED`,retryable:!0})}function yp(e,t){try{return cs(e.data)}catch(e){dc(`connect.decode-message`,e),t(e instanceof Z?e:new Z(`Malformed app connection`,{cause:e,code:`PROTOCOL`,retryable:!1}));return}}function bp(e){return new Z(e,{code:`PROTOCOL`,retryable:!1})}function xp(e,t,n){e.style.isolation=`isolate`;let r=(0,Gc.createRoot)(e),i=new AbortController,a=e.ownerDocument.documentElement,o=Dc(a),s,c,l,u=!1,d=e=>{let i=(0,Q.createElement)(Sp,{state:e,render:n});r.render(t.queryClient?(0,Q.createElement)(Mr,{client:t.queryClient},i):i)},f=()=>{l?.(),l=void 0,c?.(),c=void 0;let e=s;s=void 0,e?.dispose(),u&&=(o===null?a.removeAttribute(`data-theme`):Ec(o,a),!1)},{defaultView:p}=e.ownerDocument;return performance.mark(`fungi.app-open.react-root-render-start`),p?p.parent===p?d({app:null,status:`standalone`}):(d({app:null,status:`connecting`}),dp({host:`parent`,signal:i.signal}).then(e=>{if(i.signal.aborted){e.dispose();return}s=e;let t=()=>{let t=e.lifecycle.get();return t===`disposing`||t===`disconnected`||t===`disposed`?(f(),d({app:null,status:`ended`}),!0):!1};l=e.lifecycle.subscribe(t),!t()&&(u=!0,Ec(e.theme.get(),a),c=e.theme.subscribe(e=>{Ec(e,a)}),d({app:e,status:`live`}))}).catch(e=>{i.signal.aborted&&e instanceof Z&&e.code===`CANCELLED`||(console.error(`${t.name} host connection failed`,e),f(),i.signal.aborted||d({app:null,status:`not-hosted`,error:e instanceof Z?e:new Z(`The App host is unavailable`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}))})):d({app:null,status:`not-hosted`,error:new Z(`The App document has no window`,{code:`DISCONNECTED`,retryable:!1})}),()=>{i.signal.aborted||(i.abort(),r.unmount(),f())}}function Sp({state:e,render:t}){return(0,Q.useLayoutEffect)(()=>{performance.mark(`fungi.app-open.react-initial-commit`)},[]),(0,Q.useLayoutEffect)(()=>{e.app&&performance.mark(`fungi.app-open.react-connected-commit`)},[e.app]),(0,Q.createElement)(Q.Fragment,null,e.status===`not-hosted`?(0,Q.createElement)(`p`,{role:`alert`},`App host connection unavailable. Open this App through its host to try again.`):null,t(e))}function Cp(e){let t=(0,Q.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,Q.useCallback)(()=>e?.get(),[e]);return(0,Q.useSyncExternalStore)(t,n,n)}function wp(e){return Cp(e?.context)??null}function Tp(e,t,n,r){let i=(0,Q.useRef)(t);i.current=t;let a=(0,Q.useRef)(n);a.current=n;let o=(0,Q.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,Q.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,Q.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,Q.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function Ep(e,{canGoBack:t,canGoForward:n,title:r,crumbs:i,primary:a,menu:o,status:s,onBack:c,onForward:l,onCrumb:u,onAction:d}){let f=(0,Q.useRef)(c),p=(0,Q.useRef)(l),m=(0,Q.useRef)(u),h=(0,Q.useRef)(d);(0,Q.useEffect)(()=>{f.current=c,p.current=l,m.current=u,h.current=d},[c,l,u,d]),(0,Q.useEffect)(()=>{if(!e)return;let t=e.onBack(()=>f.current()),n=e.onForward(()=>p.current()),r=e.onActivate(e=>{if(e.kind===`action`){let t=h.current;return t?.(e.actionId),t!==void 0}let t=m.current;return e.siblingId===void 0?t?.(e.crumbId):t?.(e.crumbId,e.siblingId),t!==void 0});return()=>{t(),n(),r(),Dp(e,{canGoBack:!1,canGoForward:!1})}},[e]);let g=JSON.stringify([i,a,o,s]),_=(0,Q.useRef)({crumbs:i,primary:a,menu:o,status:s});(0,Q.useEffect)(()=>{_.current={crumbs:i,primary:a,menu:o,status:s}},[i,a,o,s]),(0,Q.useEffect)(()=>{if(!e)return;let i={canGoBack:t,canGoForward:n};r!==void 0&&(i={...i,title:r});let a=_.current;a.crumbs!==void 0&&(i={...i,crumbs:a.crumbs}),a.primary!==void 0&&(i={...i,primary:a.primary}),a.menu!==void 0&&(i={...i,menu:a.menu}),a.status!==void 0&&(i={...i,status:a.status}),Dp(e,i)},[e,t,n,r,g])}function Dp(e,t){e.publish(t).catch(e=>{e instanceof Z&&e.code===`DISCONNECTED`||console.warn(`App navigation report failed`,e)})}var Op=class extends Event{code;message;constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(jp(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(jp(this),t)}};function kp(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function Ap(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(Ap).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${Ap(e.cause)}`:e.message:`${e}`}function jp(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Mp=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},Np=10,Pp=13,Fp=32,Ip=6;function Lp(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{maxBufferSize:t,onComment:n,onError:r,onEvent:i,onId:a,onRetry:o}=e,s=[],c=0,l=!0,u,d=``,f=0,p,m=!1,h=!1,g=!1;function _(e){if(m)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,e.charCodeAt(0)===65279?e=e.slice(1):e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),(h||g)&&(e=v(e),!e))return;if(!s.length){let t=S(e);t!==``&&y(t),x();return}if(e.indexOf(`
|
|
3
|
-
`)===-1&&e.indexOf(`\r`)===-1){if(c<Ip&&!b(s.join(``)+e.slice(0,Ip-c))){s.length=0,c=0,h=!0;return}s.push(e),c+=e.length,x();return}s.push(e);let t=s.join(``);s.length=0,c=0,y(S(t)),x()}function v(e){if(e.length===0)return e;if(g)return g=!1,e.charCodeAt(0)===Np?e.slice(1):e;let t=e.indexOf(`\r`),n=e.indexOf(`
|
|
4
|
-
`),r=t===-1?n:n===-1||t<n?t:n;return r===-1?``:r===e.length-1&&e.charCodeAt(r)===Pp?(h=!1,g=!0,``):(h=!1,e.slice(r+(e.charCodeAt(r)===Pp&&e.charCodeAt(r+1)===Np?2:1)))}function y(e){if(e){if(e.charCodeAt(e.length-1)===Pp){C(e,0,e.length-1),g=!0;return}if(b(e)){s.push(e),c=e.length;return}h=!0}}function b(e){let t=e.charCodeAt(0);return t===58&&!!n||t===100&&Bp(e,`data`)||t===101&&Bp(e,`event`)||t===105&&Bp(e,`id`)||t===114&&Bp(e,`retry`)}function x(){t!==void 0&&(c+d.length<=t||(m=!0,s.length=0,c=0,u=void 0,d=``,f=0,p=void 0,h=!1,g=!1,r?.(new Mp(`Buffered data exceeded max buffer size of ${t} characters`,{type:`max-buffer-size-exceeded`}))))}function S(e){let t=0;if(e.indexOf(`\r`)===-1){let n=e.indexOf(`
|
|
5
|
-
`,t);for(;n!==-1;){if(t===n){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0,t=n+1,n=e.indexOf(`
|
|
6
|
-
`,t);continue}let r=e.charCodeAt(t);if(Rp(e,t,r)){let r=e.charCodeAt(t+5)===Fp?t+6:t+5,o=e.slice(r,n);if(f===0&&e.charCodeAt(n+1)===Np){u!==void 0&&a?.(u),i?.({id:u,event:p,data:o}),u=void 0,d=``,p=void 0,t=n+2,n=e.indexOf(`
|
|
7
|
-
`,t);continue}d=f===0?o:`${d}\n${o}`,f++}else zp(e,t,r)?p=e.slice(e.charCodeAt(t+6)===Fp?t+7:t+6,n)||void 0:C(e,t,n);t=n+1,n=e.indexOf(`
|
|
8
|
-
`,t)}return e.slice(t)}for(;t<e.length;){let n=e.indexOf(`\r`,t),r=e.indexOf(`
|
|
9
|
-
`,t),i=-1;if(n!==-1&&r!==-1?i=n<r?n:r:n===-1?r!==-1&&(i=r):i=n===e.length-1?-1:n,i===-1)break;C(e,t,i),t=i+1,e.charCodeAt(t-1)===Pp&&e.charCodeAt(t)===Np&&t++}return e.slice(t)}function C(e,t,r){if(t===r){T();return}let i=e.charCodeAt(t);if(Rp(e,t,i)){let n=e.charCodeAt(t+5)===Fp?t+6:t+5,i=e.slice(n,r);d=f===0?i:`${d}\n${i}`,f++;return}if(zp(e,t,i)){p=e.slice(e.charCodeAt(t+6)===Fp?t+7:t+6,r)||void 0;return}if(i===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let n=e.slice(e.charCodeAt(t+3)===Fp?t+4:t+3,r);n.includes(`\0`)||(u=n);return}if(i===58){if(n){let i=e.slice(t,r);n(i.slice(e.charCodeAt(t+1)===Fp?2:1))}return}let a=e.slice(t,r),o=a.indexOf(`:`);if(o===-1){w(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===Fp?2:1;w(s,a.slice(o+c),a)}function w(e,t,n){switch(e){case`event`:p=t||void 0;break;case`data`:d=f===0?t:`${d}\n${t}`,f++;break;case`id`:t.includes(`\0`)||(u=t);break;case`retry`:/^\d+$/.test(t)?o?.(parseInt(t,10)):r?.(new Mp(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:n}));break;default:r?.(new Mp(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:`unknown-field`,field:e,value:t,line:n}))}}function T(){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0}function E(e={}){if(e.consume&&s.length>0){let e=s.join(``);C(e,0,e.length)}l=!0,u=void 0,d=``,f=0,p=void 0,s.length=0,c=0,m=!1,h=!1,g=!1}return{feed:_,reset:E}}function Rp(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function zp(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}function Bp(e,t){let n=1;for(;n<e.length&&n<t.length;){if(e.charCodeAt(n)!==t.charCodeAt(n))return!1;n++}return e.length<=t.length||e.charCodeAt(t.length)===58}var Vp=104857600,Hp=class extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSED=2;CONNECTING=0;OPEN=1;CLOSED=2;get readyState(){return this.#e}get url(){return this.#t.href}get withCredentials(){return this.#r}get onerror(){return this.#u}set onerror(e){this.#u&&this.removeEventListener(`error`,this.#u),this.#u=e,e&&this.addEventListener(`error`,e)}get onmessage(){return this.#d}set onmessage(e){this.#d&&this.removeEventListener(`message`,this.#d),this.#d=e,e&&this.addEventListener(`message`,e)}get onopen(){return this.#f}set onopen(e){this.#f&&this.removeEventListener(`open`,this.#f),this.#f=e,e&&this.addEventListener(`open`,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}constructor(e,t){super();try{if(e instanceof URL)this.#t=e;else if(typeof e==`string`)this.#t=new URL(e,Wp());else throw Error(`Invalid URL`)}catch{throw kp(`An invalid or illegal string was specified`)}this.#l=Lp({maxBufferSize:t?.maxBufferSize??Vp,onEvent:this.#v,onError:this.#b,onId:this.#_,onRetry:this.#y}),this.#e=this.CONNECTING,this.#a=3e3,this.#i=t?.fetch??globalThis.fetch,this.#r=t?.withCredentials??!1,this.#p()}close(){this.#o&&clearTimeout(this.#o),this.#e!==this.CLOSED&&(this.#c&&this.#c.abort(),this.#e=this.CLOSED,this.#c=void 0)}#e;#t;#n;#r;#i;#a;#o;#s=null;#c;#l;#u=null;#d=null;#f=null;#p(){this.#e=this.CONNECTING,this.#c=new AbortController;let e=this.#i;e(this.#t,this.#g()).then(this.#m).catch(this.#h)}#m=async e=>{this.#l.reset();let{body:t,redirected:n,status:r,headers:i}=e;if(r===204){this.#x(`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(this.#n=n?new URL(e.url):void 0,r!==200){this.#x(`Non-200 status code (${r})`,r);return}if(!(i.get(`content-type`)||``).startsWith(`text/event-stream`)){this.#x(`Invalid content type, expected "text/event-stream"`,r);return}if(this.#e===this.CLOSED)return;this.#e=this.OPEN;let a=new Event(`open`);if(this.dispatchEvent(a),typeof t!=`object`||!t||!(`getReader`in t)){this.#x(`Invalid response body, expected a web ReadableStream`,r),this.close();return}let o=new TextDecoder,s=t.getReader(),c=!0;do{let{done:e,value:t}=await s.read();if(this.#e===this.CLOSED){c=!1;break}t&&this.#l.feed(o.decode(t,{stream:!e})),e&&(c=!1,this.#l.reset(),this.#S())}while(c)};#h=e=>{this.#c=void 0,e.name!==`AbortError`&&e.type!==`aborted`&&this.#S(Ap(e))};#g(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...this.#s?{"Last-Event-ID":this.#s}:void 0},cache:`no-store`,signal:this.#c?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e}#_=e=>{this.#s=e};#v=e=>{let t=this.#n?this.#n.origin:this.#t.origin,n=this.#s??``,r=new MessageEvent(e.event||`message`,{data:e.data,origin:t,lastEventId:n});r.origin!==t&&Gp(r,`origin`,t),r.lastEventId!==n&&Gp(r,`lastEventId`,n),this.dispatchEvent(r)};#y=e=>{this.#a=e};#b=e=>{e.type===`max-buffer-size-exceeded`&&(this.close(),this.#x(e.message))};#x(e,t){this.#e!==this.CLOSED&&(this.#e=this.CLOSED);let n=new Op(`error`,{code:t,message:e});this.dispatchEvent(n)}#S(e,t){if(this.#e===this.CLOSED)return;this.#e=this.CONNECTING;let n=new Op(`error`,{code:t,message:e});this.dispatchEvent(n);let r=setTimeout(this.#C,this.#a);typeof r==`object`&&r&&`unref`in r&&r.unref(),this.#o=r}#C=()=>{this.#o=void 0,this.#e===this.CONNECTING&&this.#p()}};Object.defineProperty(Hp,"name",{value:`EventSource`}),Object.defineProperty(Hp,Symbol.for(`eventsource.supports-fetch-override`),{value:!0,writable:!1,configurable:!1,enumerable:!1});var Up=Hp;function Wp(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}function Gp(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0})}var Kp=Y.check(Ta(1),J(256)),qp=Da.check(La(),Yo(0)),Jp=q([G({agentId:Kp,sessionId:Kp,title:Y.check(J(4096)),triggerId:Ca(Kp),createdAt:qp,lastActivityAt:qp,settledAt:Ca(qp),visitedAt:Ca(qp),state:Ra([`needs_you`,`running`,`errored`,`done`])}),G({agentId:Kp,sessionId:Kp,state:X(`unavailable`)})]),Yp=G({runId:Kp,nodeId:Kp,iteration:Kp}),Xp=G({kind:X(`workflow-review`),key:Yp,installationId:Kp,workflowId:vo(Kp),workflowTitle:Y,reviewTitle:Y,reviewers:Ra([`runner`,`owners`]),show:uo(Ia),choices:Ca(uo(Kp)),openedAt:qp,expiresAt:qp,state:Ra([`pending`,`answered`,`delivered`,`timed_out`,`closed`])}),Zp=q([Jp,Xp]),Qp=q([Zp,G({agentId:Kp,sessionId:Kp,deleted:X(!0)})]);function $p(e,t){return`${e}\u0000${t}`}function em(e){return`kind`in e?JSON.stringify([e.kind,e.installationId,e.key.runId,e.key.nodeId,e.key.iteration]):$p(e.agentId,e.sessionId)}var tm=Y.pipe(K(Ta(1),J(256))),nm=G({kind:X(`seller-closed`),dispositionId:Y.pipe(K(Ta(1),J(1024))),sellerAccountId:tm,buyerAccountId:tm,appId:tm,releaseIds:Fa([tm]),displayName:tm,sellerName:tm,requestId:tm}),rm={BACKGROUND:{name:`BACKGROUND`,operations:{admit:{cap:`app.background.admit`,requires:[],effect:`read`}}},GIT:{name:`GIT`,operations:{create:{cap:`app.git.create`,requires:[`git.repository`],effect:`write`},fork:{cap:`app.git.fork`,requires:[`git.repository`],effect:`write`},read:{cap:`app.git.read`,requires:[`git.repository`],effect:`read`},write:{cap:`app.git.write`,requires:[`git.repository`],effect:`write`},exchange:{cap:`app.git.exchange`,requires:[`git.repository`],effect:`write`}}},EVENTS:{name:`EVENTS`,operations:{emit:{cap:`app.events.emit`,requires:[`app.events.emit`],effect:`write`}}},APPS:{name:`APPS`,operations:{register:{cap:`app.register`,requires:[`git.repository`],effect:`write`},repository:{cap:`app.catalog.read`,requires:[`git.repository`],effect:`read`},build:{cap:`app.build`,requires:[`git.repository`,`computer.execute`],effect:`write`},buildStatus:{cap:`app.build`,requires:[`git.repository`,`computer.execute`],effect:`read`},select:{cap:`app.select`,requires:[`git.repository`,`computer.execute`],effect:`write`},catalog:{cap:`app.catalog.read`,requires:[`team.workbenchHost`],effect:`read`},fork:{cap:`app.fork`,requires:[`git.repository`],effect:`write`}}},WORKFLOWS:{name:`WORKFLOWS`,operations:{catalog:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`},runGraph:{cap:`app.workflow.run`,requires:[`workflow.run`],effect:`write`},armSchedule:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},disarmSchedule:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},pauseSchedule:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},resumeSchedule:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},schedules:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`},armEventTrigger:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},disarmEventTrigger:{cap:`app.workflow.run`,requires:[`workflow.run`,`workflow.arm`],effect:`write`},eventTriggers:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`},cancel:{cap:`app.workflow.run`,requires:[`workflow.run`],effect:`write`},answerReview:{cap:`app.workflow.run`,requires:[`workflow.run`],effect:`write`},graphStatus:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`},runs:{cap:`app.workflow.read`,requires:[`workflow.run`],effect:`read`}}},APP_STORAGE:{name:`APP_STORAGE`,operations:{read:{cap:`app.storage.read`,requires:[`app.storage`],effect:`read`},write:{cap:`app.storage.write`,requires:[`app.storage`],effect:`write`},reset:{cap:`app.storage.write`,requires:[`app.storage`],effect:`write`}}},MEDIA:{name:`MEDIA`,operations:{models:{cap:`app.media.read`,requires:[`media.generation`],effect:`read`},generate:{cap:`app.media.generate`,requires:[`media.generation`,`computer.writeFile`],effect:`write`}}},COMPUTER:{name:`COMPUTER`,operations:{list:{cap:`app.computer.read`,requires:[`computer.list`],effect:`read`},read:{cap:`app.computer.read`,requires:[`computer.readFile`],effect:`read`},ports:{cap:`app.computer.read`,requires:[`computer.execute`],effect:`read`},processes:{cap:`app.computer.read`,requires:[`computer.execute`],effect:`read`},gitChanges:{cap:`app.computer.read`,requires:[`computer.readFile`],effect:`read`},write:{cap:`app.computer.write`,requires:[`computer.writeFile`],effect:`write`},mkdir:{cap:`app.computer.write`,requires:[`computer.writeFile`],effect:`write`},move:{cap:`app.computer.write`,requires:[`computer.writeFile`],effect:`write`},preview:{cap:`app.computer.exec`,requires:[`computer.execute`],effect:`write`},processKill:{cap:`app.computer.exec`,requires:[`computer.execute`],effect:`write`},processStart:{cap:`app.computer.exec`,requires:[`computer.execute`],effect:`write`},exec:{cap:`app.computer.exec`,requires:[`computer.execute`],effect:`write`}}},INBOX:{name:`INBOX`,operations:{page:{cap:`inbox.read`,requires:[`agent.read`],effect:`read`},visit:{cap:`inbox.visit`,requires:[`agent.read`],effect:`write`}}},AGENTS:{name:`AGENTS`,operations:{list:{cap:`agent.list`,requires:[`agent.list`],effect:`read`},send:{cap:`agent.send`,requires:[`agent.send`],effect:`write`},schedules:{cap:`agent.read`,requires:[`agent.read`],effect:`read`},pauseSchedule:{cap:`agent.manage`,requires:[`agent.manage`],effect:`write`},resumeSchedule:{cap:`agent.manage`,requires:[`agent.manage`],effect:`write`},deleteSchedule:{cap:`agent.manage`,requires:[`agent.manage`],effect:`write`}}}},im=[`dashboard`,`inbox`,`files`,`media`,`sessions`,`terminal`],am=`approvals,agent.list,agent.manage,agent.rename,agent.avatar,agent.instructions,agent.toolPolicy,agent.read,agent.send,computer.list,computer.readFile,computer.writeFile,computer.execute,llm.generation,media.generation,media.share,games:servers,git.repository,apps.open,apps.call,app.storage,app.events.emit,team.workbenchHost,marketplace.browse,marketplace.purchase,workflow.run,workflow.publish,workflow.arm,world,channels.read,channels.personal.manage`.split(`,`),om=[`file.open`],sm=[`team`,`member`],cm=Object.freeze({capabilities:[],handlers:[],roles:[]}),lm=Object.freeze([`owner`,`admin`,`member`]),um=Di(()=>_i(lm));function dm(e,t){if(t===void 0)return!0;let n=e?.methods[t.method];return n?.effect===`write`&&Object.values(e?.methods??{}).every(e=>e.effect!==`write`||e.requires.every(e=>n.requires.includes(e)))}var fm=Object.freeze({intrinsic:[`constructor`,`toString`,`valueOf`,`hasOwnProperty`,`isPrototypeOf`,`propertyIsEnumerable`,`toLocaleString`],rpc:[`then`,`dup`,`connect`,`id`,`name`],instance:[`ctx`,`env`],lifecycle:[`gill`,`onGitPush`,`syncRefused`,`authorizeGitPush`,`onRegion`,`fetch`,`alarm`,`queue`,`scheduled`,`tail`,`trace`,`email`,`test`,`tailStream`,`webSocketMessage`,`webSocketClose`,`webSocketError`]}),pm=Wn().check(ii(1),zi(256)),mm=bt(`kind`,[jt({kind:r(`team`),teamId:pm}),jt({kind:r(`standalone`),tenant:pm})]),hm=Rn({kind:r(`member`),memberId:pm}),gm=Rn({kind:r(`agent`),agentId:pm}),_m=Rn({kind:r(`team-key`),keyId:pm}),vm=bt(`kind`,[hm,gm,_m]),ym=Rn({workflowId:pm,runId:pm,nodeId:pm,armedBy:vm}),bm=ht(()=>jt({method:Wn().check(gn(e=>Em(e))),seal:Wn().check(ri(/^[A-Za-z0-9_-]{43}$/u))})),xm=Rn({scope:mm,computerId:Yt(pm),actor:vm,backgroundLane:ar(Wn().check(ii(8),zi(263))),backgroundOrigin:ar(bm),role:ar(um),soleMember:ar(r(!0)),workflow:ar(ym),idempotencyKey:ar(Wn().check(ii(1),zi(128)))}),Sm=bt(`kind`,[jt(hm.shape),jt(gm.shape),jt(_m.shape)]),Cm=jt({...xm.shape,actor:Sm,workflow:ar(jt({...ym.shape,armedBy:Sm}))}),wm=(e,t=!1)=>Tm((t?Cm:xm).parse(e));function Tm(e){if(e.soleMember!==void 0&&(e.actor.kind!==`member`||e.workflow!==void 0))throw Error(`Only a member's own call can be its Team's sole member`);if(e.backgroundLane===void 0!=(e.backgroundOrigin===void 0))throw Error(`Background lane and origin must be attested together`);if(e.backgroundLane!==void 0&&(e.actor.kind!==`member`||e.workflow!==void 0||e.backgroundLane!==`member:${e.actor.memberId}`))throw Error(`Background lane must name an ordinary member`);return e}var Em=e=>e.length<=80&&/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/.test(e)&&!Object.values(fm).flat().some(t=>t===e),Dm=65536,Om=1048576,km=e=>new TextEncoder().encode(e).byteLength,Am=Wn().check(ii(1),zi(64)),jm=Wn().check(gn(e=>km(e)<=Dm));bt(`kind`,[jt({kind:r(`connect`),connection:Am,caller:xm}),jt({kind:r(`message`),connection:Am,data:jm}),jt({kind:r(`close`),connection:Am}),jt({kind:r(`alarm`)})]),jt({send:ar(ut(jt({connection:Am,data:jm})).check(zi(256),gn(e=>e.reduce((e,{data:t})=>e+km(t),0)<=Om))),close:ar(ut(Am).check(zi(256))),wakeAt:ar(Yt(mr().check(Ne(),Xr(),Wr(2**53-1))))});var Mm=Y.check(Ha(Em));function Nm(e){return typeof e==`object`&&!!e}function Pm(e,t=0){if(t>16)return!1;if(Nm(e)){for(let n of Object.values(e))if(!Pm(n,t+1))return!1}return!0}var Fm=_a.pipe(K(Ha(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=2e4&&Pm(e),{message:`App API schema exceeds its byte or depth bound`}))),Im=Y.check(Ta(1),J(128)),Lm=G({description:Y.pipe(K(Ta(1)),K(J(1e3))),input:Fm,output:Fm,pending:ba(X(!0)),hidden:ba(X(!0)),present:ba(G({verb:Y.check(Ta(1),J(32))})),effect:Ra([`read`,`write`,`external`]),requires:uo(Ra(am)).pipe(K(Ha(e=>new Set(e).size===e.length)))}),Rm=G({methods:Aa(Y,Lm).pipe(K(Ha(e=>Object.keys(e).every(eo(Mm)),{message:`Invalid App API method name`})),K(Ha(e=>Object.keys(e).length<=64)),K(Ha(e=>{let t=Object.keys(e);return t.every(e=>!t.some(t=>t.startsWith(`${e}.`)))},{message:`App API method name is also a method group`}))),toolFamily:Ca(G({name:Mm.check(Ha(e=>!e.includes(`.`))),list:Mm,call:Mm})),events:Ca(Aa(Y,G({description:Y.check(Ta(1),J(1e3)),payload:Fm})).check(Ha(e=>Object.keys(e).every(eo(Im)),{message:`Invalid App API event name`}),Ha(e=>Object.keys(e).length<=64)))}).pipe(K(Ha(e=>{if(e.toolFamily===void 0)return!0;let{name:t,list:n,call:r}=e.toolFamily,i=e.methods[n],a=e.methods[r];return i?.effect===`read`&&a!==void 0&&a.effect!==`external`&&a.hidden!==!0&&!Object.keys(e.methods).some(e=>e.split(`.`)[0]===t)},{message:`Tool family must reference declared callable methods in a distinct namespace`})),K(Ha(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=256e3,{message:`App API exceeds its total byte bound`}))),zm=e=>new Set(e).size===e.length;function Bm(e,t){let n=Object.keys(t);for(let e of n)oo(Mm)(e);return{declaration:G({name:X(e),operations:uo(Ra(n)).pipe(K(Ta(1)),K(J(n.length)),K(Ha(zm)))}),shard:G({name:X(e),operations:uo(q(Object.entries(t).map(([e,t])=>G({name:X(e),cap:X(t.cap)})))).pipe(K(Ta(1)),K(J(n.length)),K(Ha(e=>zm(e.map(e=>e.name)),{message:`App backend operation repeated`})))})}}var Vm=Object.values(rm).map(e=>Bm(e.name,e.operations)),Hm=Vm.length,Um=uo(q(Vm.map(e=>e.declaration))).pipe(K(J(Hm)),K(Ha(e=>zm(e.map(e=>e.name)))));uo(q(Vm.map(e=>e.shard))).pipe(K(J(Hm)),K(Ha(e=>zm(e.map(e=>e.name)))));var Wm=new Map(Object.entries(rm).map(([e,t])=>[e,new Map(Object.entries(t.operations))]));function Gm(e,t){return Wm.get(e)?.get(t)}var Km=Ra(im),qm=Ra(am),Jm=Ra(om),Ym={message:`App declaration entries must be unique`},Xm=e=>new Set(e).size===e.length,Zm=new Set([`super+k`,`meta+k`,`cmd+k`,`mod+k`,`ctrl+k`,`control+k`]),Qm=Y.pipe(K(J(256)),K(Ha(e=>e.trim().length>0,{message:`Declared command text must not be blank`}))),$m={order:ba(Xo)},eh=G($m),th=G({id:Qm.pipe(K(Ha(e=>!e.includes(`:`),{message:`Declared command IDs are namespace-local`}))),title:Qm,category:Qm,description:ba(Y.pipe(K(J(1024)))),sigil:ba(Qm.pipe(K(J(64)))),projections:ba(G({bindings:ba(G({...$m,values:uo(Qm).pipe(K(J(16)),K(Ha(e=>!e.some(e=>Zm.has(e.trim().toLowerCase())),{message:`Apps cannot bind the reserved leader chord`})))})),agent:ba(G({...$m,keybind:ba(Y)})),help:ba(eh),menu:ba(eh),palette:ba(eh),slash:ba(G({...$m,aliases:uo(Qm).pipe(K(J(16)))}))}))}),nh=e=>Xm(e.map(e=>e.id))&&Xm(e.flatMap(e=>e.projections?.slash?.aliases??[])),rh=e=>Xm(e.map(e=>e.id)),ih=Y.check(Ba(/^[a-z][a-z0-9.-]{0,63}$/)),ah=G({key:ih,scopes:uo(Ra(sm)).check(Ta(1),Ha(Xm,Ym)),maxBytes:Xo.check(So({minimum:1,maximum:65536}))}),oh=Io()([ah],([e])=>(t,n,r)=>Ro(e)(t,{...r,onExcessProperty:`error`}),{toCodecJson:()=>new _o(ah.ast,Zo())}),sh=G({appId:Y.check(Ta(1),J(128)),methods:uo(Mm).check(Ta(1),J(16),Ha(Xm,Ym))}),ch=Io()([sh],([e])=>(t,n,r)=>Ro(e)(t,{...r,onExcessProperty:`error`}),{toCodecJson:()=>new _o(sh.ast,Zo())}),lh=uo(ch).check(Ta(1),J(16),Ha(e=>Xm(e.map(e=>e.appId)),Ym)),uh=e=>G({api:Ca(Rm),displayName:ba(Y.pipe(K(Ta(1)),K(J(64)))),capabilities:uo(qm).pipe(K(Ha(Xm,Ym))),calls:Ca(lh),guidance:ba(Y.pipe(K(Ta(1)),K(J(12e3)))),handlers:uo(Jm).pipe(K(Ha(Xm,Ym))),receives:Ca(uo(X(`git.push`)).check(J(1),Ha(Xm,Ym))),icon:Ca(Y.pipe(K(Ta(1)),K(J(80)))),roles:uo(Km).pipe(K(Ha(Xm,Ym))),storage:Ca(uo(oh).check(J(16),Ha(e=>Xm(e.map(e=>e.key)),Ym))),commands:ba(uo(th).pipe(K(J(64)),K(Ha(nh,{message:`Declared command IDs and slash aliases must be unique`})))),gills:ba(uo(e).pipe(K(J(16)),K(Ha(rh,{message:`Declared Gill IDs must be unique`})))),backend:ba(G({bindings:Um,sync:Ca(G({method:Mm}))}))}).pipe(K(Ha(e=>e.calls===void 0||e.capabilities.includes(`apps.call`),{message:`App calls require apps.call`})),K(Ha(e=>e.backend?.bindings.every(e=>e.name!==`BACKGROUND`)??!0,{message:`BACKGROUND is host-minted and cannot be declared by an App`})),K(Ha(e=>dm(e.api,e.backend?.sync),{message:`Background continuation must be a declared write covering all write requirements`})),K(Ha(e=>!(e.receives?.includes(`git.push`)??!1)||e.capabilities.includes(`git.repository`),{message:`Git push reception requires git.repository`})),K(Ha(e=>e.backend?.bindings.every(t=>t.operations.every(n=>Gm(t.name,n)?.requires.every(t=>e.capabilities.includes(t))===!0))??!0,{message:`Backend bindings require declared App capabilities`})),K(Ha(e=>!e.backend?.bindings.some(e=>e.name===`APP_STORAGE`)||(e.storage?.length??0)>0,{message:`App storage bindings require declared keys`})),K(Ha(e=>Object.values(e.api?.methods??{}).every(t=>t.requires.every(t=>e.capabilities.includes(t))),{message:`App API requires capabilities outside the App declaration`})));uh(lr);var dh=uh(Bt);function fh(e){return/^app_[a-z0-9]{1,63}$/u.test(e)}function ph(e){return/^rel_[a-z0-9]{1,63}$/u.test(e)}function mh(e){return/^ps_[a-z0-9]{1,63}$/u.test(e)}function hh(e){return/^artifact:[a-z0-9](?:[a-z0-9._-]{0,126}[a-z0-9])?$/u.test(e)}function gh(e){return/^idem_[a-z0-9](?:[a-z0-9_-]{0,126}[a-z0-9])?$/u.test(e)}function _h(e){return/^git:[0-9a-f]{40}$/u.test(e)}function vh(e){return/^sha256:[0-9a-f]{64}$/u.test(e)}function yh(e){return/^\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(e)}var bh=Eo({family:`app-release`,version:1,kinds:{transition:{prefix:`app_transition`},surface:{prefix:`ps`},erasure:{prefix:`app_erasure`}}}),xh=bh.transition;bh.surface,bh.erasure;var Sh=Y.pipe(Fo(fh)),Ch=Y.pipe(Fo(ph)),wh=Y.pipe(Fo(mh)),Th=Y.pipe(Fo(hh)),Eh=Y.pipe(Fo(gh)),Dh=Y.pipe(Fo(_h)),Oh=Y.pipe(Fo(vh)),kh=Y.pipe(Fo(yh)),Ah=G({byteLength:Da,copy:zo(Function)}).pipe(Fo(e=>e.byteLength>=0)),jh=G({appId:Sh}),Mh=G({sourceRevision:Dh,sourceTreeDigest:Oh,buildRecipeDigest:Oh}),Nh=G({artifactRef:Th,artifactDigest:Oh,provenance:Mh}),Ph=G({releaseId:Ch,appId:Sh,artifact:Nh}),Fh=G({publicSurfaceId:wh,appId:Sh,stableRoute:kh}),Ih=Y.pipe(K(Ta(1)),K(J(256))),Lh=G({...Fh.fields,publisher:G({kind:Ra([`customer`,`platform`]),teamId:Ih,userId:Ih,requestKey:Ih})}),Rh=Ra([`text/html; charset=utf-8`,`application/vnd.fungi.app-backend+json`,`application/vnd.fungi.app-assets+json`,`application/vnd.fungi.app+json`]),zh=G({artifactRef:Th,digest:Oh,mediaType:Ra([`text/html; charset=utf-8`,`application/vnd.fungi.app-backend+json`,`application/vnd.fungi.app-assets+json`]),version:Y.pipe(K(Ta(1))),byteLength:Da.pipe(K(La()),K(Go(0)),K(Ha(Number.isSafeInteger)))}),Bh=G({runtime:G({kind:Ra([`durable-facet`,`region`]),stateSchema:Da.pipe(K(La()),K(Go(0)))}),compatibilityDate:Y.pipe(K(Ba(/^\d{4}-\d{2}-\d{2}$/))),exportName:Y.pipe(K(Ta(1)))}),Vh=G({format:X(`fungi-app-v1`),ui:vo(zh),backend:vo(G({artifact:zh,profile:Bh})),declaration:dh.pipe(Ho(qi(cm)))}),Hh=G({kind:X(`verified`),digest:Oh,mediaType:Rh,bytes:Ah,byteLength:Da}),Uh=q([Hh,G({kind:X(`unavailable`)}),G({kind:X(`missing`)}),G({kind:X(`digest-mismatch`),actualDigest:Oh})]),Wh=q([G({kind:X(`found`),app:jh}),G({kind:X(`absent`)})]),Gh=q([G({kind:X(`created`),app:jh}),G({kind:X(`existing`),app:jh})]),Kh=q([G({kind:X(`found`),release:Ph}),G({kind:X(`absent`)})]),qh=q([G({kind:X(`created`),release:Ph}),G({kind:X(`existing`),release:Ph})]),Jh=q([G({kind:X(`found`),surface:Fh}),G({kind:X(`absent`)})]),Yh=q([G({kind:X(`created`),surface:Fh}),G({kind:X(`existing`),surface:Fh}),G({kind:X(`conflict`)})]),Xh=q([G({kind:X(`verified`),digest:Oh,mediaType:X(`application/vnd.fungi.app+json`),description:Vh}),G({kind:X(`unverified`)})]),Zh=q([G({kind:X(`active`)}),G({kind:X(`revoked`)})]),Qh=q([G({kind:X(`promotion`),publicSurfaceId:wh,releaseId:Ch,idempotencyKey:Eh}),G({kind:X(`rollback`),publicSurfaceId:wh,releaseId:Ch,idempotencyKey:Eh}),G({kind:X(`revocation`),releaseId:Ch,idempotencyKey:Eh})]),$h=wa(e=>xh.schema.safeParse(e).success),eg=G({transition:Qh,transitionId:$h}),tg=q([G({kind:X(`none`)}),G({kind:X(`selected`),releaseId:Ch})]),ng=q([G({kind:X(`found`),release:Ph,verification:Xh,revocation:Zh}),G({kind:X(`absent`)})]);q([G({kind:X(`found`),surface:Fh,selection:tg}),G({kind:X(`absent`)})]);var rg=q([G({kind:X(`absent`)}),G({kind:X(`found`),receipt:eg}),G({kind:X(`conflict`)})]),ig=q([G({kind:X(`created`),receipt:eg}),G({kind:X(`existing`),receipt:eg}),G({kind:X(`conflict`)}),G({kind:X(`identity-collision`)}),G({kind:X(`lifecycle-conflict`)})]),ag=G({kind:X(`recorded`)}),og=G({kind:X(`unavailable`)});function sg(e){return q([G({kind:X(`success`),value:e}),G({kind:X(`failure`),failure:og})])}var cg=sg(Wh),lg=sg(Gh),ug=sg(Kh),dg=sg(qh),fg=sg(Jh),pg=sg(Yh),mg=sg(ng),hg=sg(ag),gg=sg(rg),_g=sg(ig);da(Sh,{onExcessProperty:`error`}),da(Ch,{onExcessProperty:`error`}),da(wh,{onExcessProperty:`error`}),da(Th,{onExcessProperty:`error`}),da(Eh,{onExcessProperty:`error`}),da(Dh,{onExcessProperty:`error`}),da(Oh,{onExcessProperty:`error`}),da(kh,{onExcessProperty:`error`}),da($h,{onExcessProperty:`error`}),Wa(Uh,{onExcessProperty:`error`}),da(jh,{onExcessProperty:`error`}),da(Ph,{onExcessProperty:`error`}),da(Fh,{onExcessProperty:`error`}),da(Lh,{onExcessProperty:`error`}),da(cg,{onExcessProperty:`error`}),da(lg,{onExcessProperty:`error`}),da(ug,{onExcessProperty:`error`}),da(dg,{onExcessProperty:`error`}),da(fg,{onExcessProperty:`error`}),da(pg,{onExcessProperty:`error`}),da(Qh,{onExcessProperty:`error`}),da(mg,{onExcessProperty:`error`}),da(hg,{onExcessProperty:`error`}),da(gg,{onExcessProperty:`error`}),da(_g,{onExcessProperty:`error`});var vg=Y.pipe(K(Ta(1)),K(J(256))),yg=Y.pipe(K(Ba(/\S/u)),K(J(1e3)));G({dispositionId:vg,requestId:vg,operatorId:vg,reason:yg,action:q([G({kind:X(`retain-detached`)}),G({kind:X(`revoke-with-notice`)})])});var bg=G({dispositionId:vg,appId:Sh,displayName:Y.pipe(K(Ta(1)),K(J(64))),releaseIds:uo(Ch).pipe(K(Ta(1)),K(J(1e4))),reason:yg}),xg=G({disposition_id:vg,app_id:Sh,release_ids_json:Y,artifact_roots_json:Y,created_at:Da,state:Ra([`pending`,`retaining`,`retained`,`revoking`,`revoked`]),request_id:vo(vg),reason:vo(yg),completed_at:vo(Da)});G({...xg.fields,releaseIds:uo(Ch).pipe(K(J(1e4)))}),ko(uo(Ch).pipe(K(J(1e4)))),ko(uo(Th).pipe(K(J(1e4)))),[`CREATE TABLE app_release_artifact_dispositions(disposition_id TEXT PRIMARY KEY, app_id TEXT NOT NULL UNIQUE REFERENCES app_release_apps(app_id),
|
|
10
|
-
release_ids_json TEXT NOT NULL CHECK(json_valid(release_ids_json)), artifact_roots_json TEXT NOT NULL CHECK(json_valid(artifact_roots_json)),
|
|
11
|
-
created_at INTEGER NOT NULL,state TEXT NOT NULL CHECK(state IN ('pending','retaining','retained','revoking','revoked')),
|
|
12
|
-
request_id TEXT,reason TEXT,completed_at INTEGER,
|
|
13
|
-
CHECK((state='pending' AND request_id IS NULL AND reason IS NULL) OR (state<>'pending' AND request_id IS NOT NULL AND length(request_id) BETWEEN 1 AND 256 AND reason IS NOT NULL AND length(trim(reason)) BETWEEN 1 AND 1000)),
|
|
14
|
-
CHECK((state IN ('retained','revoked'))=(completed_at IS NOT NULL))) STRICT;`,`CREATE TABLE app_release_artifact_notice_recipients(recipient_id INTEGER PRIMARY KEY,disposition_id TEXT NOT NULL REFERENCES app_release_artifact_dispositions(disposition_id),
|
|
15
|
-
buyer_team_id TEXT CHECK(buyer_team_id IS NULL OR length(buyer_team_id) BETWEEN 1 AND 256),receipt TEXT CHECK(receipt IS NULL OR length(receipt) BETWEEN 1 AND 256),
|
|
16
|
-
erased_by TEXT,erased_at INTEGER,
|
|
17
|
-
CHECK((erased_by IS NULL)=(erased_at IS NULL)),
|
|
18
|
-
CHECK(erased_by IS NULL OR length(erased_by) BETWEEN 1 AND 256),
|
|
19
|
-
CHECK(receipt IS NULL OR erased_at IS NULL),
|
|
20
|
-
CHECK(buyer_team_id IS NOT NULL OR erased_at IS NOT NULL),
|
|
21
|
-
UNIQUE(disposition_id,buyer_team_id)) STRICT;`,`CREATE INDEX app_release_artifact_dispositions_pending ON app_release_artifact_dispositions(state,disposition_id);`,`CREATE TABLE app_release_artifact_disposition_steps(step_id INTEGER PRIMARY KEY,disposition_id TEXT NOT NULL REFERENCES app_release_artifact_dispositions(disposition_id),
|
|
22
|
-
phase TEXT NOT NULL CHECK(phase IN ('prepared','completed')),operator_id TEXT NOT NULL,recorded_at INTEGER NOT NULL) STRICT;`,`CREATE INDEX app_release_artifact_disposition_steps_by_action ON app_release_artifact_disposition_steps(disposition_id,phase);`].map(e=>e.replaceAll(`
|
|
23
|
-
`,` `)).join(`
|
|
24
|
-
`);var Sg=Da.pipe(K(La()),K(Yo(0))),Cg=G({items:uo(Zp),next:vo(Y),cursor:Sg});Si({visited:Ki(!0)});var wg=oo(Cg),Tg=oo(ko(G({kind:X(`rows`),from:Sg,to:Sg,items:uo(Qp),more:Ko})));function Eg(e){let t=new Map,n=0,r=!1,i,a=0,o=n=>{r||e.onChange({items:[...t.values()],status:n})},s=e=>{for(let n of e){let e=em(n);`deleted`in n?t.delete(e):t.set(e,n)}},c=()=>{i?.close();let t=++a,u=e.openEvents(`${e.baseUrl}/inbox/events?after=${String(n)}`);i=u;let d=!1;u.addEventListener(`error`,()=>{r||t!==a||(d=!0,dc(`inbox.observe`,Error(`Member inbox stream disconnected`)),o(`error`))}),u.addEventListener(`open`,()=>{r||t!==a||!d||l()}),u.addEventListener(`rows`,e=>{if(r||t!==a)return;let i;try{i=Tg(e.data)}catch(e){dc(`inbox.decode-event`,e),o(`loading`),c();return}if(i.from!==n){o(`loading`),c();return}s(i.items),n=i.to,o(`live`)}),u.addEventListener(`reset`,()=>{r||t!==a||l()})},l=async()=>{let l=++a;i?.close(),i=void 0,o(`loading`);try{t.clear();let i=null,u=!0;for(let t=0;t<5;t+=1){let t=i===null?``:`?after=${encodeURIComponent(i)}`,o=await e.fetch(`${e.baseUrl}/inbox${t}`,{cache:`no-store`});if(!o.ok)throw Error(`Inbox unavailable`);let c=wg(await o.json());if(r||l!==a)return;if(u&&(n=c.cursor),u=!1,s(c.items),i=c.next,i===null)break}o(`live`),c()}catch(e){if(r||l!==a)return;dc(`inbox.refresh`,e),o(`error`)}};return l(),Object.freeze({refresh:()=>r?Promise.resolve():l(),visit:async(t,n)=>{let r=await e.fetch(`${e.baseUrl}/inbox/visits`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t,sessionId:n})});if(!r.ok&&r.status!==404)throw Error(`Visit was not recorded`)},close:()=>{r=!0,a+=1,i?.close()}})}var Dg=oo(G({items:uo(q([G({...bg.fields,reason:ba(bg.fields.reason),createdAt:Sg}),G({...nm.fields,createdAt:Sg})])).pipe(K(J(100))),next:vo(Y.pipe(K(J(1024))))}),{onExcessProperty:`error`});async function Og(e,t=null){let n=new URL(`${e.baseUrl}/inbox/notices`);t!==null&&n.searchParams.set(`after`,t);let r=await e.fetch(n);if(!r.ok)throw Error(`Team notices unavailable`);return Dg(await r.json())}var kg=Ui({status:Ai()}),Ag=3,jg=/network ?(?:changed|error)|failed to fetch|load failed|network connection was lost/iu;function Mg(e){let t=[];for(let n=e;n!==void 0&&t.length<5;n=n instanceof Error?n.cause:void 0)t.push(n);return t}function Ng(e){return Mg(e).some(e=>{if(e instanceof TypeError)return!0;if(e instanceof Z)return e.code===`HOST_FAILURE`&&e.retryable;let t=kg.safeParse(e);return t.success?t.data.status>=500:e instanceof Error&&jg.test(e.message)})}function Pg(e,t){return e<Ag&&Ng(t)}function Fg(e){return 250*2**e}function Ig(e,t){return t.status===`live`?t:{...t,data:t.data??e.data}}function Lg(e,t,n={}){return Uc({queryKey:e,...n,retry:Pg,retryDelay:Fg,staleTime:1/0,refetchOnMount:`always`,queryFn:Gt({initialValue:{status:`loading`},refetchMode:`append`,reducer:Ig,streamFn:({signal:e})=>Ka($o(n=>Ri(function*(){let r={status:`loading`},i=()=>{Lo(n)};if(yield*$i(Pi(()=>{e.addEventListener(`abort`,i,{once:!0})}),()=>Pi(()=>{e.removeEventListener(`abort`,i)})),e.aborted){i();return}yield*$i(Ci({try:()=>Promise.resolve(t(e=>{r=Ig(r,e),Za(n,r)},e)),catch:zg}),e=>Pi(e))}).pipe(Ti(e=>go(n,e))),{bufferSize:1,strategy:`sliding`}))})})}async function Rg(e,t,n){if(!e)throw new Z(`No App connection`,{code:`DISCONNECTED`,retryable:!0});let r=await uc(e.capabilities),i=()=>{r.close().catch(e=>{dc(`inbox.query-close`,e)})};if(n.aborted)return i(),()=>void 0;let a=Eg({baseUrl:r.baseUrl,fetch:r.fetch,openEvents:e=>{let t=new Up(e,{fetch:(e,t)=>r.fetch(e,t)});return{addEventListener:(e,n)=>{t.addEventListener(e,t=>{e===`open`||e===`error`?n(new MessageEvent(e)):t instanceof MessageEvent&&n(new MessageEvent(e,{data:ra().parse(t.data)}))})},close:()=>{t.close()}}},onChange:e=>{t(e.status===`live`?{status:`live`,data:e.items}:{status:e.status})}});return()=>{a.close(),i()}}function zg(e){return e instanceof Z?e:new Z(`App operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!1})}var Bg=new WeakMap,Vg={of(e,...t){return[e?.identity.surfaceId??null,e?.context.get().computerId??null,...t]}};function Hg(e){let t={};return e&&Bg.set(t,e),t}function Ug(){let e=new en({defaultOptions:{queries:{retry:!1,staleTime:3e4,refetchOnWindowFocus:!1},mutations:{retry:!1}}}),t=new Map;return e.getQueryCache().subscribe(n=>{let r=n.query;if(n.type===`removed`){t.get(r.queryHash)?.release(),t.delete(r.queryHash);return}let i=r.meta&&Bg.get(r.meta),a=t.get(r.queryHash);if(a?.app===i||(a?.release(),t.delete(r.queryHash),!i))return;let o=()=>{queueMicrotask(()=>{e.getQueryCache().get(r.queryHash)===r&&t.get(r.queryHash)?.app===i&&e.resetQueries({predicate:e=>e===r})})},s=i.capabilities.subscribe(o);t.set(r.queryHash,{app:i,release:s}),a&&o()}),e}function Wg(e,t,n,r){let i=e?.context.get().computerId;return vr({queryKey:n,meta:Hg(e),enabled:e!==null,retry:Pg,retryDelay:Fg,queryFn:async({signal:n})=>{try{if(!e)throw new Z(`No App connection`,{code:`DISCONNECTED`,retryable:!0});if(e.context.get().computerId!==i)throw new Z(`The selected Computer changed`,{code:`SELECTION_CHANGED`,retryable:!1});return await r(e.capabilities.require(t),n)}catch(e){throw zg(e)}}})}function Gg(e){Cp(e?.context);let t=He(),n=e?.context.get().computerId,r=(0,Q.useMemo)(()=>Vg.of(e,`member-inbox`),[e,n]),i=Lg(r,(0,Q.useCallback)((t,r)=>{if(e?.context.get().computerId!==n)throw new Z(`The selected Computer changed`,{code:`SELECTION_CHANGED`,retryable:!1});return Rg(e,t,r)},[e,n]),{enabled:e!==null,meta:Hg(e)}),a=(0,Q.useCallback)(()=>{t.invalidateQueries({queryKey:r,exact:!0})},[t,r]),o=(0,Q.useCallback)(async(t,n)=>{if(!e)throw new Z(`No App connection`,{code:`DISCONNECTED`,retryable:!0});let r=await uc(e.capabilities);try{let e=await r.fetch(`${r.baseUrl}/inbox/visits`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t,sessionId:n})});if(!e.ok&&e.status!==404)throw new Z(`Visit was not recorded`,{code:`HOST_FAILURE`,retryable:!0})}finally{await r.close()}},[e]);return{items:i.data?.data??[],status:i.isError?`error`:i.data?.status??`loading`,error:i.error,refresh:a,visit:o}}var Kg=q([G({kind:X(`compose`),text:Y.pipe(K(Ta(1)),K(J(2e3)))}),G({kind:X(`navigate`),params:uo(G({key:Y.pipe(K(Ta(1)),K(J(64))),value:Y.pipe(K(J(1024)))})).pipe(K(J(16)))})]);q([G({role:Y.pipe(K(Ta(1)),K(J(80))),intent:Kg}),G({appId:Y.pipe(K(Ta(1)),K(J(128))),intent:Kg})],{mode:`oneOf`});var qg=Si({displayName:ra().min(1).max(80).nullable()}).nullable(),Jg=Ws(`apps.open`,1,Di(()=>as({open:hs,role:is(cc(qg))}))),Yg=(e,t)=>e.require(Jg).open(t);Ws(`apps.call`,1,Di(()=>as({call:is(cc(ci().transform(e=>Wo(e))))})));var Xg=8e3,Zg=(0,Q.forwardRef)(function({className:e,detail:t,framed:n=!0,icon:r,message:i,onRetry:a,size:o=`md`,slowAfterMs:s=Xg,variant:c=`line`,...l},u){let[d,f]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{if(f(!1),!Number.isFinite(s))return;let e=globalThis.setTimeout(()=>{f(!0)},s);return()=>{globalThis.clearTimeout(e)}},[s,i]),(0,$.jsxs)(`div`,{...l,className:N(`caps-loading-state`,e),"data-framed":n?void 0:`false`,"data-icon":r?``:void 0,"data-size":o,"data-slow":d||void 0,ref:u,role:`status`,children:[r?(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`caps-loading-state-icon`,children:r}):null,(0,$.jsx)(Oe,{decorative:!0,size:o,variant:c}),(0,$.jsxs)(`span`,{className:`caps-loading-state-copy`,children:[(0,$.jsx)(`span`,{children:i}),t?(0,$.jsx)(`span`,{className:`caps-loading-state-detail`,children:t}):null,d?(0,$.jsx)(`span`,{className:`caps-loading-state-detail`,children:`Still working…`}):null]}),d&&a?(0,$.jsx)(W,{className:`caps-loading-state-retry`,size:`sm`,variant:`outline`,onClick:a,children:`Retry`}):null]})}),Qg=Q.createContext(void 0);function $g(e){let t=Q.useContext(Qg);if(t===void 0&&!e)throw Error(U(33));return t}var e_=Q.createContext(void 0);function t_(e){let t=Q.useContext(e_);if(t===void 0&&!e)throw Error(U(36));return t}var n_=Q.createContext(void 0);function r_(e=!0){let t=Q.useContext(n_);if(t===void 0&&!e)throw Error(U(25));return t}var i_=Q.createContext(null);function a_(e=`root`){let t=Q.useContext(i_),n=Q.useContext(e_);return t===null||n===void 0?null:(e===`submenu-trigger`?n.virtualFocus||n.parentVirtualFocus:n.virtualFocus)?t:null}var o_={visible:!0,ref:null};function s_(){return o_}function c_(e,t,n=`root`){let r=a_(n),i=((n===`submenu-trigger`?r?.useSubmenuTrigger:r?.useItem)??s_)({label:e.label,children:e.children,render:e.render}),a=c(t,i.ref);return{visible:i.visible,ref:a,props:i.props}}var l_=Q.createContext(void 0);function u_(){let e=Q.useContext(l_);if(e===void 0)throw Error(U(30));return e}function d_(e){e.preventDefault()}function f_(e){let{closeOnClick:t,highlighted:n,id:r,nodeId:i,store:a,typingRef:o,itemRef:s,itemMetadata:c}=e,l=t_(),u=r_(!0),d=c.type===`submenu-trigger`,f=d?l.parentVirtualFocus:l.virtualFocus,p=(d&&l.parent.type===`menu`?l.parent.store:l.store).useState(`webkitAriaSelected`,n),{events:m}=a.useState(`floatingTreeRoot`),h=a.useState(`open`),g=u!==void 0,_=!f&&h&&n?0:-1;return Q.useMemo(()=>({id:r,role:`menuitem`,tabIndex:_,"aria-selected":p,onMouseDown:f?d_:void 0,onKeyDown(e){e.key===` `&&o?.current&&e.preventDefault()},onMouseMove(e){i&&m.emit(`itemhover`,{nodeId:i,target:e.currentTarget})},onClick(e){t&&m.emit(`close`,{domEvent:e.nativeEvent,reason:Gn})},onMouseUp(e){if(u){let t=u.initialCursorPointRef.current;if(u.initialCursorPointRef.current=null,g&&t&&Math.abs(e.clientX-t.x)<=1&&Math.abs(e.clientY-t.y)<=1||g&&!Dn&&e.button===2)return}s.current&&a.context.allowMouseUpTriggerRef.current&&(!g||e.button===2)&&c.type===`regular-item`&&Cn(s.current,e,{detail:1,pointerType:`mouse`})}}),[t,_,r,m,i,a.context.allowMouseUpTriggerRef,o,s,u,g,c.type,p,f])}var p_={type:`regular-item`};function m_(e){let{closeOnClick:t,disabled:n,highlighted:r,id:i,store:a,typingRef:o=a.context.typingRef,nativeButton:s,itemMetadata:l,nodeId:d}=e,f=Q.useRef(null),{getButtonProps:p,buttonRef:m}=u({disabled:n,focusableWhenDisabled:!0,native:s,composite:!0}),h=f_({closeOnClick:t,highlighted:r,id:i,nodeId:d,store:a,typingRef:o,itemRef:f,itemMetadata:l}),g=Q.useCallback(e=>qe(h,{onMouseEnter(e){l.type===`submenu-trigger`&&l.setActive(e.nativeEvent)}},e,p),[h,p,l]),_=c(f,m);return Q.useMemo(()=>({getItemProps:g,itemRef:_}),[g,_])}var h_=Q.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function g_(){return Q.useContext(h_)}function __(e={}){let{guess:t,label:n,metadata:r,textRef:i,index:a}=e,{register:o,unregister:s,subscribeMapChange:c,nextIndexRef:l}=g_(),u=Q.useRef(-1),[d,f]=Q.useState(a==null&&t?()=>{if(u.current===-1){let e=l.current;l.current+=1,u.current=e}return u.current}:-1),p=a??d,m=Q.useRef(null),h=Q.useCallback(e=>{let t=m.current;t&&s(t),m.current=e,e&&o(e,{metadata:r??null,index:a??null,label:n,textRef:i})},[a,o,s,r,n,i]);return Ae(()=>{if(a==null)return c(e=>{let t=m.current?e.get(m.current)?.index:null;t!=null&&f(t)})},[a,c]),{ref:h,index:p}}var v_=`data-checked`,y_=`data-unchecked`,b_={checked(e){return e?{[v_]:``}:{[y_]:``}},...Lt},x_=Q.forwardRef(function(e,t){let{render:n,className:r,id:i,label:a,nativeButton:o=!1,disabled:s=!1,closeOnClick:c=!1,checked:l=!1,onCheckedChange:u,style:d,...f}=e,{store:p}=t_(),m=__({guess:!0,label:a}),h=D(i),g=p.useState(`disabled`),_=p.useState(`isActive`,m.index),v=p.useState(`floatingNodeId`),y=p.useState(`itemProps`),b=s||g,{getItemProps:x,itemRef:S}=m_({closeOnClick:c,disabled:b,highlighted:_,id:h,store:p,nativeButton:o,nodeId:v,itemMetadata:p_}),C=Q.useMemo(()=>({disabled:b,highlighted:_,checked:l}),[b,_,l]);function w(e){let t=Ar(Gn,e.nativeEvent,void 0,{preventUnmountOnClose:Tn});u?.(!l,t)}let T=Or(`div`,e,{state:C,stateAttributesMapping:b_,props:[y,{role:`menuitemcheckbox`,"aria-checked":l,onClick:w},f,x],ref:[S,t,m.ref]});return(0,$.jsx)(l_.Provider,{value:C,children:T})}),S_=Q.forwardRef(function(e,t){let{checked:n,defaultChecked:r,onCheckedChange:i,...o}=e,[s,c]=a({controlled:n,default:r??!1,name:`MenuCheckboxItem`,state:`checked`}),l=c_(e,t);function u(e,t){i?.(e,t),t.isCanceled||c(e)}return l.visible?(0,$.jsx)(x_,{...o,checked:s,onCheckedChange:u,ref:l.ref}):null}),C_=Q.forwardRef(function(e,t){let{render:n,className:r,style:i,keepMounted:a=!1,...o}=e,s=u_(),c=Q.useRef(null),{transitionStatus:l,mounted:u,setMounted:d}=zt(s.checked);Ot({batch:!0,enabled:!s.checked,open:s.checked,ref:c,onComplete(){s.checked||d(!1)}});let f={checked:s.checked,disabled:s.disabled,highlighted:s.highlighted,transitionStatus:l};return Or(`span`,e,{state:f,ref:[t,c],stateAttributesMapping:b_,props:{"aria-hidden":!0,...o},enabled:a||u})}),w_=Q.createContext(void 0);function T_(){let e=Q.useContext(w_);if(e===void 0)throw Error(U(31));return e}var E_=Q.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,s=D(a),c=T_();return Ae(()=>(c(s),()=>{c(e=>e===s?void 0:e)}),[c,s]),Or(`div`,e,{ref:t,props:{id:s,"aria-hidden":!0,...o}})}),D_=Q.forwardRef(function(e,t){let{render:n,className:r,id:i,label:a,nativeButton:o=!1,disabled:s=!1,closeOnClick:c=!0,style:l,...u}=e,{store:d}=t_(),f=__({guess:!0,label:a}),p=D(i),m=d.useState(`disabled`),h=d.useState(`isActive`,f.index),g=d.useState(`floatingNodeId`),_=d.useState(`itemProps`),v=s||m,{getItemProps:y,itemRef:b}=m_({closeOnClick:c,disabled:v,highlighted:h,id:p,store:d,nativeButton:o,nodeId:g,itemMetadata:p_});return Or(`div`,e,{state:{disabled:v,highlighted:h},props:[_,u,y],ref:[b,t,f.ref]})}),O_=Q.forwardRef(function(e,t){let n=c_(e,t);return n.visible?(0,$.jsx)(D_,{...e,ref:n.ref}):null});function k_(e,t){return t!=null&&!Jt(t)?0:typeof e==`function`?e():e}function A_(e,t,n){let r=k_(e,n);return typeof r==`number`?r:r?.[t]}function j_(e){return typeof e==`function`?e():e}function M_(e,t){return t||e===`click`||e===`mousedown`}function N_(e){return e?.includes(`mouse`)&&e!==`mousedown`}var P_=Math.min,F_=Math.max,I_=Math.round,L_=Math.floor,R_=e=>({x:e,y:e}),z_={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function B_(e,t,n){return F_(e,P_(t,n))}function V_(e,t){return typeof e==`function`?e(t):e}function H_(e){return e.split(`-`)[0]}function U_(e){return e.split(`-`)[1]}function W_(e){return e===`x`?`y`:`x`}function G_(e){return e===`y`?`height`:`width`}function K_(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function q_(e){return W_(K_(e))}function J_(e,t,n){n===void 0&&(n=!1);let r=U_(e),i=q_(e),a=G_(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=rv(o)),[o,rv(o)]}function Y_(e){let t=rv(e);return[X_(e),t,X_(t)]}function X_(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var Z_=[`left`,`right`],Q_=[`right`,`left`],$_=[`top`,`bottom`],ev=[`bottom`,`top`];function tv(e,t,n){switch(e){case`top`:case`bottom`:return n?t?Q_:Z_:t?Z_:Q_;case`left`:case`right`:return t?$_:ev;default:return[]}}function nv(e,t,n,r){let i=U_(e),a=tv(H_(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(X_)))),a}function rv(e){let t=H_(e);return z_[t]+e.slice(t.length)}function iv(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function av(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:iv(e)}function ov(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function sv(e,t){let n=null,r=null,i=!1;return{contextElement:e||void 0,getBoundingClientRect(){let a=e?.getBoundingClientRect()||{width:0,height:0,x:0,y:0},o=t.axis===`x`||t.axis===`both`,s=t.axis===`y`||t.axis===`both`,c=[`mouseenter`,`mousemove`].includes(t.dataRef.current.openEvent?.type||``)&&t.pointerType!==`touch`,l=t.axis===`y`?a.width:0,u=t.axis===`x`?a.height:0,d=a.x,f=a.y;return n==null&&t.x&&o&&(n=a.x-t.x),r==null&&t.y&&s&&(r=a.y-t.y),d-=n||0,f-=r||0,(!i||c)&&(d=o&&t.x!=null?t.x:d,f=s&&t.y!=null?t.y:f),i=!0,{width:l,height:u,x:d,y:f,top:f,right:d+l,bottom:f+u,left:d}}}}function cv(e){return e!=null&&e.clientX!=null}function lv(e,t={}){let{enabled:n=!0,axis:r=`both`}=t,i=e.useState(`open`),a=e.useState(`floatingElement`),o=e.useState(`domReferenceElement`),s=e.context.dataRef,c=Q.useRef(!1),l=Q.useRef(null),[u,d]=Q.useState(),[f,p]=Q.useState([]),m=A(t=>{e.set(`positionReference`,t)}),h=A((t,n,i)=>{c.current||s.current.openEvent&&!cv(s.current.openEvent)||e.set(`positionReference`,sv(i??o,{x:t,y:n,axis:r,dataRef:s,pointerType:u}))}),g=A(e=>{i?l.current||(h(e.clientX,e.clientY,e.currentTarget),p([])):h(e.clientX,e.clientY,e.currentTarget)}),_=Jt(u)?a:i;Q.useEffect(()=>{if(!n){m(o);return}if(!_)return;function e(){l.current?.(),l.current=null}let t=st(a);function r(t){let n=br(t);jn(a,n)?e():h(t.clientX,t.clientY)}return!s.current.openEvent||cv(s.current.openEvent)?l.current=dt(t,`mousemove`,r):m(o),e},[_,n,a,s,o,e,h,m,f]),Q.useEffect(()=>()=>{e.set(`positionReference`,null)},[e]),Q.useEffect(()=>{n&&!a&&(c.current=!1)},[n,a]),Q.useEffect(()=>{!n&&i&&(c.current=!0)},[n,i]);let v=Q.useMemo(()=>{function e(e){d(e.pointerType)}return{onPointerDown:e,onPointerEnter:e,onMouseMove:g,onMouseEnter:g}},[g]);return Q.useMemo(()=>n?{reference:v,trigger:v}:{},[n,v])}var uv=Dn&&Ee;function dv(e,t={}){let{enabled:n=!0,delay:r}=t,{events:a,dataRef:o}=e.context,s=Q.useRef(!1),c=Q.useRef(null),l=Q.useRef(!0),u=ln();Q.useEffect(()=>{let t=e.select(`domReferenceElement`);if(!n)return;let r=st(t);function i(){let t=e.select(`domReferenceElement`);!e.select(`open`)&&nr(t)&&t===fr(ye(t))&&(s.current=!0,c.current=t)}function a(){l.current=!0}function o(){l.current=!1}return gt(dt(r,`blur`,i),uv&&dt(r,`keydown`,a,!0),uv&&dt(r,`pointerdown`,o,!0))},[e,n]),Q.useEffect(()=>{if(!n)return;function t(t){if(t.reason===`trigger-press`||t.reason===`escape-key`){let t=e.select(`domReferenceElement`);H(t)&&(c.current=t,s.current=!0)}}return a.on(`openchange`,t),()=>{a.off(`openchange`,t)}},[a,n,e]);let d=Q.useMemo(()=>{function t(){s.current=!1,c.current=null}return{onMouseLeave(){t()},onFocus(n){let a=n.currentTarget;if(s.current){if(c.current===a)return;t()}let o=br(n.nativeEvent);if(H(o)){if(uv&&!n.relatedTarget){if(!l.current&&!gr(o))return}else if(!Vn(o))return}let d=i(n.relatedTarget,e.context.triggerElements),{nativeEvent:f,currentTarget:p}=n;if(e.select(`open`)&&d||!r){e.setOpen(!0,Ar(Zn,f,p));return}u.start(r,()=>{s.current||e.setOpen(!0,Ar(Zn,f,p))})},onBlur(n){t();let r=n.relatedTarget,a=n.nativeEvent,s=H(r)&&r.hasAttribute(he(`focus-guard`))&&r.getAttribute(`data-type`)===`outside`;u.start(0,()=>{let t=e.select(`domReferenceElement`),n=fr(ye(t));!r&&n===t||jn(o.current.floatingContext?.refs.floating.current,n)||jn(t,n)||s||i(r??n,e.context.triggerElements)||e.setOpen(!1,Ar(Zn,a))})}}},[o,r,e,u]);return Q.useMemo(()=>n?{reference:d,trigger:d}:{},[n,d])}var fv=class e{pointerType=void 0;interactedInside=!1;handler=void 0;blockMouseMove=!0;performedPointerEventsMutation=!1;pointerEventsScopeElement=null;pointerEventsReferenceElement=null;pointerEventsFloatingElement=null;restTimeoutPending=!1;openChangeTimeout=new mn;restTimeout=new mn;handleCloseOptions=void 0;static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose},pv=new WeakMap;function mv(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&pv.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),pv.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function hv(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=pv.get(n);a&&a!==e&&mv(a),mv(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,pv.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function gv(e){let t=e.context.dataRef.current,n=xn(()=>t.hoverInteractionState??fv.create()).current;return t.hoverInteractionState||=n,y(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function _v(e,t={}){let{enabled:n=!0,closeDelay:r=0,nodeId:a}=t,o=e.useState(`open`),s=e.useState(`floatingElement`),c=e.useState(`domReferenceElement`),{dataRef:l}=e.context,u=Te(),d=S(),f=gv(e),p=ln(),m=A(()=>M_(l.current.openEvent?.type,f.interactedInside)),h=A(()=>N_(l.current.openEvent?.type)),g=A(()=>{mv(f)});Ae(()=>{o||(f.pointerType=void 0,f.restTimeoutPending=!1,f.interactedInside=!1,g())},[o,f,g]),Q.useEffect(()=>g,[g]),Ae(()=>{if(n&&o&&f.handleCloseOptions?.blockPointerEvents&&h()&&H(c)&&s){let e=c,t=s,n=ye(s),r=u?.nodesRef.current.find(e=>e.id===d)?.context?.elements.floating;r&&(r.style.pointerEvents=``);let i=f.pointerEventsScopeElement===t?null:f.pointerEventsScopeElement,a=r===t?null:r,o=f.handleCloseOptions?.getScope?.()??i??a??Ut(e,`[data-rootownerid]`)??n.body;return hv(f,{scopeElement:o,referenceElement:e,floatingElement:t}),()=>{g()}}},[n,o,c,s,f,h,u,d,g]),Q.useEffect(()=>{if(!n)return;function t(){return!!(u&&d&&ze(u.nodesRef.current,d).length>0)}function o(t){let n=A_(r,`close`,f.pointerType),i=()=>{e.setOpen(!1,Ar(Pn,t)),u?.events.emit(`floating.closed`,t)};n?f.openChangeTimeout.start(n,i):(f.openChangeTimeout.clear(),i())}function c(e){let t=br(e);if(!Pe(t)){f.interactedInside=!1;return}f.interactedInside=Ut(t,`[aria-haspopup]`)!=null}function _(){f.openChangeTimeout.clear(),p.clear(),u?.events.off(`floating.closed`,y),g()}function v(n){if(t()&&u){u.events.on(`floating.closed`,y);return}if(i(n.relatedTarget,e.context.triggerElements))return;let r=l.current.floatingContext?.nodeId??a,s=n.relatedTarget;if(!(u&&r&&H(s)&&ze(u.nodesRef.current,r,!1).some(e=>jn(e.context?.elements.floating,s)))){if(f.handler){f.handler(n);return}g(),h()&&!m()&&o(n)}}function y(n){!u||!d||t()||p.start(0,()=>{u.events.off(`floating.closed`,y),e.setOpen(!1,Ar(Pn,n)),u.events.emit(`floating.closed`,n)})}let b=s;return gt(b&&dt(b,`mouseenter`,_),b&&dt(b,`mouseleave`,v),b&&dt(b,`pointerdown`,c,!0),()=>{u?.events.off(`floating.closed`,y)})},[n,s,e,l,r,a,h,m,g,f,u,d,p])}var vv=e(On(),1),yv={current:null};function bv(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:a=null,mouseOnly:o=!1,restMs:s=0,move:c=!0,triggerElementRef:l=yv,externalTree:u,isActiveTrigger:d=!0,getHandleCloseContext:f,isClosing:p,shouldOpen:m,guardStaleOpen:h=!1}=t,{dataRef:g,events:_}=e.context,v=Te(u),y=gv(e),b=Q.useRef(!1),x=B(a),S=B(r),C=B(s),w=B(n),T=B(m),E=B(p),D=A(()=>M_(g.current.openEvent?.type,y.interactedInside)),O=A(()=>T.current?.()!==!1),k=A((t,n,r)=>{let i=e.context.triggerElements;if(i.hasElement(n))return!t||!jn(t,n);if(!H(r))return!1;let a=r;return i.hasMatchingElement(e=>jn(e,a))&&(!t||!jn(t,a))}),j=A(()=>{y.handler&&=(ye(e.select(`domReferenceElement`)).removeEventListener(`mousemove`,y.handler),void 0)}),M=A(()=>{mv(y)});return d&&(y.handleCloseOptions=a?.__options),Q.useEffect(()=>j,[j]),Q.useEffect(()=>{if(!n)return;function e(e){e.open?b.current=!1:(b.current=e.reason===Pn,j(),y.openChangeTimeout.clear(),y.restTimeout.clear(),y.blockMouseMove=!0,y.restTimeoutPending=!1)}return _.on(`openchange`,e),()=>{_.off(`openchange`,e)}},[n,_,y,j]),Q.useEffect(()=>{if(!n)return;function t(t,n=!0){let r=A_(S.current,`close`,y.pointerType);r?y.openChangeTimeout.start(r,()=>{e.setOpen(!1,Ar(Pn,t)),v?.events.emit(`floating.closed`,t)}):n&&(y.openChangeTimeout.clear(),e.setOpen(!1,Ar(Pn,t)),v?.events.emit(`floating.closed`,t))}let r=l.current??(d?e.select(`domReferenceElement`):null);if(!H(r))return;function a(t){if(y.openChangeTimeout.clear(),y.blockMouseMove=!1,o&&!Jt(y.pointerType))return;let n=j_(C.current),r=A_(S.current,`open`,y.pointerType),i=br(t),a=t.currentTarget??null,s=e.select(`domReferenceElement`),c=a;if(H(i)&&!e.context.triggerElements.hasElement(i)){for(let t of e.context.triggerElements.elements())if(jn(t,i)){c=t;break}}H(a)&&H(s)&&!e.context.triggerElements.hasElement(a)&&jn(a,s)&&(c=s);let l=c!=null&&k(s,c,i),u=e.select(`open`),d=E.current?.()??e.select(`transitionStatus`)===`ending`,f=!u&&d&&b.current,p=!l&&H(c)&&H(s)&&jn(s,c)&&f,m=n>0&&!r,h=l&&(u||f)||p,g=!u||l;if(h){O()&&e.setOpen(!0,Ar(Pn,t,c));return}m||(r?y.openChangeTimeout.start(r,()=>{g&&O()&&e.setOpen(!0,Ar(Pn,t,c))}):g&&O()&&e.setOpen(!0,Ar(Pn,t,c)))}function s(n){if(D()){M();return}j();let r=e.select(`domReferenceElement`),a=ye(r);y.restTimeout.clear(),y.restTimeoutPending=!1;let o=g.current.floatingContext??f?.();if(!i(n.relatedTarget,e.context.triggerElements)){if(x.current&&o){e.select(`open`)||y.openChangeTimeout.clear();let r=l.current;y.handler=x.current({...o,tree:v,x:n.clientX,y:n.clientY,onClose(){M(),j(),w.current&&!D()&&r===e.select(`domReferenceElement`)&&t(n,!0)}}),a.addEventListener(`mousemove`,y.handler),y.handler(n);return}(y.pointerType!==`touch`||!jn(e.select(`floatingElement`),n.relatedTarget))&&t(n)}}function u(e){jn(r,e.relatedTarget)||(y.openChangeTimeout.clear(),y.restTimeout.clear(),y.restTimeoutPending=!1)}let p=h?dt(r,`mouseout`,u):void 0;return c?gt(dt(r,`mousemove`,a,{once:!0}),dt(r,`mouseenter`,a),dt(r,`mouseleave`,s),p):gt(dt(r,`mouseenter`,a),dt(r,`mouseleave`,s),p)},[j,M,g,S,e,n,x,y,d,k,D,o,c,C,l,v,w,f,E,O,h]),Q.useMemo(()=>{if(!n)return;function t(e){y.pointerType=e.pointerType}return{onPointerDown:t,onPointerEnter:t,onMouseMove(t){let{nativeEvent:n}=t,r=t.currentTarget,i=e.select(`domReferenceElement`),a=e.select(`open`),s=k(i,r,t.target);if(o&&!Jt(y.pointerType))return;if(a&&s&&y.handleCloseOptions?.blockPointerEvents){let t=e.select(`floatingElement`);if(t){let e=y.handleCloseOptions?.getScope?.()??r.ownerDocument.body;hv(y,{scopeElement:e,referenceElement:r,floatingElement:t})}}let c=j_(C.current);if(a&&!s||c===0||!s&&y.restTimeoutPending&&t.movementX**2+t.movementY**2<2)return;y.restTimeout.clear();function l(){if(y.restTimeoutPending=!1,D())return;let t=e.select(`open`);!y.blockMouseMove&&(!t||s)&&O()&&e.setOpen(!0,Ar(Pn,n,r))}y.pointerType===`touch`?vv.flushSync(()=>{l()}):s&&a?l():(y.restTimeoutPending=!0,y.restTimeout.start(c,l))}}},[n,y,D,k,o,e,C,O])}function xv(e){return Ee&&e.movementX===0&&e.movementY===0}function Sv(e,t,n){switch(e){case`vertical`:return t;case`horizontal`:return n;default:return t||n}}function Cv(e,t){return Sv(t,e===`ArrowUp`||e===`ArrowDown`,e===`ArrowLeft`||e===`ArrowRight`)}function wv(e,t,n){return Sv(t,e===`ArrowDown`,n?e===`ArrowLeft`:e===`ArrowRight`)||e===`Enter`||e===` `||e===``}function Tv(e,t,n){return Sv(t,n?e===yn:e===Pt,e===sr)}function Ev(e,t,n,r){return t===`both`||t===`horizontal`&&r?e===`Escape`:Sv(t,n?e===Pt:e===yn,e===qn)}function Dv(e,t){let{listRef:n,activeIndex:r,onNavigate:i=()=>{},enabled:a=!0,selectedIndex:o=null,allowEscape:s=!1,loopFocus:c=!1,nested:l=!1,rtl:u=!1,virtual:d=!1,focusItemOnOpen:f=`auto`,focusItemOnHover:p=!0,openOnArrowKeyDown:m=!0,disabledIndices:h=void 0,orientation:g=`vertical`,triggerOrientation:_=g,parentOrientation:v,id:y,resetOnPointerLeave:b=!0,externalTree:x,nestedReturnFocusRef:C,grid:w}=t,T=w!=null,E=e.useState(`open`),D=e.useState(`floatingElement`),O=e.useState(`domReferenceElement`),k=e.context.dataRef,j=xt(D),M=Qt(O),N=B(j),te=S(),ne=Te(x),P=Q.useRef(f),F=Q.useRef(o??-1),I=Q.useRef(null),L=Q.useRef(!0),R=A(e=>{i(F.current===-1?null:F.current,e)}),ie=Q.useRef(!!D),ae=Q.useRef(E),oe=Q.useRef(!1),se=Q.useRef(!1),ce=Q.useRef(null),le=B(h),ue=B(E),V=B(o),de=B(b),H=We(),fe=We(),pe=A(()=>{H.cancel();function e(e){d||(ce.current=z(e,{sync:oe.current,preventScroll:!0}))}let t=n.current[F.current],r=se.current;t&&e(t),(oe.current?e=>e():e=>H.request(e))(()=>{let i=n.current[F.current]||t;i&&(t||e(i),ve&&(r||!L.current)&&i.scrollIntoView?.({block:`nearest`,inline:`nearest`}))})});Ae(()=>{k.current.orientation=g},[k,g]),Ae(()=>{E||(I.current=null),(!E||f!==`auto`)&&(P.current=f)},[E,f]),Ae(()=>{a&&(E&&D?(F.current=o??-1,P.current&&o!=null&&(se.current=!0,R())):ie.current&&(F.current=-1,R()))},[a,E,D,o,R]),Ae(()=>{if(a){if(!E){oe.current=!1;return}if(D){if(r==null){if(oe.current=!1,V.current!=null)return;if(ie.current&&(F.current=-1,pe()),(!ae.current||!ie.current)&&P.current&&(I.current!=null||P.current===!0&&I.current==null)){let e=0,t=()=>{n.current[0]==null?(e<2&&(e?e=>fe.request(e):queueMicrotask)(t),e+=1):(F.current=I.current==null||wv(I.current,_,u)||l?re(n):nt(n),I.current=null,R())};t()}}else ee(n.current,r)||(F.current=r,pe(),se.current=!1)}}},[a,E,D,r,V,l,n,_,u,R,pe,fe]),Ae(()=>{if(!a||D||!ne||d||!ie.current)return;let e=ne.nodesRef.current,t=e.find(e=>e.id===te)?.context?.elements.floating,n=fr(ye(O??t??null)),r=e.some(e=>e.context&&jn(e.context.elements.floating,n));t&&!r&&L.current&&t.focus({preventScroll:!0})},[a,D,O,ne,te,d]),Ae(()=>{ae.current=E,ie.current=!!D});let me=r!=null,he=A(e=>{if(!ue.current)return;let t=n.current.indexOf(e.currentTarget);t!==-1&&(F.current!==t||r!==t)&&(F.current=t,R(e))}),ge=A(()=>v??ne?.nodesRef.current.find(e=>e.id===te)?.context?.dataRef?.current.orientation),_e=A(()=>re(n,le.current)),U=A(t=>{if(L.current=!1,oe.current=!0,t.which===229||!ue.current&&t.currentTarget===N.current)return;if(l&&Ev(t.key,g,u,T)){Cv(t.key,ge())||In(t),e.setOpen(!1,Ar(Vt,t.nativeEvent));let n=C?.current??O;nr(n)&&n.focus();return}r!=null&&r!==F.current&&!ee(n.current,r)&&(F.current=r);let i=F.current,a=re(n,h),o=nt(n,h);if(M||(t.key===`Home`&&(In(t),F.current=a,R(t)),t.key===`End`&&(In(t),F.current=o,R(t))),w!=null){let e=w(t,F.current,n,g,c,u,h,a,o);if(e!=null&&e!==F.current&&(F.current=e,R(t)),g===`both`)return}if(Cv(t.key,g)){In(t);let e=fr(t.currentTarget.ownerDocument);if(E&&!d&&jn(t.currentTarget,e)&&!n.current.some(t=>t!=null&&jn(t,e))){F.current=wv(t.key,g,u)?a:o,R(t),r===F.current&&pe();return}let{index:l,wrapped:f}=Qe(n.current,i,{decrement:!wv(t.key,g,u),loopFocus:c,allowEscape:s,disabledIndices:h,minIndex:a,maxIndex:o});f&&(oe.current=!1),F.current=l,R(t)}}),ve=Q.useMemo(()=>({onFocus(e){oe.current=!0,he(e)},onClick({currentTarget:e}){d||e.focus({preventScroll:!0})},onMouseMove(e){xv(e)||(oe.current=!0,se.current=!1,p&&he(e))},onPointerLeave(e){if(!ue.current||!L.current||e.pointerType===`touch`)return;oe.current=!0;let t=e.relatedTarget;if(!(!p||n.current.includes(t))&&de.current&&(ce.current?.(),ce.current=null,F.current=-1,R(e),!d)){let e=N.current,t=fr(ye(e));e&&jn(e,t)&&e.focus({preventScroll:!0})}}}),[he,ue,N,p,n,R,de,d]),be=Q.useMemo(()=>d&&E&&me&&{"aria-activedescendant":`${y}-${r}`},[d,E,me,y,r]),W=Q.useMemo(()=>({...M?{}:be,onKeyDown(t){if(t.key===`Tab`&&t.shiftKey&&E&&!d){let n=br(t.nativeEvent);if(n&&!jn(N.current,n))return;In(t);let r=Ar(_n,t.nativeEvent);e.setOpen(!1,r);let i=C?.current??O;!r.isCanceled&&nr(i)&&i.focus();return}U(t)},onPointerMove(e){xv(e)||(L.current=!0)}}),[be,U,N,M,e,E,d,O,C]),xe=Q.useMemo(()=>{function t(t){e.setOpen(!0,Ar(Vt,t.nativeEvent,t.currentTarget))}function n(e){f===`auto`&&rn(e.nativeEvent)&&(P.current=!d)}function r(e){P.current=f,f===`auto`&&$n(e.nativeEvent)&&(P.current=!0)}return{onKeyDown(n){let r=e.select(`open`);L.current=!1;let i=n.key.startsWith(`Arrow`),a=Tv(n.key,ge(),u),o=Cv(n.key,r?g:_),s=(l?a:o)||n.key===`Enter`||n.key.trim()===``;if(d&&r&&(!l||gr(n.currentTarget)))return U(n);if(!(!r&&!m&&i)){if(s){let e=Cv(n.key,ge());I.current=l&&e?null:n.key}if(l){a&&(In(n),r?(F.current=_e(),R(n),d&&N.current?.focus()):t(n));return}o&&(V.current!=null&&(F.current=V.current),In(n),!r&&m?t(n):U(n),r&&R(n))}},onFocus(t){t.target===t.currentTarget&&e.select(`open`)&&!d&&(F.current=-1,R(t))},onPointerDown:r,onPointerEnter:r,onMouseDown:n,onClick:n}},[U,f,_e,l,R,e,m,g,_,ge,u,V,d,N]),Se=Q.useMemo(()=>({...be,...xe}),[be,xe]);return Q.useMemo(()=>a?{reference:Se,floating:W,item:ve,trigger:xe}:{},[a,Se,W,xe,ve])}function Ov(e,t){let{listRef:n,elementsRef:r,activeIndex:i,onMatch:a,disabledIndices:o,onTyping:s,enabled:c=!0,resetMs:l=750,selectedIndex:u=null}=t,d=A(s),f=e.useState(`open`),p=ln(),m=Q.useRef(``),h=Q.useRef(u??i??-1),g=Q.useRef(null),_=A(e=>{function t(e){return r?.current[e]}function s(e){let n=t(e);return n&&!ot(n)||n?.matches(`:disabled`)?!1:o==null||!de(x,e,o)}function c(e,t,n=0){if(e.length===0)return-1;let r=(n%e.length+e.length)%e.length,i=t.toLowerCase();for(let t=0;t<e.length;t+=1){let n=(r+t)%e.length;if(!(!e[n]?.toLowerCase().startsWith(i)||!s(n)))return n}return-1}let _=n.current;if(m.current.length>0&&e.key===` `&&(In(e),d?.(!0)),m.current.length>0&&m.current[0]!==` `&&c(_,m.current)===-1&&e.key!==` `&&d?.(!1),_==null||e.key.length!==1||e.ctrlKey||e.metaKey||e.altKey)return;f&&e.key!==` `&&(In(e),d?.(!0));let v=m.current===``;v&&(h.current=u??i??-1),_.every((e,t)=>e&&s(t)?e[0]?.toLowerCase()!==e[1]?.toLowerCase():!0)&&m.current===e.key&&(m.current=``,h.current=g.current),m.current+=e.key,p.start(l,()=>{m.current=``,h.current=g.current,d?.(!1)});let y=((v?u??i??-1:h.current)??0)+1,b=c(_,m.current,y);b===-1?e.key!==` `&&(m.current=``,d?.(!1)):(a?.(b,e),g.current=b)}),v=A(t=>{let n=t.relatedTarget,r=e.select(`domReferenceElement`),i=e.select(`floatingElement`);jn(r,n)||jn(i,n)||(p.clear(),m.current=``,h.current=g.current,d?.(!1))});Ae(()=>{!f&&u!==null||(p.clear(),g.current=null,m.current!==``&&(m.current=``,d?.(!1)))},[f,u,p,d]);let y=Q.useMemo(()=>({onKeyDown:_,onBlur:v}),[_,v]);return Q.useMemo(()=>c?{reference:y,floating:y}:{},[c,y])}var kv=.1,Av=kv*kv,jv=.5;function Mv(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function Nv(e,t,n,r,i,a,o,s,c,l){let u=!1;return Mv(e,t,n,r,i,a)&&(u=!u),Mv(e,t,i,a,o,s)&&(u=!u),Mv(e,t,o,s,c,l)&&(u=!u),Mv(e,t,c,l,n,r)&&(u=!u),u}function Pv(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function Fv(e,t,n,r,i,a){return e>=Math.min(n,i)&&e<=Math.max(n,i)&&t>=Math.min(r,a)&&t<=Math.max(r,a)}function Iv(e={}){let{blockPointerEvents:t=!1}=e,n=new mn,r=({x:e,y:t,placement:r,elements:i,onClose:a,nodeId:o,tree:s})=>{let c=r?.split(`-`)[0],l=!1,u=null,d=null,f=typeof performance<`u`?performance.now():0;function p(e,t){let n=performance.now(),r=n-f;if(u===null||d===null||r===0)return u=e,d=t,f=n,!1;let i=e-u,a=t-d,o=i*i+a*a,s=r*r*Av;return u=e,d=t,f=n,o<s}function m(){n.clear(),a()}return function(r){n.clear();let a=i.domReference,u=i.floating;if(!a||!u||c==null||e==null||t==null)return;let{clientX:d,clientY:f}=r,h=br(r),g=r.type===`mouseleave`,_=jn(u,h),v=jn(a,h);if(_&&(l=!0,!g))return;if(v&&(l=!1,!g)){l=!0;return}if(g&&H(r.relatedTarget)&&jn(u,r.relatedTarget))return;function y(){return!!(s&&ze(s.nodesRef.current,o).length>0)}function b(){y()||m()}if(y())return;let x=a.getBoundingClientRect(),S=u.getBoundingClientRect(),C=e>S.right-S.width/2,w=t>S.bottom-S.height/2,T=S.width>x.width,E=S.height>x.height,D=(T?x:S).left,O=(T?x:S).right,k=(E?x:S).top,A=(E?x:S).bottom;if(c===`top`&&t>=x.bottom-1||c===`bottom`&&t<=x.top+1||c===`left`&&e>=x.right-1||c===`right`&&e<=x.left+1){b();return}let j=!1;switch(c){case`top`:j=Fv(d,f,D,x.top+1,O,S.bottom-1);break;case`bottom`:j=Fv(d,f,D,S.top+1,O,x.bottom-1);break;case`left`:j=Fv(d,f,S.right-1,A,x.left+1,k);break;case`right`:j=Fv(d,f,x.right-1,A,S.left+1,k)}if(j)return;if(l&&!Pv(d,f,x)){b();return}if(!g&&p(d,f)){b();return}let M=!1;switch(c){case`top`:{let n=T?jv/2:jv*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t+jv+1,o=C||T?S.bottom-jv:S.top,s=C?T?S.bottom-jv:S.top:S.bottom-jv;M=Nv(d,f,r,a,i,a,S.left,o,S.right,s);break}case`bottom`:{let n=T?jv/2:jv*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t-jv,o=C||T?S.top+jv:S.bottom,s=C?T?S.top+jv:S.bottom:S.top+jv;M=Nv(d,f,r,a,i,a,S.left,o,S.right,s);break}case`left`:{let n=E?jv/2:jv*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e+jv+1,o=w||E?S.right-jv:S.left,s=w?E?S.right-jv:S.left:S.right-jv;M=Nv(d,f,o,S.top,s,S.bottom,a,r,a,i);break}case`right`:{let n=E?jv/2:jv*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e-jv,o=w||E?S.left+jv:S.right,s=w?E?S.left+jv:S.right:S.left+jv;M=Nv(d,f,a,r,a,i,o,S.top,s,S.bottom);break}}M?l||n.start(40,b):b()}};return r.__options={...e,blockPointerEvents:t},r}function Lv(e,t,n){let{reference:r,floating:i}=e,a=K_(t),o=q_(t),s=G_(o),c=H_(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=U_(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function Rv(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=V_(t,e),p=av(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=ov(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=ov(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var zv=50,Bv=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:Rv},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=Lv(l,r,c),f=r,p=0,m={};for(let n=0;n<a.length;n++){let h=a[n];if(!h)continue;let{name:g,fn:_}=h,{x:v,y,data:b,reset:x}=await _({x:u,y:d,initialPlacement:r,placement:f,strategy:i,middlewareData:m,rects:l,platform:s,elements:{reference:e,floating:t}});u=v??u,d=y??d,m[g]={...m[g],...b},x&&p<zv&&(p++,typeof x==`object`&&(x.placement&&(f=x.placement),x.rects&&(l=x.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):x.rects),{x:u,y:d}=Lv(l,f,c)),n=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:m}},Vv=function(e){return e===void 0&&(e={}),{name:`flip`,options:e,async fn(t){var n;let{placement:r,middlewareData:i,rects:a,initialPlacement:o,platform:s,elements:c}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:f=`bestFit`,fallbackAxisSideDirection:p=`none`,flipAlignment:m=!0,...h}=V_(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let g=H_(r),_=K_(o),v=H_(o)===o,y=await(s.isRTL==null?void 0:s.isRTL(c.floating)),b=d||(v||!m?[rv(o)]:Y_(o)),x=p!==`none`;!d&&x&&b.push(...nv(o,m,p,y));let S=[o,...b],C=await s.detectOverflow(t,h),w=[],T=i.flip?.overflows||[];if(l&&w.push(C[g]),u){let e=J_(r,a,y);w.push(C[e[0]],C[e[1]])}if(T=[...T,{placement:r,overflows:w}],!w.every(e=>e<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(u!==`alignment`||_===K_(t)||T.every(e=>K_(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=K_(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o}if(r!==n)return{reset:{placement:n}}}return{}}}},Hv=new Set([`left`,`top`]);async function Uv(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=H_(n),s=U_(n),c=K_(n)===`y`,l=Hv.has(o)?-1:1,u=a&&c?-1:1,d=V_(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var Wv=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await Uv(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},Gv=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=V_(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=K_(i),p=W_(f),m=u[p],h=u[f],g=(e,t)=>B_(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},Kv=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=V_(e,t),u={x:n,y:r},d=K_(i),f=W_(d),p=u[f],m=u[d],h=V_(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;p<t?p=t:p>n&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=Hv.has(H_(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);m<n?m=n:m>r&&(m=r)}return{[f]:p,[d]:m}}}},qv=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=V_(e,t),c=await i.detectOverflow(t,s),l=H_(n),u=U_(n),d=K_(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=P_(p-c[m],g),y=P_(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*F_(c.left,c.right):S=p-2*F_(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function Jv(e){let t=ie(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=nr(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=I_(n)!==a||I_(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function Yv(e){return H(e)?e:e.contextElement}function Xv(e){let t=Yv(e);if(!nr(t))return R_(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=Jv(t),o=(a?I_(n.width):n.width)/r,s=(a?I_(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var Zv=R_(0);function Qv(e){let t=st(e);return!Fe()||!t.visualViewport?Zv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function $v(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===st(e)}function ey(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=Yv(e),o=R_(1);t&&(r?H(r)&&(o=Xv(r)):o=Xv(e));let s=$v(a,n,r)?Qv(a):R_(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=st(a),t=H(r)?st(r):r,n=e,i=Ur(n);for(;i&&t!==n;){let e=Xv(i),t=i.getBoundingClientRect(),r=ie(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=st(i),i=Ur(n)}}return ov({width:u,height:d,x:c,y:l})}function ty(e,t){let n=rt(e).scrollLeft;return t?t.left+n:ey(Be(e)).left+n}function ny(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ty(e,n),y:n.top+t.scrollTop}}function ry(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=Be(r),s=t?St(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=R_(1),u=R_(0),d=nr(r);if((d||!a)&&((m(r)!==`body`||_t(o))&&(c=rt(r)),d)){let e=ey(r);l=Xv(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?ny(o,c):R_(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function iy(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function ay(e){let t=rt(e),n=e.ownerDocument.body,r=F_(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=F_(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+ty(e),o=-t.scrollTop;return ie(n).direction===`rtl`&&(a+=F_(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var oy=25;function sy(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=st(e),a=Be(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!Fe()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(ty(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=oy&&(s-=o)}return{width:s,height:c,x:l,y:u}}function cy(e,t){let n=ey(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=Xv(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function ly(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=sy(e,n,t);else if(t===`document`)r=ay(Be(e));else if(H(t))r=cy(t,n);else{let n=Qv(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return ov(r)}function uy(e,t){let n=t.get(e);if(n)return n;let r=I(e,[],!1).filter(e=>H(e)&&m(e)!==`body`),i=null,a=ie(e).position===`fixed`,o=a?$e(e):e;for(;H(o)&&!ce(o);){let e=ie(o),t=te(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=$e(o)}return t.set(e,r),r}function dy(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?St(t)?[]:uy(t,this._c):[].concat(n),r],o=ly(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e<a.length;e++){let n=ly(t,a[e],i);s=F_(n.top,s),c=P_(n.right,c),l=P_(n.bottom,l),u=F_(n.left,u)}return{width:c-u,height:l-s,x:u,y:s}}function fy(e){let{width:t,height:n}=Jv(e);return{width:t,height:n}}function py(e,t,n){let r=nr(t),i=Be(t),a=n===`fixed`,o=ey(e,!0,a,t),s={scrollLeft:0,scrollTop:0},c=R_(0);if((r||!a)&&((m(t)!==`body`||_t(i))&&(s=rt(t)),r)){let e=ey(t,!0,a,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}!r&&i&&(c.x=ty(i));let l=i&&!r&&!a?ny(i,s):R_(0);return{x:o.left+s.scrollLeft-c.x-l.x,y:o.top+s.scrollTop-c.y-l.y,width:o.width,height:o.height}}function my(e){return ie(e).position===`static`}function hy(e,t){if(!nr(e)||ie(e).position===`fixed`)return null;if(t)return t(e);let n=e.offsetParent;return Be(e)===n&&(n=n.ownerDocument.body),n}function gy(e,t){let n=st(e);if(St(e))return n;if(!nr(e)){let t=$e(e);for(;t&&!ce(t);){if(H(t)&&!my(t))return t;t=$e(t)}return n}let r=hy(e,t);for(;r&&ft(r)&&my(r);)r=hy(r,t);return r&&ce(r)&&my(r)&&!te(r)?n:r||ge(e)||n}var _y=async function(e){let t=this.getOffsetParent||gy,n=this.getDimensions,r=await n(e.floating);return{reference:py(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function vy(e){return ie(e).direction===`rtl`}var yy={convertOffsetParentRelativeRectToViewportRelativeRect:ry,getDocumentElement:Be,getClippingRect:dy,getOffsetParent:gy,getElementRects:_y,getClientRects:iy,getDimensions:fy,getScale:Xv,isElement:H,isRTL:vy};function by(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function xy(e,t,n){let r=null,i,a=Be(e);function o(){var e;clearTimeout(i),(e=r)==null||e.disconnect(),r=null}function s(n,c){n===void 0&&(n=!1),c===void 0&&(c=1),o();let l=e.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=l;if(n||t(),!f||!p)return;let m=L_(d),h=L_(a.clientWidth-(u+f)),g=L_(a.clientHeight-(d+p)),_=L_(u),v={rootMargin:-m+`px `+-h+`px `+-g+`px `+-_+`px`,threshold:F_(0,P_(1,c))||1},y=!0;function b(t){let n=t[0].intersectionRatio;if(!by(l,e.getBoundingClientRect()))return s();if(n!==c){if(!y)return s();n?s(!1,n):i=setTimeout(()=>{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=st(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function Sy(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=Yv(e),u=i||a?[...l?I(l):[],...t?I(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?xy(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?ey(e):null;c&&g();function g(){let t=ey(e);h&&!by(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var Cy=Wv,wy=Gv,Ty=Vv,Ey=qv,Dy=Kv,Oy=(e,t,n)=>{let r=new Map,i=n??{},a={...yy,...i.platform,_c:r};return Bv(e,t,{...i,platform:a})},ky=typeof document<`u`?Q.useLayoutEffect:function(){};function Ay(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e==`function`&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ay(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!Ay(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function jy(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function My(e,t){let n=jy(e);return Math.round(t*n)/n}function Ny(e){let t=Q.useRef(e);return ky(()=>{t.current=e}),t}function Py(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=Q.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=Q.useState(r);Ay(f,r)||p(r);let[m,h]=Q.useState(null),[g,_]=Q.useState(null),v=Q.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=Q.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=Q.useRef(null),C=Q.useRef(null),w=Q.useRef(u),T=c!=null,E=Ny(c),D=Ny(i),O=Ny(l),k=Q.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),Oy(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};A.current&&!Ay(w.current,t)&&(w.current=t,vv.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);ky(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let A=Q.useRef(!1);ky(()=>(A.current=!0,()=>{A.current=!1}),[]),ky(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,k);k()}},[b,x,k,E,T]);let j=Q.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),M=Q.useMemo(()=>({reference:b,floating:x}),[b,x]),N=Q.useMemo(()=>{let e={position:n,left:0,top:0};if(!M.floating)return e;let t=My(M.floating,u.x),r=My(M.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...jy(M.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,M.floating,u.x,u.y]);return Q.useMemo(()=>({...u,update:k,refs:j,elements:M,floatingStyles:N}),[u,k,j,M,N])}var Fy=(e,t)=>{let n=Cy(e);return{name:n.name,fn:n.fn,options:[e,t]}},Iy=(e,t)=>{let n=wy(e);return{name:n.name,fn:n.fn,options:[e,t]}},Ly=(e,t)=>({fn:Dy(e).fn,options:[e,t]}),Ry=(e,t)=>{let n=Ty(e);return{name:n.name,fn:n.fn,options:[e,t]}},zy=(e,t)=>{let n=Ey(e);return{name:n.name,fn:n.fn,options:[e,t]}},By=Q.createContext(void 0);function Vy(e){let t=Q.useContext(By);if(t===void 0&&!e)throw Error(U(69));return t}function Hy(e){return e===`starting`?xe:we}var Uy=Q.createContext(void 0);function Wy(){return Q.useContext(Uy)}function Gy(e,t){let n=_(e.render);if(Q.isValidElement(n)){let e=n.props;if(Object.hasOwn(e,`id`))return e.id??``}return e.id??t}function Ky(e,t,n){let r=Gy(e,t),i=r===t?void 0:r;return[r,Q.useCallback(e=>n?.(e?i:void 0),[i,n])]}function qy(e,t,n){let r=_(e.render),i=Q.isValidElement(r)?r.props:void 0,a=e[`aria-label`]??i?.[`aria-label`],o=e[`aria-labelledby`]??i?.[`aria-labelledby`];return o==null&&!a&&(o=t?t.id||void 0:n||void 0),o}var Jy=Q.forwardRef(function(e,t){let{render:n,className:r,style:i,finalFocus:a,id:s,initialFocus:c,...l}=e,{store:u,defaultFloatingId:d,setRenderedFloatingId:f,virtualFocus:p,orientation:m}=t_(),h=Wy(),{side:g,align:_}=$g(),y=Vy(!0)!=null,b=u.useState(`open`),x=u.useState(`transitionStatus`),S=u.useState(`popupProps`),C=u.useState(`mounted`),w=u.useState(`instantType`),T=u.useState(`activeTriggerElement`),E=u.useState(`parent`),D=u.useState(`lastOpenChangeReason`),O=u.useState(`rootId`),k=u.useState(`floatingRootContext`),A=u.useState(`floatingTreeRoot`),j=u.useState(`closeDelay`),M=u.useState(`hoverEnabled`),N=u.useState(`disabled`),ee=u.useState(`openMethod`),te=u.useState(`activeTriggerId`),ne=u.useState(`listElement`),[P,F]=Ky(e,d,f),re=qy(e,T,te),I=E.type===`menu`?h:void 0,L=E.type===`context-menu`,R=c??E.type!==`menu`;c===void 0&&ne&&E.type!==`menu`&&(R=()=>u.state.activeIndex===null&&ne),Ot({open:b,ref:u.context.popupRef,onComplete(){b&&u.context.onOpenChangeComplete?.(!0)}}),Q.useEffect(()=>{function e(e){u.setOpen(!1,Ar(e.reason,e.domEvent))}return A.events.on(`close`,e),()=>{A.events.off(`close`,e)}},[A.events,u]),_v(k,{enabled:M&&!N&&!L&&E.type!==`menubar`,closeDelay:j});let z=u.useStateSetter(`popupElement`),{parentVirtualFocusRef:ie,handleFocus:ae}=(Q.useContext(i_)?.useParentHandoff??Xy)(u,E,b,p),oe={transitionStatus:x,side:g,align:_,open:b,nested:E.type===`menu`,instant:w},se=Or(`div`,e,{state:oe,ref:[t,u.context.popupRef,z,F],stateAttributesMapping:Et,props:[S,{id:P,...ne?{role:`presentation`}:{role:`menu`,"aria-orientation":m===`horizontal`?`horizontal`:void 0,"aria-labelledby":re},onKeyDown(e){I?.onPopupKeyDown?.(e),y&&o.has(e.key)&&e.stopPropagation()},onFocus:ae},Hy(x),l,{"data-rootownerid":O}]}),B=E.type===void 0||L;(T||E.type===`menubar`&&D!==`outside-press`)&&(B=!0);let ce=I?.getReturnElement??ie;return(0,$.jsx)(v,{context:k,openInteractionType:ee,modal:L,disabled:!C,returnFocus:a??ce??B,explicitReturnFocus:a===void 0&&ce?!1:void 0,initialFocus:R,restoreFocus:!0,getInsideElements:E.type===void 0?()=>[u.context.beforeTriggerFocusGuardRef.current]:void 0,externalTree:E.type===`menubar`?void 0:A,previousFocusableElement:T,nextFocusableElement:E.type===void 0?u.context.triggerFocusTargetRef:void 0,beforeContentFocusGuardRef:u.context.beforeContentFocusGuardRef,children:se})}),Yy={parentVirtualFocusRef:void 0,handleFocus:void 0};function Xy(){return Yy}var Zy=Q.forwardRef(function(e,t){let n=a_()?.Popup??Jy;return(0,$.jsx)(n,{...e,ref:t})}),Qy=Q.createContext(void 0);function $y(){let e=Q.useContext(Qy);if(e===void 0)throw Error(U(32));return e}var eb=Q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,{store:i,parent:a}=t_();if(!(i.useState(`mounted`)||n))return null;let o=a.type===`menu`||a.type===`menubar`?`group`:void 0;return(0,$.jsx)(Qy.Provider,{value:n,children:(0,$.jsx)(l,{ref:t,...r,portalOwnerRole:o})})});function tb(e){let{nodeId:t,externalTree:n,rootContext:r}=e,i=r.useState(`referenceElement`),a=r.useState(`floatingElement`),o=r.useState(`domReferenceElement`),s=r.useState(`open`),c=r.useState(`floatingId`),[l,u]=Q.useState(null),d=Q.useRef(null),f=Te(n),p=Q.useMemo(()=>({reference:i,floating:a,domReference:o}),[i,a,o]),m=Py({...e,elements:{...p,...l&&{reference:l}}}),h=Q.useCallback(e=>{let t=H(e)?{getBoundingClientRect:()=>e.getBoundingClientRect(),getClientRects:()=>e.getClientRects(),contextElement:e}:e;u(t),m.refs.setReference(t)},[m.refs]),g=Q.useMemo(()=>({...m.refs,setPositionReference:h,domReference:d}),[m.refs,h]),_=Q.useMemo(()=>({...m.elements,domReference:o}),[m.elements,o]),v=Q.useMemo(()=>({...m,dataRef:r.context.dataRef,open:s,onOpenChange:r.setOpen,events:r.context.events,floatingId:c,refs:g,elements:_,nodeId:t,rootStore:r}),[m,g,_,t,r,s,c]);return Ae(()=>{o&&(d.current=o)},[o]),Ae(()=>{r.context.dataRef.current.floatingContext=v;let e=f?.nodesRef.current.find(e=>e.id===t);e&&(e.context=v)}),Q.useMemo(()=>({...m,context:v,refs:g,elements:_,rootStore:r}),[m,g,_,v,r])}var nb=Q.createContext(void 0);function rb(){return Q.useContext(nb)?.direction??`ltr`}var ib=e=>({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=V_(e,t)||{};if(l==null)return{};let d=av(u),f={x:n,y:r},p=q_(i),m=G_(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=s.floating[y]||a.floating[m],C=b/2-x/2,w=S/2-h[m]/2-1,T=Math.min(d[_],w),E=Math.min(d[v],w),D=T,O=S-h[m]-E,k=S/2-h[m]/2+C,A=B_(D,k,O),j=!c.arrow&&U_(i)!=null&&k!==A&&a.reference[m]/2-(k<D?T:E)-h[m]/2<0,M=j?k<D?k-D:k-O:0;return{[p]:f[p]+M,data:{[p]:A,centerOffset:k-A-M,...j&&{alignmentOffset:M}},reset:j}}}),ab=(e,t)=>{let{name:n,fn:r}=ib(e);return{name:n,fn:r,options:[e,t]}},ob={name:`hide`,async fn(e){let{width:t,height:n,x:r,y:i}=e.rects.reference,a=t===0&&n===0&&r===0&&i===0,o=await e.platform.detectOverflow(e,{elementContext:`reference`});return{data:{referenceHidden:o.top-n>=0||o.right-t>=0||o.bottom-n>=0||o.left-t>=0||a}}}},sb={sideX:`left`,sideY:`top`},cb=`--available-width`,lb=`--available-height`,ub=`--anchor-width`,db=`--anchor-height`,fb=`--transform-origin`,pb=cb,mb=lb;function hb(e,t,n){let r=e===`inline-start`||e===`inline-end`;return{top:`top`,right:r?n?`inline-start`:`inline-end`:`right`,bottom:`bottom`,left:r?n?`inline-end`:`inline-start`:`left`}[t]}function gb(e,t,n){let{rects:r,placement:i}=e;return{side:hb(t,H_(i),n),align:U_(i)||`center`,anchor:{width:r.reference.width,height:r.reference.height},positioner:{width:r.floating.width,height:r.floating.height}}}function _b(e){return vb(e,tb)}function vb(e,t){let{anchor:n,positionMethod:r=`absolute`,side:i=`bottom`,sideOffset:a=0,align:o=`center`,alignOffset:s=0,collisionBoundary:c,collisionPadding:l=5,sticky:u=!1,arrowPadding:d=5,disableAnchorTracking:f=!1,inline:p,keepMounted:m=!1,floatingRootContext:h,mounted:g,collisionAvoidance:_,shift:v,nodeId:y,adaptiveOrigin:b,lazyFlip:x=!1,externalTree:S}=e,C=_.side||`flip`,w=_.align||`flip`,T=_.fallbackAxisSide||`end`,E=v?.crossAxis??!1,D=v?.rootBoundary,O=typeof n==`function`?n:void 0,k=A(O),j=O?k:n,M=B(n),N=B(g),ee=rb()===`rtl`,[te,ne]=Q.useState(null);!g&&te!==null&&ne(null);let P=x===`placement`,F=te?H_(te):null,re=te&&P?U_(te)||`center`:null,I=F||{top:`top`,right:`right`,bottom:`bottom`,left:`left`,"inline-end":ee?`left`:`right`,"inline-start":ee?`right`:`left`}[i],L=re||o,R=L===`center`?I:`${I}-${L}`,z=l;typeof z==`number`?z={top:z,right:z,bottom:z,left:z}:z&&={top:z.top||0,right:z.right||0,bottom:z.bottom||0,left:z.left||0};let ie=+(i===`bottom`),ae=+(i===`top`),oe=+(i===`right`),se=+(i===`left`),ce={boundary:c===`clipping-ancestors`?`clippingAncestors`:c,padding:z},le=Q.useRef(null),ue=B(a),V=B(s),de=typeof a==`function`?0:a,H=typeof s==`function`?0:s,fe=[];p&&fe.push(p),fe.push(Fy(e=>{let t=gb(e,i,ee),n=typeof ue.current==`function`?ue.current(t):ue.current,r=typeof V.current==`function`?V.current(t):V.current;return{mainAxis:n,crossAxis:r,alignmentAxis:r}},[de,H,ee,i]));let pe=w===`none`&&C!==`shift`,me=!pe&&(u||E||C===`shift`),he=C===`none`?null:Ry({...ce,padding:{top:z.top+1+ie,right:z.right+1+se,bottom:z.bottom+1+ae,left:z.left+1+oe},mainAxis:!E&&C===`flip`,crossAxis:w===`flip`&&`alignment`,fallbackAxisSideDirection:T}),ge=pe?null:Iy({...ce,rootBoundary:D,mainAxis:w!==`none`,crossAxis:me,limiter:u||E?void 0:Ly(e=>{if(!le.current)return{};let{width:t,height:n}=le.current.getBoundingClientRect(),r=K_(H_(e.placement)),i=r===`y`?t:n,a=r===`y`?z.left+z.right:z.top+z.bottom;return{offset:i/2+a/2}})},[ce,u,E,D,z,w]);C===`shift`||w===`shift`||L===`center`?fe.push(ge,he):fe.push(he,ge),fe.push(zy({...ce,apply({elements:{floating:e},availableWidth:t,availableHeight:n,rects:r}){if(!N.current)return;let i=e.style;i.setProperty(pb,`${t}px`),i.setProperty(mb,`${n}px`);let a=st(e).devicePixelRatio||1,{x:o,y:s,width:c,height:l}=r.reference,u=(Math.round((o+c)*a)-Math.round(o*a))/a,d=(Math.round((s+l)*a)-Math.round(s*a))/a;i.setProperty(ub,`${u}px`),i.setProperty(db,`${d}px`)}}),ab(e=>({element:le.current||ye(e.elements.floating).createElement(`div`),padding:le.current?d:0}),[d]),{name:`transformOrigin`,fn(e){let{elements:{floating:t},middlewareData:n,placement:r,platform:o,rects:s,y:c}=e,l=H_(r),u=U_(r),d=K_(l)===`y`,f=le.current,p=typeof a==`function`?a(gb(e,i,ee)):a,m;m=!f&&u&&Math.abs(d?n.shift?.x||0:n.shift?.y||0)<=1?u===`start`===(d&&o.isRTL?.(t)===!0)?`100%`:`0%`:`${(d?n.arrow?.x||0:n.arrow?.y||0)+(d?f?.clientWidth||0:f?.clientHeight||0)/2}px`;let h=l===`top`||l===`left`?`calc(100% + ${p}px)`:`${-p}px`;return me&&d&&Math.abs(n.shift?.y||0)>p&&(h=`${s.reference.y+s.reference.height/2-c}px`),t.style.setProperty(fb,d?`${m} ${h}`:`${h} ${m}`),{}}},ob,b),Ae(()=>{!g&&h&&h.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[g,h]);let _e=Q.useMemo(()=>({ancestorScroll:!f,elementResize:!f&&typeof ResizeObserver<`u`,layoutShift:!f&&typeof IntersectionObserver<`u`}),[f]),{refs:U,elements:ve,x:be,y:W,middlewareData:xe,update:Se,placement:Ce,context:we,isPositioned:Te,floatingStyles:Ee}=t({rootContext:h,open:m?g:void 0,placement:R,middleware:fe,strategy:r,whileElementsMounted:m?void 0:(...e)=>Sy(...e,_e),nodeId:y,externalTree:S}),{sideX:De,sideY:Oe}=xe.adaptiveOrigin||sb,ke=Te?r:`fixed`,je=Q.useMemo(()=>{let e;return e=Te?b?{position:ke,[De]:be,[Oe]:W}:{...Ee,position:ke}:{position:ke,top:0,left:0},e[pb]=`100vw`,e[mb]=`100vh`,Te||(e.opacity=0),e},[b,ke,De,be,Oe,W,Ee,Te]),Me=Q.useRef(null);Ae(()=>{if(!g)return;let e=M.current,t=typeof e==`function`?e():e,n=(yb(t)?t.current:t)||null;n!==Me.current&&(U.setPositionReference(n),Me.current=n)},[g,U,j,M]),Q.useEffect(()=>{if(!g)return;let e=M.current;typeof e!=`function`&&yb(e)&&e.current!==Me.current&&(U.setPositionReference(e.current),Me.current=e.current)},[g,U,j,M]),Q.useEffect(()=>{if(m&&g&&ve.reference&&ve.floating)return Sy(ve.reference,ve.floating,Se,_e)},[m,g,ve,Se,_e]);let Ne=H_(Ce),Pe=hb(i,Ne,ee),Fe=U_(Ce)||`center`,Ie=!!xe.hide?.referenceHidden;Ae(()=>{x&&g&&Te&&(Ne!==I||P&&Fe!==L)&&ne(Ce)},[x,P,g,Te,Ce,Ne,Fe,I,L]);let Le=Q.useMemo(()=>({position:`absolute`,top:xe.arrow?.y,left:xe.arrow?.x}),[xe.arrow]),Re=xe.arrow?.centerOffset!==0;return Q.useMemo(()=>({positionerStyles:je,arrowStyles:Le,arrowRef:le,arrowUncentered:Re,side:Pe,align:Fe,physicalSide:Ne,anchorHidden:Ie,refs:U,context:we,isPositioned:Te,update:Se}),[je,Le,le,Re,Pe,Fe,Ne,Ie,U,we,Te,Se])}function yb(e){return e!=null&&`current`in e}function bb(e){let{children:t,elementsRef:n,labelsRef:r,onMapChange:i}=e,a=A(i),[,o]=Q.useState(0),s=xn(Sb).current,c=xn(xb).current,l=Q.useRef(0),u=Q.useRef(!0),d=Q.useRef(null),f=Q.useRef(null),p=A(()=>{u.current||(u.current=!0,o(e=>e+1))}),m=A((e,t)=>{c.set(e,t),p()}),h=A(e=>{c.delete(e),p()}),g=A(e=>{let t=new Map;return n.current.length=0,r&&(r.current.length=0),e.forEach(e=>{t.set(e.element,{...e.registration.metadata??{},index:e.index}),n.current[e.index]=e.element,r&&(r.current[e.index]=e.registration.label===void 0?e.registration.textRef?.current?.textContent??e.element.textContent:e.registration.label)}),l.current=n.current.length,t});function _(e){if(f.current?.disconnect(),f.current=null,typeof MutationObserver!=`function`||e.length<2)return;let t=new MutationObserver(n=>{if(!Tb(n))return;let r=null;for(let n of e)if(n.isConnected){if(r&&Eb(r,n)>0){t.disconnect(),p();return}r=n}});f.current=t;let n=new Set;for(let t=1;t<e.length;t+=1){let r=wb(e[t-1],e[t]);r&&n.add(r)}n.forEach(e=>t.observe(e,{childList:!0}))}let v=A(()=>{let[e,t]=Cb(c),n=g(e),r=d.current,i=!r||r.length!==e.length||e.some((e,t)=>{let n=r[t];return e.index!==n.index||e.element!==n.element||e.registration.index!==n.registration.index||e.registration.metadata!==n.registration.metadata});_(t),d.current=e,u.current=!1,i&&(s.forEach(e=>e(n)),a(n))});Ae(()=>(!u.current&&d.current&&g(d.current),()=>{n.current=[],r&&(r.current=[])}),[n,r,g]),Ae(()=>{u.current&&v()}),Ae(()=>()=>{f.current?.disconnect(),u.current=!0},[]);let y=A(e=>(s.add(e),()=>{s.delete(e)})),b=Q.useMemo(()=>({register:m,unregister:h,subscribeMapChange:y,nextIndexRef:l}),[m,h,y,l]);return(0,$.jsx)(h_.Provider,{value:b,children:t})}function xb(){return new Map}function Sb(){return new Set}function Cb(e){let t=new Set,n=[],r=[];e.forEach((e,i)=>{if(!i.isConnected)return;let a=e.index,o={index:a??-1,element:i,registration:e};a===null?r.push(o):a>=0&&(t.add(a),n.push(o))});let i=0;return r.sort((e,t)=>Eb(e.element,t.element)),r.forEach(e=>{for(;t.has(i);)i+=1;e.index=i,n.push(e),i+=1}),t.size>0&&n.sort((e,t)=>e.index-t.index),[n,r.map(e=>e.element)]}function wb(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function Tb(e){for(let t of e)for(let e=0;e<t.removedNodes.length;e+=1)if(t.removedNodes[e].isConnected)return!0;return!1}function Eb(e,t){return e.nextElementSibling===t?-1:t.nextElementSibling===e?1:e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function Db(e){let{store:t,domReference:n,positionerElement:r,open:i}=e,a=Q.useRef(null),o=Q.useRef(null),s=Tr(r);Ae(()=>{i||(o.current?.abort(),o.current=null,t.state.instantType===`trigger-change`&&t.set(`instantType`,void 0))},[i,t]),Ae(()=>{let e=n,r=a.current;if(e&&(a.current=e),!r||!e||e===r||!t.select(`open`))return;t.set(`instantType`,void 0);let i=new AbortController;return o.current=i,s(()=>{t.select(`open`)&&t.set(`instantType`,`trigger-change`)},i.signal),()=>{i.abort()}},[n,s,t])}function Ob(e,t,{styles:n,transitionStatus:r,props:i,refs:a,hidden:o,inert:s=!1}){let c={...n};return s&&(c.pointerEvents=`none`),Or(`div`,e,{state:t,ref:a,props:[{role:`presentation`,hidden:o,style:c},Hy(r),i],stateAttributesMapping:sn})}var kb=20;function Ab(e,t,n,r){let[i,a]=Q.useState(!1);Ae(()=>{if(!e||!t||n==null){a(!1);return}let r=ye(n).documentElement.clientWidth,i=n.offsetWidth;a(r>0&&i>0&&i>=r-kb)},[e,t,n]),pt(e&&(!t||i),r)}var jb=Q.forwardRef(function(e,t){let{anchor:n,positionMethod:r=`absolute`,className:i,render:a,side:o,align:s,sideOffset:c=0,alignOffset:l=0,collisionBoundary:u=`clipping-ancestors`,collisionPadding:d=5,arrowPadding:f=5,sticky:p=!1,disableAnchorTracking:m=!1,collisionAvoidance:h=ke,style:g,..._}=e,{store:v,virtualFocus:y,syncHighlightedItem:b}=t_(),x=$y(),S=r_(!0),C=v.useState(`parent`),w=v.useState(`floatingRootContext`),T=v.useState(`floatingTreeRoot`),E=v.useState(`mounted`),D=v.useState(`open`),O=v.useState(`modal`),A=v.useState(`openMethod`),j=v.useState(`activeTriggerElement`),M=v.useState(`transitionStatus`),N=v.useState(`positionerElement`),ee=v.useState(`instantType`),te=v.useState(`adaptiveOrigin`),ne=v.useState(`lastOpenChangeReason`),P=v.useState(`floatingNodeId`),F=v.useState(`floatingParentNodeId`),re=w.useState(`domReferenceElement`),I=n,L=c,R=l,z=s,ie=h;C.type===`context-menu`&&(I=n??C.context?.anchor,z??=`start`,!o&&z!==`center`&&(R=e.alignOffset??2,L=e.sideOffset??-5));let ae=o,oe=z;C.type===`menu`?(ae??=`inline-end`,oe??=`start`,ie=e.collisionAvoidance??k):C.type===`menubar`&&(ae??=C.context.orientation===`vertical`?`inline-end`:`bottom`,oe??=`start`);let se=C.type===`context-menu`,B=_b({anchor:I,floatingRootContext:w,positionMethod:S?`fixed`:r,mounted:E,side:ae,sideOffset:L,align:oe,alignOffset:R,arrowPadding:se?0:f,collisionBoundary:u,collisionPadding:d,sticky:p,nodeId:P,keepMounted:x,disableAnchorTracking:m,collisionAvoidance:ie,shift:se?{crossAxis:!(`side`in ie&&ie.side===`flip`),rootBoundary:`layoutViewport`}:void 0,externalTree:T,adaptiveOrigin:te,lazyFlip:y?`placement`:!1});Q.useEffect(()=>{function e(e){e.open&&(e.parentNodeId===P&&v.set(`hoverEnabled`,!1),e.nodeId!==P&&e.parentNodeId===v.select(`floatingParentNodeId`)&&v.setOpen(!1,Ar(tn)))}return T.events.on(`menuopenchange`,e),()=>{T.events.off(`menuopenchange`,e)}},[v,T.events,P]),Q.useEffect(()=>{if(v.select(`floatingParentNodeId`)==null)return;function e(e){if(e.open||e.nodeId!==v.select(`floatingParentNodeId`))return;let t=e.reason??`sibling-open`;v.setOpen(!1,Ar(t))}return T.events.on(`menuopenchange`,e),()=>{T.events.off(`menuopenchange`,e)}},[T.events,v]);let ce=ln();Q.useEffect(()=>{D||ce.clear()},[D,ce]),Q.useEffect(()=>{function e(e){if(!(!D||e.nodeId!==v.select(`floatingParentNodeId`))){if(e.target&&j&&j!==e.target){let e=v.select(`closeDelay`);e>0?ce.isStarted()||ce.start(e,()=>{v.setOpen(!1,Ar(tn))}):v.setOpen(!1,Ar(tn))}else ce.clear()}}return T.events.on(`itemhover`,e),()=>{T.events.off(`itemhover`,e)}},[T.events,D,j,v,ce]),Q.useEffect(()=>{let e={open:D,nodeId:P,parentNodeId:F,reason:v.select(`lastOpenChangeReason`)};T.events.emit(`menuopenchange`,e)},[T.events,D,v,P,F]),Db({store:v,domReference:re,positionerElement:N,open:D});let le={open:D,side:B.side,align:B.align,anchorHidden:B.anchorHidden,nested:C.type===`menu`,instant:ee},ue=C.type===`menubar`&&C.context.modal;Ab(D&&(ue||O&&ne!==`trigger-hover`),A===`touch`,N,j);let V=Ob(e,le,{styles:B.positionerStyles,transitionStatus:M,props:_,refs:[t,v.useStateSetter(`positionerElement`)],hidden:!E,inert:!D}),de=E&&C.type!==`menu`&&(C.type!==`menubar`&&O&&ne!==`trigger-hover`||C.type===`menubar`&&C.context.modal),H=null;return C.type===`menubar`?H=C.context.contentElement:C.type===void 0&&(H=j),(0,$.jsxs)(Qg.Provider,{value:B,children:[de&&(0,$.jsx)(Ct,{ref:C.type===`context-menu`||C.type===`nested-context-menu`?C.context.internalBackdropRef:null,inert:Ie(!D),cutout:H}),(0,$.jsx)(kr,{id:P,children:(0,$.jsx)(bb,{elementsRef:v.context.itemDomElements,labelsRef:v.context.itemLabels,onMapChange:b,children:V})})]})}),Mb=Q.createContext(null);function Nb(e){let t=Q.useContext(Mb);if(t===null&&!e)throw Error(U(5));return t}function Pb(e){return e==null?kn:e.type.startsWith(`key`)?ur:e.type.startsWith(`mouse`)||e.type.startsWith(`pointer`)?Kt:kn}var Fb={...Bn,disabled:e=>e.parent.type===`menubar`&&e.parent.context.disabled||e.disabled,modal:e=>(e.parent.type===void 0||e.parent.type===`context-menu`)&&(e.modal??!0),openMethod:e=>e.openMethod,keyboardOpen:e=>e.keyboardOpen,allowMouseEnter:e=>e.allowMouseEnter,highlightItemOnHover:e=>e.highlightItemOnHover,parent:e=>e.parent,rootId:e=>e.parent.type===`menu`?e.parent.store.select(`rootId`):e.parent.type===void 0?e.rootId:e.parent.context.rootId,activeIndex:e=>e.activeIndex,listElement:e=>e.listElement,triggerControlsId:(e,t)=>{let n=Bn.triggerPopupId(e,t);return n?e.listElement?.id||n:void 0},filterTriggerProps:e=>e.filterTriggerProps,inputProps:e=>e.inputProps,webkitAriaSelected:(e,t)=>Ee&&e.inputFocused&&t?!0:void 0,highlightedItemId:e=>e.highlightedItem?.id||void 0,isActive:(e,t)=>e.activeIndex===t,hoverEnabled:e=>e.hoverEnabled,instantType:e=>e.instantType===`trigger-change`&&!Bn.open(e)?void 0:e.instantType,lastOpenChangeReason:e=>e.openChangeReason,floatingTreeRoot:e=>e.parent.type===`menu`?e.parent.store.select(`floatingTreeRoot`):e.floatingTreeRoot,floatingNodeId:e=>e.floatingNodeId,floatingParentNodeId:e=>e.floatingParentNodeId,itemProps:e=>e.itemProps,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin,keyboardEventRelay:e=>{if(e.keyboardEventRelay)return e.keyboardEventRelay;if(e.parent.type===`menu`)return e.parent.store.select(`keyboardEventRelay`)}},Ib=class extends or{constructor(e,t,n=!1){let r=new dr,i=Rb(r,t,n,e);super(i,Lb(r),Fb),this.observe(`parent`,e=>{e.type===`menu`?this.context.allowMouseUpTriggerRef=e.store.context.allowMouseUpTriggerRef:e.type!==void 0&&(this.context.allowMouseUpTriggerRef=e.context.allowMouseUpTriggerRef)})}subscribeToParentMenu(){let e=this.state.parent;if(e.type!==`menu`)return;let t=e.store.select(`rootId`),n=e.store.select(`floatingTreeRoot`),r=e.store.select(`keyboardEventRelay`);return e.store.subscribe(()=>{let i=e.store.select(`rootId`),a=e.store.select(`floatingTreeRoot`),o=e.store.select(`keyboardEventRelay`);(t!==i||n!==a||r!==o)&&(t=i,n=a,r=o,this.notifyAll())})}setOpen(e,t){this.state.floatingRootContext.context.events.emit(`setOpen`,{open:e,eventDetails:t})}setActiveIndex(e,t,n){if(this.state.activeIndex!==e){let r=(e===null?void 0:this.context.itemDomElements.current[e])===this.context.reportedItem;this.context.highlightReason=r?`none`:t,this.context.highlightEvent=r?void 0:n}this.set(`activeIndex`,e)}highlightItem(e,t,n){let r=this.context.itemDomElements.current.indexOf(e);r>-1&&this.setActiveIndex(r,t,n)}};function Lb(e){return{positionerRef:Q.createRef(),popupRef:Q.createRef(),typingRef:{current:!1},itemDomElements:{current:[]},itemLabels:{current:[]},highlightReason:`none`,highlightEvent:void 0,reportedItem:void 0,allowMouseUpTriggerRef:{current:!1},virtualFocusRef:void 0,triggerFocusTargetRef:Q.createRef(),beforeTriggerFocusGuardRef:Q.createRef(),beforeContentFocusGuardRef:Q.createRef(),onOpenChangeComplete:void 0,triggerElements:e}}function Rb(e,t,n=!1,r){return{...hr(e,t,n),disabled:!1,modal:!0,openMethod:null,keyboardOpen:!1,allowMouseEnter:!1,highlightItemOnHover:!0,parent:{type:void 0},rootId:void 0,activeIndex:null,listElement:null,filterTriggerProps:we,inputProps:we,inputFocused:!1,highlightedItem:void 0,hoverEnabled:!0,instantType:void 0,openChangeReason:null,floatingTreeRoot:new En,floatingNodeId:void 0,floatingParentNodeId:null,itemProps:we,keyboardEventRelay:void 0,closeDelay:0,adaptiveOrigin:void 0,...r}}var zb=Q.createContext(null);function Bb(e,t){return(e===`trigger-press`||e===`item-press`)&&t?.detail===0}function Vb(e,t){return e===`list-navigation`||Bb(e,t)}var Hb=vn(function(e){let{children:t,open:n,onOpenChange:r,onOpenChangeComplete:i,onItemHighlighted:a,defaultOpen:o=!1,disabled:s=!1,modal:c,loopFocus:l=!0,orientation:u=`vertical`,actionsRef:d,closeParentOnEsc:f=!1,handle:p,triggerId:m,defaultTriggerId:h=null,highlightItemOnHover:g=!0,isSubmenu:_=!1,virtualFocus:v=!1,virtualFocusRef:y,allowEscape:b=!0,resetOnPointerLeave:C=!0}=e,w=r_(!0),T=t_(!0),O=Nb(!0),k=T?.store,j=T?.virtualFocus??!1,M=Q.useMemo(()=>_&&k?{type:`menu`,store:k}:O?{type:`menubar`,context:O}:w&&!k?{type:`context-menu`,context:w}:{type:void 0},[w,k,O,_]),N=D(),ee=D(),[te,ne]=Q.useState(void 0),P=(te??ee)||void 0,F=S(),re=M.type===`menu`?M.store:void 0,I=(n??o)&&re?.state.transitionStatus===`starting`,L=xn(()=>I?re?.state.instantType:void 0).current,R=xn(()=>{let e=new Ib({open:o,openProp:n,activeTriggerId:h,triggerIdProp:m,parent:M,disabled:s,highlightItemOnHover:g,modal:M.type===void 0?c:void 0,rootId:N,instantType:L},P,F!=null);return e.context.virtualFocusRef=y,e}).current;R.useControlledProp(`openProp`,n),R.useControlledProp(`triggerIdProp`,m),R.useContextCallback(`onOpenChangeComplete`,i);let z=R.useState(`floatingTreeRoot`),ie=E(z),ae=R.useState(`open`),oe=R.useState(`activeTriggerElement`),se=R.useState(`positionerElement`),B=R.useState(`hoverEnabled`),ce=R.useState(`disabled`),ue=R.useState(`lastOpenChangeReason`),V=R.useState(`parent`),de=R.useState(`activeIndex`),H=R.useState(`keyboardOpen`),fe=R.useState(`payload`),pe=R.useState(`floatingParentNodeId`),me=Q.useRef(null),he=Q.useRef(V.type!==`context-menu`),ge=ln(),_e=Q.useRef(!0),U=ln(),ve=pe!=null,{openMethod:ye,triggerProps:be}=le(ae);R.useSyncedValues({disabled:s,highlightItemOnHover:g,modal:V.type===void 0?c:void 0,openMethod:ye,rootId:N}),Fn(R);let{forceUnmount:W,transitionStatus:xe}=pn(ae,R,()=>{R.set(`allowMouseEnter`,!1)},I),Se=Tr(R.context.popupRef);Q.useEffect(()=>{if(L===void 0)return;let e=()=>{R.state.instantType===L&&R.set(`instantType`,void 0)};if(!ae){e();return}if(xe!==void 0)return;if(R.context.popupRef.current==null){e();return}let t=new AbortController;return Se(e,t.signal),()=>{t.abort()}},[L,ae,xe,Se,R]),Ae(()=>{w&&!T?R.update({parent:{type:`context-menu`,context:w},floatingNodeId:ie,floatingParentNodeId:F}):(T||!R.select(`activeTriggerElement`))&&R.update({floatingNodeId:ie,floatingParentNodeId:F})},[w,T,ie,F,oe,R]),Q.useEffect(()=>{if(ae||(me.current=null),V.type===`context-menu`){if(!ae){ge.clear(),he.current=!1;return}ge.start(500,()=>{he.current=!0})}},[ge,ae,V.type]),Ae(()=>{!ae&&!B&&R.set(`hoverEnabled`,!0)},[ae,B,R]);let Ce=A((e,t)=>{let n=t.reason;if(!e&&!R.select(`open`)||ae===e&&t.trigger===oe&&ue===n)return;let i=qt(t);if(!e&&t.trigger==null&&(t.trigger=oe??void 0),r?.(e,t),t.isCanceled)return;R.state.floatingRootContext.dispatchOpenChange(e,t);let a=t.event;if(e===!1&&n!==`item-press`&&a?.type===`click`&&a.pointerType===`touch`&&!_e.current)return;e&&n===`trigger-focus`?(_e.current=!1,U.start(300,()=>{_e.current=!0})):(_e.current=!0,U.clear());let o=!e&&(n===`escape-key`||n==null);me.current=t.event;let s=Qn(R.state,e,t.trigger,i());s.openChangeReason=n,s.keyboardOpen=e&&Vb(n,a),s.instantType=V.type===`menubar`&&(n===`trigger-focus`||n===`focus-out`||n===`trigger-hover`||n===`list-navigation`||n===`sibling-open`)?`group`:Bb(n,a)?`click`:o?`dismiss`:void 0,R.update(s)}),Te=Rt({popupStore:R,floatingRootContext:R.state.floatingRootContext,floatingId:P,nested:F!=null,onOpenChange:Ce}),Ee=Te.context.events;Ae(()=>{let e=({open:e,eventDetails:t})=>Ce(e,t);return Ee.on(`setOpen`,e),()=>{Ee?.off(`setOpen`,e)}},[Ee,Ce]),Ae(()=>R.subscribeToParentMenu(),[R]);let De=Q.useCallback(()=>{R.setOpen(!1,Ar(Mt))},[R]);Q.useImperativeHandle(d,()=>({unmount:W,close:De}),[W,De]);let Oe;V.type===`context-menu`&&(Oe=V.context),Q.useImperativeHandle(Oe?.positionerRef,()=>se,[se]),Q.useImperativeHandle(Oe?.actionsRef,()=>({setOpen:Ce}),[Ce]);let ke=Nr(Te,{enabled:!ce,bubbles:{escapeKey:f&&V.type===`menu`},outsidePress(){return V.type!==`context-menu`||me.current?.type===`contextmenu`||he.current},externalTree:ve?z:void 0}),je=rb(),Me=Dv(Te,{enabled:!ce,listRef:R.context.itemDomElements,activeIndex:de,virtual:v,nested:V.type===`menubar`||!v&&V.type!==void 0,parentOrientation:V.type===`menubar`?V.context.orientation:void 0,loopFocus:l,focusItemOnOpen:v?H:void 0,allowEscape:v&&l&&b,orientation:u,triggerOrientation:v?`vertical`:u,rtl:je===`rtl`,disabledIndices:x,onNavigate(e,t){R.setActiveIndex(e,Pb(t),t?.nativeEvent)},openOnArrowKeyDown:V.type!==`context-menu`&&!(v&&_),externalTree:!v&&ve?z:void 0,nestedReturnFocusRef:re?.context.virtualFocusRef,focusItemOnHover:g,resetOnPointerLeave:C}),Ne=Q.useCallback(e=>{R.context.typingRef.current=e},[R]),Pe=Ov(Te,{enabled:!ce&&!v,listRef:R.context.itemLabels,elementsRef:R.context.itemDomElements,activeIndex:de,resetMs:500,onMatch:(e,t)=>{ae&&e!==de&&R.setActiveIndex(e,ur,t.nativeEvent)},onTyping:Ne}),Fe=A(a),Ie=Q.useRef(-1),Le=A(()=>{let e=R.state.activeIndex,t=e===null?void 0:R.context.itemDomElements.current[e]??void 0;if(t?.isConnected===!1)return;let n=t===void 0?-1:e;if(Ie.current===n&&R.context.reportedItem===t)return;Ie.current=n,R.context.reportedItem=t,v&&R.set(`highlightedItem`,t);let{highlightReason:r,highlightEvent:i}=R.context;R.context.highlightReason=kn,R.context.highlightEvent=void 0,a&&Fe(t,Ye(r,i,{label:t===void 0?void 0:R.context.itemLabels.current[n]??void 0}))});Ae(()=>{Le()},[de,Le]);let Re=Q.useMemo(()=>{if(!v)return Me.reference;if(!Me.trigger)return we;let{onFocus:e,...t}=Me.trigger;return t},[v,Me.reference,Me.trigger]);R.useSyncedValue(`inputProps`,v?Me.reference??we:we);let ze=Q.useMemo(()=>{let e=qe(Pe.reference,Re,ke.reference,{onMouseMove(){R.set(`allowMouseEnter`,!0)}},be);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=ae,e},[R,Pe.reference,Re,ke.reference,be,ae]),Be=Q.useMemo(()=>{let e=qe(Me.trigger,ke.trigger,be);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=!1,e},[Me.trigger,ke.trigger,be]);xn(()=>(R.update({inactiveTriggerProps:Be}),null));let Ve=Q.useMemo(()=>qe(Ht,{onMouseMove(){R.set(`allowMouseEnter`,!0),V.type===`menu`&&R.set(`hoverEnabled`,!1)},onClick(){R.select(`hoverEnabled`)&&R.set(`hoverEnabled`,!1)},onKeyDown(e){let t=R.select(`keyboardEventRelay`);t&&!e.isPropagationStopped()&&t(e)}},Pe.floating,Me.floating,ke.floating),[V.type,R,Pe.floating,Me.floating,ke.floating]),He=Me.item??we;cn(R,{floatingRootContext:Te,activeTriggerProps:ze,inactiveTriggerProps:Be,popupProps:Ve,itemProps:He});let Ue=Q.useMemo(()=>({store:R,parent:M,orientation:u,loopFocus:l,allowEscape:b,defaultFloatingId:ee,setRenderedFloatingId:ne,virtualFocus:v,parentVirtualFocus:j,syncHighlightedItem:Le}),[R,M,u,l,b,ee,v,j,Le]),We=typeof t==`function`?t({payload:fe}):t,Ge=(0,$.jsxs)(e_.Provider,{value:Ue,children:[p&&(0,$.jsx)(An,{handle:p,store:R}),We]});return(V.type===void 0||V.type===`context-menu`)&&(Ge=(0,$.jsx)(Je,{externalTree:z,children:Ge})),Ge});function Ub(e){let t=Q.useContext(zb);if(t===null)return(0,$.jsx)(Hb,{...e});let n=t.Root;return(0,$.jsx)(zb.Provider,{value:null,children:(0,$.jsx)(n,{...t.options,...e})})}var Wb=5;function Gb(e,t){let n=Kb(t);return e.clientX>=n.left-Wb&&e.clientX<=n.right+Wb&&e.clientY>=n.top-Wb&&e.clientY<=n.bottom+Wb}function Kb(e){let t=e.getBoundingClientRect(),n=st(e);if(C)return t;let r=n.getComputedStyle(e,`::before`),i=n.getComputedStyle(e,`::after`);if(r.content===`none`&&i.content===`none`)return t;let a=parseFloat(r.width)||0,o=parseFloat(r.height)||0,s=parseFloat(i.width)||0,c=parseFloat(i.height)||0,l=Math.max(t.width,a,s),u=Math.max(t.height,o,c),d=l-t.width,f=u-t.height;return{left:t.left-d/2,right:t.right+d/2,top:t.top-f/2,bottom:t.bottom+f/2}}function qb(e={}){let{highlightItemOnHover:t,highlightedIndex:n,onHighlightedIndexChange:r}=Se(),{ref:i,index:a}=__(e),o=n===a,s=Q.useRef(null),l=c(i,s);return{compositeProps:{tabIndex:o?0:-1,onFocus(){r(a)},onMouseMove(){let e=s.current;if(!t||!e)return;let n=e.hasAttribute(`disabled`)||e.ariaDisabled===`true`;!o&&!n&&e.focus()}},compositeRef:l,index:a}}function Jb(e){let{render:t,className:n,style:r,state:i=we,props:a=x,refs:o=x,metadata:s,stateAttributesMapping:c,tag:l=`div`,...u}=e,{compositeProps:d,compositeRef:f}=qb({metadata:s});return Or(l,e,{state:i,ref:[f,...o],props:[d,...a,u],stateAttributesMapping:c})}function Yb(e){if(nr(e)&&e.hasAttribute(`data-rootownerid`))return e.getAttribute(`data-rootownerid`);if(!ce(e))return Yb($e(e))}function Xb(e,t){function n(n,r,i){let a=n.currentTarget;vv.flushSync(()=>{e.setOpen(!1,Ar(_n,n.nativeEvent,a))}),Hr(a.isConnected?a:t.current,r,i)?.focus()}function r(t){n(t,-1,e.select(`positionerElement`))}function i(t){let r=e.select(`positionerElement`);r&&p(t,r)?e.context.beforeContentFocusGuardRef.current?.focus():n(t,1,r)}return{handlePreFocusGuardFocus:r,handleFocusTargetFocus:i}}function Zb(e){let{enabled:t=!0,mouseDownAction:n,open:r}=e,i=Q.useRef(!1);return Q.useMemo(()=>t?{onMouseDown:e=>{(n===`open`&&!r||n===`close`&&r)&&(i.current=!0,ye(e.currentTarget).addEventListener(`click`,()=>{i.current=!1},{once:!0}))},onClick:e=>{i.current&&(i.current=!1,e.preventBaseUIHandler())}}:we,[t,n,r])}var Qb=Nt(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,id:s,openOnHover:c,delay:l=100,closeDelay:d=0,handle:f,payload:p,...m}=e,h=t_(!0),g=Zt(f)??h?.store;if(!g)throw Error(U(85));let _=D(s),v=g.useState(`isTriggerActive`,_),y=g.useState(`floatingRootContext`),b=g.useState(`isOpenedByTrigger`,_),x=g.useState(`triggerControlsId`,_),C=Q.useRef(null),w=ex(),T=Se(!0),O=Te(),k=Q.useMemo(()=>O??new En,[O]),j=E(k),M=S(),{registerTrigger:N,isMountedByThisTrigger:ee}=Lr(_,C,g,{payload:p,closeDelay:d,parent:w,floatingTreeRoot:k,floatingNodeId:j,floatingParentNodeId:M,keyboardEventRelay:T?.relayKeyboardEvent}),te=w.type===`menubar`,ne=g.useState(`disabled`),P=a||ne||te&&w.context.disabled,{getButtonProps:F,buttonRef:re}=u({disabled:P,native:o});Q.useEffect(()=>{!b&&w.type===void 0&&(g.context.allowMouseUpTriggerRef.current=!1)},[g,b,w.type]);let I=Q.useRef(null),L=ln(),R=A(e=>{if(!I.current)return;L.clear(),g.context.allowMouseUpTriggerRef.current=!1;let t=e.target;jn(I.current,t)||jn(g.select(`positionerElement`),t)||t===I.current||(t==null||Yb(t)!==g.select(`rootId`))&&(Gb(e,I.current)||k.events.emit(`close`,{domEvent:e,reason:Xt}))});Q.useEffect(()=>{let e=ye(I.current);if(b&&g.select(`lastOpenChangeReason`)===`trigger-hover`)return e.addEventListener(`mouseup`,R,{once:!0}),()=>{e.removeEventListener(`mouseup`,R)}},[b,R,g]);let z=te&&w.context.hasSubmenuOpen,ie=bv(y,{enabled:(c??z)&&!P&&(!te||z&&!ee),handleClose:Iv({blockPointerEvents:!te}),mouseOnly:!0,move:!1,restMs:w.type===void 0?l:void 0,delay:{close:d},triggerElementRef:C,externalTree:k,isActiveTrigger:v,isClosing:()=>g.select(`transitionStatus`)===`ending`}),ae=$b(b,g.select(`lastOpenChangeReason`)),oe=Ue(y,{enabled:!P,event:b&&te?`click`:`mousedown`,toggle:!0,ignoreMouse:!1,stickIfOpen:w.type===void 0&&ae}),se=dv(y,{enabled:!P&&z}),B=Zb({open:b,enabled:te,mouseDownAction:`open`}),ce=Q.useMemo(()=>qe(se.reference,oe.reference),[se.reference,oe.reference]),le=g.useState(`triggerProps`,ee),ue=g.useState(`filterTriggerProps`),{handlePreFocusGuardFocus:V,handleFocusTargetFocus:de}=Xb(g,C),H={disabled:P,open:b},fe=[I,t,re,N,C],pe=[ce,ie??we,le,{"aria-haspopup":`menu`,"aria-controls":x,id:_,onMouseDown:e=>{g.select(`open`)||(L.start(200,()=>{g.context.allowMouseUpTriggerRef.current=!0}),ye(e.currentTarget).addEventListener(`mouseup`,R,{once:!0}))}},ue,te?{role:`menuitem`}:{},B,m,F],me=Or(`button`,e,{enabled:!te,stateAttributesMapping:Cr,state:H,ref:fe,props:pe});return te?(0,$.jsx)(Jb,{tag:`button`,render:n,className:r,style:i,state:H,refs:fe,props:pe,stateAttributesMapping:Cr}):b?(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsx)(tr,{ref:g.context.beforeTriggerFocusGuardRef,onFocus:V},`${_}-pre-focus-guard`),(0,$.jsx)(Q.Fragment,{children:me},_),(0,$.jsx)(tr,{ref:g.context.triggerFocusTargetRef,onFocus:de},`${_}-post-focus-guard`)]}):(0,$.jsx)(Q.Fragment,{children:me},_)});function $b(e,t){let n=ln(),[r,i]=Q.useState(!1);return Ae(()=>{e&&t===`trigger-hover`?(i(!0),n.start(500,()=>{i(!1)})):e||(n.clear(),i(!1))},[e,t,n]),r}function ex(){let e=Nb(!0);return Q.useMemo(()=>e?{type:`menubar`,context:e}:{type:void 0},[e])}var tx=Q.forwardRef(function(e,t){let{className:n,render:r,orientation:i=`horizontal`,style:a,...o}=e;return Or(`div`,e,{state:{orientation:i},ref:t,props:[{role:`separator`,"aria-orientation":i},o]})}),nx=(0,Q.createContext)(null);function rx({actionsRef:e,children:t,interactionOwner:n=`local`,onOpenChange:r,...i}){let a=(0,Q.useRef)(null),o=e??a;return ne(()=>o.current?.close()),(0,$.jsx)(nx.Provider,{value:{actionsRef:o,interactionOwner:n},children:(0,$.jsx)(Ub,{...i,actionsRef:o,onOpenChange:(e,t)=>{if(n===`host`&&!e&&t.reason===`escape-key`){t.cancel(),t.allowPropagation();return}r?.(e,t)},children:t})})}function ix(){let e=(0,Q.useContext)(nx);if(!e)throw Error(`DropdownMenu parts must be used inside <DropdownMenu>`);return e}var ax=(0,Q.forwardRef)(function({className:e,render:t,type:n=`button`,...r},i){return(0,$.jsx)(Qb,{...r,className:t=>N(`btn caps-dropdown-trigger`,V(e,t)),ref:i,render:t,type:n})}),ox=(0,Q.forwardRef)(function({container:e,...t},n){let r=fe(`popover`);return e==null&&r===null?null:(0,$.jsx)(eb,{...t,container:e??r,ref:n})}),sx=(0,Q.forwardRef)(function({collisionBoundary:e,...t},n){let r=fe(`popover`);return(0,$.jsx)(jb,{...t,collisionBoundary:e??(r&&r!==document.body?r:void 0),ref:n})}),cx=(0,Q.forwardRef)(function({className:e,finalFocus:t,...n},r){let{interactionOwner:i}=ix(),a=(0,Q.useRef)(null);(0,Q.useImperativeHandle)(r,()=>a.current);let o=rr(`.caps-dropdown-item[data-highlighted]`),s=(0,Q.useCallback)(e=>{a.current=e,o(e)},[o]);return(0,$.jsx)(Zy,{...n,className:t=>N(`caps-dropdown-popup min-w-40 rounded-box border border-base-300 bg-base-100 p-xs shadow-lg outline-none`,V(e,t)),finalFocus:i===`host`?!1:t??!0,ref:s})}),lx=(0,Q.forwardRef)(function({align:e=`end`,alignOffset:t,children:n,container:r,keepMounted:i,side:a=`bottom`,sideOffset:o=4,...s},c){return(0,$.jsx)(ox,{container:r,keepMounted:i,children:(0,$.jsx)(sx,{align:e,alignOffset:t,side:a,sideOffset:o,children:(0,$.jsx)(cx,{...s,ref:c,children:n})})})}),ux=`caps-dropdown-item flex w-full items-center gap-sm rounded-field px-md py-sm text-left text-sm outline-none transition-colors hover:bg-base-200 focus-visible:bg-base-200 aria-[current=page]:bg-base-200 aria-[current=page]:font-semibold disabled:cursor-not-allowed disabled:text-base-content/40 data-disabled:cursor-not-allowed data-disabled:text-base-content/40`,dx=(0,Q.forwardRef)(function({className:e,onClick:t,onSelect:n,variant:r=`default`,...i},a){return(0,$.jsx)(O_,{...i,className:t=>N(ux,r===`destructive`&&`text-error hover:bg-error hover:text-error-content focus-visible:bg-error focus-visible:text-error-content`,V(e,t)),onClick:e=>{t?.(e),e.defaultPrevented||n?.(e)},ref:a})});(0,Q.forwardRef)(function({children:e,className:t,onClick:n,onSelect:r,...i},a){return(0,$.jsxs)(S_,{...i,className:e=>N(ux,V(t,e)),onClick:e=>{n?.(e),e.defaultPrevented||r?.(e)},ref:a,children:[(0,$.jsx)(`span`,{className:`min-w-0 flex-1`,children:e}),(0,$.jsx)(C_,{"aria-hidden":`true`,className:`shrink-0`,children:`✓`})]})}),(0,Q.forwardRef)(function({className:e,...t},n){return(0,$.jsx)(tx,{...t,className:t=>N(`my-xs h-px bg-base-300`,V(e,t)),ref:n})}),(0,Q.forwardRef)(function({className:e,...t},n){return(0,$.jsx)(E_,{...t,className:t=>N(`px-md pb-xs pt-sm text-xs font-semibold text-base-content/60`,V(e,t)),ref:n})});var fx=e=>String(e).padStart(2,`0`),px=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime();function mx(e,t){let n=new Date(e),r=Math.round((px(new Date(t))-px(n))/864e5);return r<=0?`${fx(n.getHours())}:${fx(n.getMinutes())}`:r===1?`Yesterday`:`${String(n.getFullYear())}-${fx(n.getMonth()+1)}-${fx(n.getDate())}`}function hx(e,t){let n=e.replace(/\s+/gu,` `).trim();if(n.length<=t)return n;let r=n.slice(0,Math.max(0,t-1)),i=r.lastIndexOf(` `);return`${(i>t/2?r.slice(0,i):r).trimEnd()}…`}function gx(e,t,n,r){let i=new Map(t.map(e=>[e.providerId,e])),a=new Map(n.map((e,t)=>[e,t])),o=e=>i.has(e)?0:r===`login`&&a.has(e)?1:2,s=e=>r===`model`&&e===`fungi`;return[...new Map(e.map(e=>[e.id,e])).values()].sort((e,t)=>Number(s(t.id))-Number(s(e.id))||o(e.id)-o(t.id)||(o(e.id)<2?(a.get(e.id)??n.length)-(a.get(t.id)??n.length):0)||e.name.localeCompare(t.name)||e.id.localeCompare(t.id)).map(e=>{let t=e.methods.map(e=>e.kind===`api_key`?`API key`:`Subscription`),n=i.get(e.id),r=e.id===`fungi`?`Fungi account`:t.length>0?t.join(` or `):n?.type===`oauth`?`Subscription`:n?.type===`api_key`?`API key`:void 0,a={value:e.id,label:e.name,group:s(e.id)&&!i.has(e.id)?`Default`:o(e.id)===0?`Signed in`:o(e.id)===1?`Popular`:`More providers`};return r===void 0?a:{...a,description:r}})}function _x(e,t){return e.map(e=>({...e,methods:e.methods.filter(n=>t.policy.loginAllowed({providerId:e.id,method:n.kind,host:t.host,scope:t.scope}))})).filter(e=>e.methods.length>0).sort((e,t)=>e.name.localeCompare(t.name)||e.id.localeCompare(t.id))}var vx=Si({providerId:ra().min(1).max(200).optional(),method:_i([`api_key`,`subscription`]).optional(),option:ra().min(1).max(200).optional()});sa(ra(),Ei()).parse(structuredClone(ai(vx)));var yx=Si({providerId:ra().min(1).max(200).optional()});sa(ra(),Ei()).parse(structuredClone(ai(yx)));function bx(e,t){return e.kind===`api_key`?`Paste an API key you created`:`Sign in with your ${t.name} account`}async function xx(e,t,n){if(t!==void 0){let n=e.methods.find(e=>e.kind===t);if(n===void 0)throw new Dr(`method_unavailable`,`${e.name} does not offer that sign-in method here.`);return n}let[r,...i]=e.methods;if(r!==void 0&&i.length===0)return r;let a=await n.prompt({type:`choice`,message:`How do you want to sign in to ${e.name}?`,summary:`You can add the other kind later.`,options:e.methods.map(t=>({value:t.kind,label:t.label,description:bx(t,e)}))}),o=e.methods.find(e=>e.kind===a);if(o===void 0)throw new Dr(`method_unavailable`,`Choose a listed method.`);return o}async function Sx(e,t,n,r={}){let i=await xx(t,r.method,n);n.notify({type:`progress`,message:`Signing in to ${t.name}…`}),await n.run(()=>e.login(r.option===void 0?{providerId:t.id,method:i.kind}:{providerId:t.id,method:i.kind,option:r.option},n))}var Cx=Oo(qa(ma,{onExcessProperty:`error`})).schema;Y.pipe(K(Ba(/^[^/\s]+\/[^\s]+$/u)),K(J(513)));var wx=`default`,Tx=new WeakMap,Ex=256;function Dx(e,t,n){return[...e].sort((e,r)=>{let i=t?.providerId===e.providerId?t:n.get(e.providerId),a=t?.providerId===r.providerId?t:n.get(r.providerId),o=e.id===i?.modelId;return o===(r.id===a?.modelId)?e.providerName.localeCompare(r.providerName):o?-1:1})}async function Ox(e,t,n){if(t.reasoning.length===0)return;let r=await e.prompt({type:`choice`,message:`Thinking level for ${t.name}`,summary:`How long the model thinks before it answers.`,current:n??wx,options:[{value:wx,label:`Model default`},...t.reasoning.map(e=>({value:e,label:e}))]});return t.reasoning.find(e=>e===r)}var kx=255;async function Ax(e,t,n,r,i){if(n===void 0){let n=[...new Map(t.map(e=>[e.providerId,e.providerName]))].slice(0,kx),a=await e.prompt({type:`choice`,message:`Choose a provider`,summary:`Or follow the Agent's own model.`,current:i??wx,options:[{value:wx,label:`Use agent model`},...n.map(([e,t])=>({value:e,label:t}))]});if(a===wx)return null;let o=(await e.run(()=>r(e.signal))).filter(e=>e.providerId===a).slice(0,kx);if(o.length===0)throw new Dr(`model_unavailable`,`That provider has no available models. Retry /model.`);return o}let{owner:a}=n,[o,s]=await Promise.all([a.access(e.signal),a.providers(e.signal).then(e=>_x(e,n))]),c=s.filter(e=>e.id===`fungi`);for(let e of new Map(t.map(e=>[e.providerId,e])).values()){let t=s.find(t=>t.id===e.providerId);c.some(t=>t.id===e.providerId)||(t?c.push(t):o.some(t=>t.providerId===e.providerId&&n.policy.loginAllowed({providerId:t.providerId,method:t.type===`oauth`?`subscription`:`api_key`,host:n.host,scope:n.scope}))&&c.push({id:e.providerId,name:e.providerName,methods:[]}))}let l=await e.prompt({type:`choice`,message:`Choose a provider`,summary:`Or follow the Agent's own model.`,current:i??wx,collapsedGroup:`More providers`,options:[{value:wx,label:`Use agent model`},...gx(c,o,a.popularProviderIds,`model`).slice(0,kx)]});if(l===wx)return null;let u=c.find(e=>e.id===l);if(!u)throw new Dr(`provider_unavailable`,`Choose a listed provider.`);let d=t;o.some(e=>e.providerId===l)||(await Sx(a,u,e),d=await e.run(()=>r(e.signal)));let f=d.filter(e=>e.providerId===l).slice(0,kx);if(f.length===0)throw new Dr(`model_unavailable`,`${u.name} has no available models. Retry /model.`);return f}function jx(e,t){let n=Tx.get(e.modelPreference.read)??new Map;Tx.set(e.modelPreference.read,n);let r=e=>{if(e!==null&&(n.delete(e.providerId),n.set(e.providerId,e),n.size>Ex)){let e=n.keys().next().value;e!==void 0&&n.delete(e)}},i=sa(ra(),Ei()).parse(Cx),a=t.models.map(e=>({title:`${e.providerName} · ${e.name}`,properties:{providerId:{const:e.providerId},modelId:{const:e.id},reasoning:e.reasoning.length!==0&&{enum:[...e.reasoning]}}}));return[{id:`model`,title:`Model`,category:`Settings`,description:`Choose a model`,projections:{agent:{},palette:{},help:{},slash:{aliases:[`model`],consumesDraft:!0}},action:{inputSchema:{anyOf:[{type:`null`,title:`Use agent model`},a.length===0?{not:{}}:{allOf:[i,{oneOf:a}]}]},outputSchema:{anyOf:[{type:`null`},i]}},availability:t.availability??(()=>({status:`available`})),handler:async i=>{if(i.arguments===void 0){let a=i.interaction;if(i.origin===`agent`||a===void 0)return e.modelPreference.read();let o=await e.modelPreference.read();r(o);let s=await Ax(a,t.models,t.account,t.refreshModels,o?.providerId);if(s===null)return await a.run(()=>e.modelPreference.set(null)),a.run(()=>e.modelPreference.read());let c=Dx(s,o,n),l=c.findIndex(e=>e.providerId===o?.providerId&&e.id===o.modelId),u=await a.prompt({type:`choice`,message:`Choose a model`,summary:`Models from ${c[0]?.providerName??`this provider`}.`,current:l<0?void 0:String(l),options:c.map((e,t)=>({value:String(t),label:e.name}))}),d=c[Number(u)];if(d===void 0)throw new Dr(`model_unavailable`,`Choose a listed model.`);let f=await Ox(a,d,(o?.providerId===d.providerId?o:n.get(d.providerId))?.reasoning),p=f===void 0?{providerId:d.providerId,modelId:d.id}:{providerId:d.providerId,modelId:d.id,reasoning:f};return await a.run(()=>e.modelPreference.set(p)),r(p),a.run(()=>e.modelPreference.read())}let a;try{a=yo(i.arguments)}catch{throw new Dr(`invalid_model_preference`,`Model preference arguments are invalid`)}if(a!==null){let e=a,n=(t.account===void 0?await t.refreshModels(i.signal??new AbortController().signal):t.models).find(t=>t.providerId===e.providerId&&t.id===e.modelId);if(n===void 0)throw new Dr(`model_unavailable`,`That model is not in the current catalog`);if(e.reasoning!==void 0&&!n.reasoning.includes(e.reasoning))throw new Dr(`reasoning_unavailable`,`That thinking level is not supported by this model`)}return await e.modelPreference.set(a),r(a),e.modelPreference.read()}},{id:`thinking`,title:`Thinking level`,category:`Settings`,description:`Choose thinking effort`,projections:{palette:{order:1},help:{},slash:{aliases:[`thinking`],consumesDraft:!0}},availability:t.availability??(()=>({status:`available`})),handler:async n=>{let r=n.interaction;if(r===void 0)throw new Dr(`interaction_required`,`Choosing a thinking level needs a person.`);let i=await e.modelPreference.read(),a=t.models.find(e=>e.providerId===i?.providerId&&e.id===i.modelId);if(i===null||a===void 0)throw new Dr(`model_required`,`Choose a model with /model before its thinking level.`);if(a.reasoning.length===0)throw new Dr(`reasoning_unavailable`,`${a.name} has no thinking levels.`);let o=await Ox(r,a,i.reasoning),s=o===void 0?{providerId:a.providerId,modelId:a.id}:{providerId:a.providerId,modelId:a.id,reasoning:o};return await r.run(()=>e.modelPreference.set(s)),r.run(()=>e.modelPreference.read())}}]}var Mx=(e,t)=>Math.min(t.baseMs===0?0:t.baseMs*2**Math.max(0,e-1),t.maxMs),Nx=Xo.check(Yo(0),bo(2**53-1)),Px=G({baseMs:Nx,maxMs:Nx,limit:q([G({maxAttempts:Nx}),G({deadlineAt:Nx})])}),Fx=oo(Px);function Ix(e,t,n){return Math.min(t+Mx(e,n),`deadlineAt`in n.limit?n.limit.deadlineAt:2**53-1)}function Lx(e,t,n){let r=`maxAttempts`in n.limit?e>=n.limit.maxAttempts:t>=n.limit.deadlineAt,i=r?e:e+1;return{attempt:{count:i,status:r?`exhausted`:`admitted`,final:r||`maxAttempts`in n.limit&&i>=n.limit.maxAttempts},notBefore:Ix(i,t,n)}}var Rx=class extends Error{_tag=`WatchdogError`;cause;underlying;constructor(e,t){super(`Watchdog ${e.replaceAll(`_`,` `)}`),this.name=this._tag,this.cause=e,this.underlying=t}},zx=Eo({family:`watchdog`,version:1,kinds:{claim:{prefix:`watchdog_claim`}}});function Bx(e){if(Ga(e))return`execution_interrupted`;let t=Sa(e);return t._tag===`Some`?t.value.cause:`execution_defect`}var Vx=(e,t)=>{let n=`idle`,r,i=`open`,a,o,s=Wi(()=>{if(o!==void 0)return Oa(o);let e=ya();o=e,i=`stopping`;let t=a;return r?.fiber.interruptUnsafe(),(t===void 0?qi(void 0):Oa(t)).pipe(ti(t=>(i=`stopped`,ja(e,Va(t,()=>void 0)))),si)}),c=t=>(e.executor.retryPolicy?.(t)??qi(void 0)).pipe(oa(e=>e===void 0?qi(void 0):aa({try:()=>Fx(e),catch:e=>new Rx(`store_invalid`,e)}))),l=e=>t.ingest(e),u=e=>t.read(e).pipe($r(e=>e.status===`missing`?e:{status:`found`,job:e.job,cancellation:e.cancellation})),d=e=>t.readQueueHead(e),f=(e,n,r)=>t.readSettled(e,n,r),p=n=>t.recordCancellation(n).pipe(Mi(t=>{if(t.status!==`recorded`&&t.status!==`replayed`)return na;let i=r;return i?.jobId===n.jobId?Pi(()=>{i.fiber.interruptUnsafe()}):e.wake.recompute()})),m=n=>t.failLane(n).pipe(Mi(t=>{let n=r,i=t.jobs.find(e=>e.jobId===n?.jobId);return n!==void 0&&i!==void 0&&(n.failed=i,n.fiber.interruptUnsafe()),t.jobs.length===0?na:e.wake.recompute()}),$r(({jobs:e,more:t})=>({settled:e.length,more:t}))),h=e=>t.purgeQueued(e),g=()=>aa({try:()=>zx.claim.generate(),catch:()=>new Rx(`claim_unavailable`)}).pipe(oa(e=>t.selectAndClaim(e))),_=()=>Ri(function*(){let n=yield*t.nextRunningClaim();if(n===void 0)return{status:`none`};let r=yield*ea(e.isAlive(n.job));if(r._tag===`Failure`)return{status:`liveness_unknown`,jobId:n.job.jobId,reason:r.failure.cause};if(r.success)return{status:`none`};let i=yield*c(n.job),a=yield*t.reconcileDisappearedClaim({...n,requeue:i!==void 0||e.executor.replaySafe?.(n.job)===!0});switch(a.status){case`requeued`:return yield*e.wake.recompute(),{status:`none`};case`settled`:return yield*e.wake.recompute(),{status:`recovered`,job:a.job};case`conflict`:case`missing`:{let e=yield*t.read(n.job.jobId);return e.status===`found`&&(e.job.state!==`running`||e.claimToken!==n.claimToken||e.recoveryCount!==n.recoveryCount)?{status:`none`}:yield*ki(new Rx(`settlement_rejected`))}}}),v=n=>t.finishCompletingClaim(n).pipe(oa(t=>t.status===`settled`||t.status===`replayed`?e.wake.recompute().pipe(Zi({status:`settled`,job:t.job})):ki(new Rx(`settlement_rejected`))));return Object.freeze({close:s,wakeState:t.wakeState,ingest:l,read:u,readQueueHead:d,readSettled:f,tick:()=>Wi(()=>{if(i!==`open`)return qi({status:`stopped`});if(n!==`idle`)return qi({status:`busy`});n=`running`;let o=ya();return a=o,Ri(function*(){let n=yield*t.nextCompletingClaim();return n===void 0?yield*_().pipe(oa(e=>e.status===`recovered`?qi({status:`recovered`,job:e.job}):g().pipe($r(t=>t.status===`no_ready`&&e.status===`liveness_unknown`?e:t))),oa(n=>n.status===`no_ready`?qi({status:`no_ready`}):n.status===`liveness_unknown`?qi(n):n.status===`claim_unavailable`?ki(new Rx(`claim_unavailable`)):n.status===`cancelled`?e.wake.recompute().pipe(Zi({status:`settled`,job:n.job})):n.status===`recovered`?qi({status:`settled`,job:n.job}):Ri(function*(){let a=yield*c(n.job),o=e.executor.replaySafe?.(n.job)===!0,s=yield*Ma(),l={started:!1},u=yield*qr(Oa(s).pipe(bi(Pi(()=>{l.started=!0})),bi(a===void 0?qi(void 0):t.reserveAttempt({jobId:n.job.jobId,claimToken:n.claimToken,policy:a})),oa(t=>e.executor.execute(n.job,t)))),d={jobId:n.job.jobId,fiber:u};r=d;let f=yield*t.read(n.job.jobId);i!==`open`||f.status!==`found`||f.job.state!==`running`||f.cancellation.status===`present`?(f.status===`found`&&f.job.state===`settled`&&f.job.outcome===`failed`&&(d.failed=f.job),yield*Vo(u)):yield*xa(s,void 0);let p=yield*so(u).pipe(Hi(Pi(()=>{r?.fiber===u&&(r=void 0)})));if(d.failed!==void 0)return yield*e.wake.recompute().pipe(Zi({status:`settled`,job:d.failed}));if(i!==`open`&&Qo(p)){if(!(Ga(p.cause)&&(!l.started||(yield*e.executor.isDrained?.(n.job)??qi(!1)))))return yield*ki(new Rx(`drain_failed`));let r=yield*t.handoffExactClaim({jobId:n.job.jobId,claimToken:n.claimToken});if(r.status===`requeued`)return yield*e.wake.recompute().pipe(Zi({status:`stopped`}));if(r.status!==`cancelled`)return yield*ki(new Rx(`settlement_rejected`))}let m=ga(p)?p.value:{kind:`failed`,reason:Bx(p.cause)};if(a!==void 0&&(m.kind===`retry`||Qo(p))||o&&Qo(p)){let r={jobId:n.job.jobId,claimToken:n.claimToken};a!==void 0&&Object.assign(r,{policy:a});let i=yield*t.retryExactClaim(r);if(i.status===`requeued`&&o&&Qo(p))return yield*vi(p.cause);if(i.status===`requeued`)return yield*e.wake.recompute().pipe(Zi({status:`requeued`,jobId:n.job.jobId}));if(i.status===`conflict`)return yield*ki(new Rx(`settlement_rejected`))}switch((yield*t.recordExecutionDecision({jobId:n.job.jobId,claimToken:n.claimToken,decision:m.kind===`retry`?{kind:`failed`,reason:`retry_policy_missing`}:m})).status){case`recorded`:case`replayed`:return yield*v({jobId:n.job.jobId,claimToken:n.claimToken});case`conflict`:case`missing`:return yield*ki(new Rx(`settlement_rejected`))}}))):yield*v({jobId:n.job.jobId,claimToken:n.claimToken})}).pipe(ti(e=>(n=`idle`,a=void 0,ja(o,Va(e,()=>void 0)))))}),cancel:p,failLane:m,purge:h})};function Hx(e,t,n,r){if(e===void 0)return{kind:`interrupted`};let i=e.windowMs!==void 0&&n!==null&&r-n>=e.windowMs,a=i?0:t;return a>=e.maxRecoveries?{kind:`interrupted`}:{kind:`requeue`,recoveryCount:a+1,windowStartedAt:e.windowMs===void 0?null:i||n===null?r:n}}var Ux=Y.check(Ta(1),J(512)),Wx=Y.check(Ta(1),J(256)),Gx=Xo.check(Yo(-(2**53-1)),bo(2**53-1)),Kx=Xo.check(Yo(0),bo(2**53-1)),qx=Y.check(Ta(1),J(200)),Jx=G({lane:Ux,reason:qx});function Yx(e){try{return oo(Jx,{onExcessProperty:`error`})(e)}catch(e){throw new Rx(`store_invalid`,e)}}var Xx=G({sequence:Xo,job_id:Wx,queue_name:Wx,lane:Ux,priority:Gx,payload_json:Y,not_before:Kx,attempt_count:Kx,recovery_max:vo(Kx),recovery_window_ms:vo(Kx),recovery_window_started_at:vo(Kx),state:Ra([`queued`,`running`,`completing`,`settled`]),outcome:vo(Ra([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`])),claim_token:vo(Wx),recovery_count:Kx,cancellation_id:vo(Wx),failure_reason:vo(qx)}),Zx=ko(za),Qx=Ja(Xx,{onExcessProperty:`error`}),$x=Ja(Zx),eS=ho(Zx);function tS(e){return e===void 0?{predicate:`1 = 1`,values:[]}:{predicate:e.include?`lane = ?`:`lane <> ?`,values:[e.lane]}}var nS=`sequence, job_id, queue_name, lane, priority, payload_json, not_before, attempt_count,
|
|
25
|
-
recovery_max, recovery_window_ms, recovery_window_started_at, state, outcome, claim_token, recovery_count,
|
|
26
|
-
cancellation_id, failure_reason`,rS=`(cancellation_id IS NOT NULL OR NOT EXISTS (
|
|
27
|
-
SELECT 1 FROM watchdog_jobs predecessor
|
|
28
|
-
WHERE predecessor.queue_name = watchdog_jobs.queue_name
|
|
29
|
-
AND predecessor.state IN ('queued', 'running', 'completing')
|
|
30
|
-
AND (predecessor.state IN ('running', 'completing') OR
|
|
31
|
-
(predecessor.state = 'queued' AND
|
|
32
|
-
(predecessor.priority > watchdog_jobs.priority OR
|
|
33
|
-
(predecessor.priority = watchdog_jobs.priority AND
|
|
34
|
-
predecessor.sequence < watchdog_jobs.sequence))))))`,iS=G({pending:Ra([0,1]),next_wake_at:vo(Kx)}),aS=oo(Kx);function oS(e){let t=oo(iS)(e);return{pending:t.pending===1,nextWakeAt:t.next_wake_at}}function sS(e,t){return aS(t),oS(e.sql.exec(`SELECT
|
|
35
|
-
COALESCE(MAX(CASE WHEN state IN ('running','completing') OR cancellation_id IS NOT NULL OR not_before <= ? THEN 1 ELSE 0 END),0) AS pending,
|
|
36
|
-
MIN(CASE WHEN state='queued' AND cancellation_id IS NULL AND not_before > ? THEN not_before END) AS next_wake_at
|
|
37
|
-
FROM watchdog_jobs WHERE state IN ('running','completing') OR (state='queued' AND ${rS})`,t,t).toArray()[0])}function cS(e){return new Rx(`store_unavailable`,e)}function lS(e){return aa({try:e,catch:e=>e instanceof Rx?e:cS(e)})}function uS(e){let t=eS(e);if(t._tag===`Failure`)throw cS(Pa(t.cause));return t.value}function dS(e){let t=Qx(e);if(t._tag===`Failure`)throw cS(Pa(t.cause));let n=t.value,r=$x(n.payload_json);if(r._tag===`Failure`)throw cS(Pa(r.cause));let i={jobId:n.job_id,queue:n.queue_name,lane:n.lane,priority:n.priority,payload:r.value};if(n.not_before!==0&&(i={...i,notBefore:n.not_before}),n.recovery_max!==null){let e=n.recovery_window_ms===null?{maxRecoveries:n.recovery_max}:{maxRecoveries:n.recovery_max,windowMs:n.recovery_window_ms};i={...i,recovery:e}}if(n.state===`queued`)return{row:n,job:{...i,state:`queued`}};if(n.state===`running`){if(n.claim_token===null)throw cS();return{row:n,job:{...i,state:`running`}}}if(n.outcome===null)throw cS();let a={...i,state:n.state,outcome:n.outcome};return{row:n,job:(n.outcome===`failed`||n.outcome===`interrupted`)&&n.failure_reason!==null?{...a,failureReason:n.failure_reason}:a}}function fS(e,t){let n=e.sql.exec(`SELECT ${nS}
|
|
38
|
-
FROM watchdog_jobs
|
|
39
|
-
WHERE job_id = ?`,t).toArray()[0];return n===void 0?void 0:dS(n)}function pS(e,t,n,r,i){let a=tS(r),o=i===void 0?a:{predicate:`${a.predicate} AND lane = ?`,values:[...a.values,oo(Ux)(i)]};return e.sql.exec(`SELECT ${nS} FROM watchdog_jobs NOT INDEXED WHERE state = 'settled' AND ${o.predicate} AND sequence > ?
|
|
40
|
-
AND sequence < COALESCE(
|
|
41
|
-
(SELECT MIN(sequence) FROM watchdog_jobs INDEXED BY idx_watchdog_ready
|
|
42
|
-
WHERE state IN ('queued', 'running', 'completing') AND ${o.predicate}),
|
|
43
|
-
9223372036854775807)
|
|
44
|
-
ORDER BY sequence ASC LIMIT ?`,...o.values,n??0,...o.values,t).toArray().map(e=>{let t=dS(e);if(t.job.state!==`settled`)throw cS();return{sequence:t.row.sequence,job:t.job}})}function mS(e,t){let n=e.sql.exec(`SELECT ${nS}
|
|
45
|
-
FROM watchdog_jobs
|
|
46
|
-
WHERE queue_name = ? AND state IN ('running', 'completing', 'queued')
|
|
47
|
-
ORDER BY CASE state WHEN 'queued' THEN 1 ELSE 0 END,
|
|
48
|
-
priority DESC, sequence ASC
|
|
49
|
-
LIMIT 1`,t).toArray()[0];if(n===void 0)return{state:`idle`};let r=dS(n);if(r.job.state===`settled`)throw cS();return{state:r.job.state===`completing`?`running`:r.job.state,jobId:r.job.jobId,cancellationRequested:r.row.cancellation_id!==null}}function hS(e,t){let n=e.sql.exec(`SELECT ${nS}
|
|
50
|
-
FROM watchdog_jobs
|
|
51
|
-
WHERE queue_name = ? AND state = 'settled'
|
|
52
|
-
ORDER BY sequence DESC
|
|
53
|
-
LIMIT 1`,t).toArray()[0];if(n===void 0)return;let r=dS(n);if(r.job.state!==`settled`)throw cS();return r.job}function gS(e,t,n,r){if(t===void 0)return;let i=mS(e,n);t(r===void 0?{queue:n,head:i}:{queue:n,head:i,settled:r})}function _S(e){e.transactionSync(()=>{if(e.sql.exec(`
|
|
54
|
-
CREATE TABLE IF NOT EXISTS watchdog_jobs (
|
|
55
|
-
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
56
|
-
job_id TEXT UNIQUE NOT NULL,
|
|
57
|
-
queue_name TEXT NOT NULL,
|
|
58
|
-
lane TEXT NOT NULL,
|
|
59
|
-
priority INTEGER NOT NULL,
|
|
60
|
-
payload_json TEXT NOT NULL,
|
|
61
|
-
not_before INTEGER NOT NULL DEFAULT 0 CHECK (not_before >= 0),
|
|
62
|
-
attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
|
|
63
|
-
recovery_max INTEGER,
|
|
64
|
-
recovery_window_ms INTEGER CHECK (recovery_window_ms IS NULL OR recovery_window_ms > 0),
|
|
65
|
-
recovery_window_started_at INTEGER,
|
|
66
|
-
state TEXT NOT NULL CHECK (state IN ('queued', 'running', 'completing', 'settled')),
|
|
67
|
-
outcome TEXT CHECK (
|
|
68
|
-
outcome IS NULL OR outcome IN (
|
|
69
|
-
'completed', 'failed', 'cancelled', 'outcome_unknown', 'interrupted'
|
|
70
|
-
)
|
|
71
|
-
),
|
|
72
|
-
claim_token TEXT,
|
|
73
|
-
recovery_count INTEGER NOT NULL DEFAULT 0,
|
|
74
|
-
cancellation_id TEXT UNIQUE,
|
|
75
|
-
failure_reason TEXT,
|
|
76
|
-
CHECK (recovery_max IS NULL OR recovery_max >= 0),
|
|
77
|
-
CONSTRAINT watchdog_execution_state CHECK (
|
|
78
|
-
(state = 'queued' AND outcome IS NULL AND claim_token IS NULL) OR
|
|
79
|
-
(state = 'running' AND outcome IS NULL AND claim_token IS NOT NULL) OR
|
|
80
|
-
(state = 'completing' AND outcome IS NOT NULL AND claim_token IS NOT NULL) OR
|
|
81
|
-
(state = 'settled' AND outcome IS NOT NULL)
|
|
82
|
-
)
|
|
83
|
-
)
|
|
84
|
-
`),e.sql.exec(`SELECT 1 AS current FROM sqlite_schema WHERE name = 'watchdog_jobs' AND instr(sql, 'watchdog_execution_state') > 0`).toArray().length!==1)throw new Rx(`store_invalid`,Error(`Obsolete Watchdog execution schema`));try{e.sql.exec(`SELECT ${nS} FROM watchdog_jobs LIMIT 0`)}catch(e){throw new Rx(`store_invalid`,e)}e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_watchdog_lane_failure
|
|
85
|
-
ON watchdog_jobs(lane, state DESC, sequence ASC)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_watchdog_ready
|
|
86
|
-
ON watchdog_jobs(state, not_before, priority DESC, sequence ASC)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_watchdog_queue_head
|
|
87
|
-
ON watchdog_jobs(queue_name, state, priority DESC, sequence ASC)`)})}function vS(e,t,n){let r=uS(n.payload),i=fS(e,n.jobId);if(i!==void 0){let e=i.job.recovery?.maxRecoveries,t=n.recovery?.maxRecoveries;if(i.job.queue!==n.queue||i.job.lane!==n.lane||i.job.priority!==n.priority||i.row.payload_json!==r||e!==t||i.job.recovery?.windowMs!==n.recovery?.windowMs)throw cS();return!1}return e.sql.exec(`INSERT INTO watchdog_jobs
|
|
88
|
-
(job_id, queue_name, lane, priority, payload_json, recovery_max, recovery_window_ms, not_before,
|
|
89
|
-
state, outcome, claim_token, recovery_count, cancellation_id)
|
|
90
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL, NULL, 0, NULL)`,n.jobId,n.queue,n.lane,n.priority,r,n.recovery?.maxRecoveries??null,n.recovery?.windowMs??null,n.notBefore??0),gS(e,t,n.queue),!0}function yS(e,t,n){let r=fS(e,n.jobId);return r===void 0?{status:`missing`}:r.job.state===`completing`||r.job.state===`settled`?{status:`decided`,outcome:r.job.outcome}:r.row.cancellation_id===null?n.onlyIfQueued===!0&&r.job.state!==`queued`?{status:`conflict`}:(e.sql.exec(`UPDATE watchdog_jobs
|
|
91
|
-
SET cancellation_id = ?
|
|
92
|
-
WHERE job_id = ? AND cancellation_id IS NULL`,n.cancellationId,n.jobId),gS(e,t,r.job.queue),{status:`recorded`,intent:n}):r.row.cancellation_id===n.cancellationId?{status:`replayed`,intent:n}:{status:`conflict`}}function bS(e,t,n,r){let i=tS(r);return e.transactionSync(()=>{let r=e.sql.exec(`SELECT ${nS}
|
|
93
|
-
FROM watchdog_jobs
|
|
94
|
-
WHERE state = 'queued' AND ${i.predicate}
|
|
95
|
-
AND (cancellation_id IS NOT NULL OR not_before <= ?)
|
|
96
|
-
AND ${rS}
|
|
97
|
-
ORDER BY priority DESC, sequence ASC
|
|
98
|
-
LIMIT 1`,...i.values,Date.now()).toArray()[0];if(r===void 0)return{status:`no_ready`};let a=dS(r);if(a.job.state!==`queued`)return{status:`claim_unavailable`};if(a.row.cancellation_id!==null){e.sql.exec(`UPDATE watchdog_jobs
|
|
99
|
-
SET state = 'settled', outcome = 'cancelled'
|
|
100
|
-
WHERE job_id = ? AND state = 'queued' AND cancellation_id = ?`,a.job.jobId,a.row.cancellation_id);let n=fS(e,a.job.jobId)?.job;return n?.state!==`settled`||n.outcome!==`cancelled`?{status:`claim_unavailable`}:(gS(e,t,n.queue,n),{status:`cancelled`,job:n})}e.sql.exec(`UPDATE watchdog_jobs
|
|
101
|
-
SET state = 'running', claim_token = ?
|
|
102
|
-
WHERE job_id = ? AND state = 'queued'`,n,a.job.jobId);let o=fS(e,a.job.jobId)?.job;return o?.state===`running`?(gS(e,t,o.queue),{status:`claimed`,job:o,claimToken:n}):{status:`claim_unavailable`}})}function xS(e,t){return e.transactionSync(()=>{let n=fS(e,t.jobId);if(n===void 0)return{status:`missing`};let r=n.row.cancellation_id===null?t.decision.kind:`cancelled`;if(n.job.state===`completing`||n.job.state===`settled`)return n.row.claim_token===t.claimToken&&n.job.outcome===r?{status:`replayed`,job:n.job}:{status:`conflict`};if(n.job.state!==`running`||n.row.claim_token!==t.claimToken)return{status:`conflict`};e.sql.exec(`UPDATE watchdog_jobs SET state = 'completing', outcome = ?, failure_reason = ?
|
|
103
|
-
WHERE job_id = ? AND state = 'running' AND claim_token = ?`,r,r===`failed`&&t.decision.kind===`failed`?t.decision.reason??null:null,t.jobId,t.claimToken);let i=fS(e,t.jobId)?.job;return i?.state===`completing`?{status:`recorded`,job:i}:{status:`conflict`}})}function SS(e,t,n){return e.transactionSync(()=>{let r=fS(e,n.jobId);if(r===void 0)return{status:`missing`};if(r.row.claim_token!==n.claimToken)return{status:`conflict`};if(r.job.state===`settled`)return{status:`replayed`,job:r.job};if(r.job.state!==`completing`)return{status:`conflict`};e.sql.exec(`UPDATE watchdog_jobs SET state = 'settled' WHERE job_id = ? AND state = 'completing' AND claim_token = ?`,n.jobId,n.claimToken);let i=fS(e,n.jobId)?.job;return i?.state===`settled`?(gS(e,t,i.queue,i),{status:`settled`,job:i}):{status:`conflict`}})}function CS(e,t,n){_S(e);let r=Object.freeze({wakeState:t=>sS(e,t),readJob:t=>{let n=fS(e,t);return n===void 0?void 0:{state:n.row.state,notBefore:n.row.not_before}},expediteQueuedJob:(t,n)=>(aS(n),e.sql.exec(`UPDATE watchdog_jobs SET not_before=? WHERE job_id=? AND state='queued' AND not_before>? RETURNING job_id`,n,t,n).toArray().length===1),readQueueHead:t=>mS(e,t),readLatestSettledJob:t=>hS(e,t),enqueueAcceptedJob:n=>{vS(e,t,n)},recordCancellationIntent:n=>yS(e,t,n)}),i=n=>{let r=tS(n);return Object.freeze({wakeState:t=>lS(()=>sS(e,t)),ingest:n=>lS(()=>e.transactionSync(()=>({status:vS(e,t,n)?`queued`:`duplicate`}))),read:t=>lS(()=>{let n=fS(e,t);return n===void 0?{status:`missing`}:{status:`found`,job:n.job,claimToken:n.row.claim_token,recoveryCount:n.row.recovery_count,cancellation:n.row.cancellation_id===null?{status:`absent`}:{status:`present`,cancellation:{jobId:t,cancellationId:n.row.cancellation_id}}}}),readQueueHead:t=>lS(()=>mS(e,t)),readSettled:(t,r,i)=>lS(()=>pS(e,t,r,n,i)),selectAndClaim:r=>lS(()=>bS(e,t,r,n)),reserveAttempt:t=>lS(()=>e.transactionSync(()=>{let n=fS(e,t.jobId);if(n?.job.state!==`running`||n.row.claim_token!==t.claimToken||n.row.cancellation_id!==null)throw new Rx(`claim_unavailable`);let r=Lx(n.row.attempt_count,Date.now(),t.policy);return e.sql.exec(`UPDATE watchdog_jobs SET attempt_count=?, not_before=? WHERE job_id=? AND state='running' AND claim_token=?`,r.attempt.count,r.notBefore,t.jobId,t.claimToken),r.attempt})),retryExactClaim:n=>lS(()=>e.transactionSync(()=>{let r=fS(e,n.jobId);if(r?.job.state!==`running`||r.row.claim_token!==n.claimToken)return{status:`conflict`};if(r.row.cancellation_id!==null)return{status:`cancelled`};let i=n.policy===void 0?r.row.not_before:Ix(r.row.attempt_count,Date.now(),n.policy);return e.sql.exec(`UPDATE watchdog_jobs SET state='queued', claim_token=NULL, not_before=? WHERE job_id=? AND state='running' AND claim_token=?`,i,n.jobId,n.claimToken),gS(e,t,r.job.queue),{status:`requeued`}})),recordExecutionDecision:t=>lS(()=>xS(e,t)),nextCompletingClaim:()=>lS(()=>{let t=e.sql.exec(`SELECT ${nS} FROM watchdog_jobs WHERE state = 'completing' AND ${r.predicate} ORDER BY sequence LIMIT 1`,...r.values).toArray()[0];if(t===void 0)return;let n=dS(t);if(n.job.state!==`completing`||n.row.claim_token===null)throw cS();return{job:n.job,claimToken:n.row.claim_token}}),finishCompletingClaim:n=>lS(()=>SS(e,t,n)),recordCancellation:n=>lS(()=>e.transactionSync(()=>{let r=yS(e,t,n);return r.status===`decided`?r:{status:r.status}})),failLane:n=>lS(()=>{let r=Yx(n);return e.transactionSync(()=>{let n=e.sql.exec(`SELECT ${nS} FROM watchdog_jobs
|
|
104
|
-
WHERE lane = ? AND state IN ('queued', 'running', 'completing')
|
|
105
|
-
ORDER BY state DESC, sequence ASC LIMIT ?`,r.lane,256).toArray(),i=[];for(let a of n){let n=dS(a);e.sql.exec(`UPDATE watchdog_jobs SET state = 'settled', outcome = 'failed', failure_reason = ?, claim_token = NULL
|
|
106
|
-
WHERE job_id = ? AND state IN ('queued', 'running', 'completing')`,r.reason,n.job.jobId);let o=fS(e,n.job.jobId)?.job;if(o?.state!==`settled`||o.outcome!==`failed`)throw cS();gS(e,t,o.queue,o),i.push(o)}return{jobs:i,more:e.sql.exec(`SELECT 1 FROM watchdog_jobs WHERE lane = ? AND state IN ('queued', 'running', 'completing') LIMIT 1`,r.lane).toArray().length!==0}})}),purgeQueued:n=>lS(()=>{e.transactionSync(()=>{e.sql.exec(`DELETE FROM watchdog_jobs
|
|
107
|
-
WHERE queue_name = ? AND state = 'queued'`,n),gS(e,t,n)})}),handoffExactClaim:n=>lS(()=>e.transactionSync(()=>{let r=fS(e,n.jobId);return r===void 0?{status:`missing`}:r.job.state!==`running`||r.row.claim_token!==n.claimToken?{status:`conflict`}:r.row.cancellation_id===null?(e.sql.exec(`UPDATE watchdog_jobs SET state = 'queued', claim_token = NULL WHERE job_id = ? AND state = 'running' AND claim_token = ?`,n.jobId,n.claimToken),gS(e,t,r.job.queue),{status:`requeued`}):{status:`cancelled`}})),nextRunningClaim:()=>lS(()=>{let t=e.sql.exec(`SELECT ${nS}
|
|
108
|
-
FROM watchdog_jobs
|
|
109
|
-
WHERE state = 'running' AND ${r.predicate}
|
|
110
|
-
ORDER BY sequence ASC
|
|
111
|
-
LIMIT 1`,...r.values).toArray()[0];if(t===void 0)return;let n=dS(t);if(n.job.state!==`running`||n.row.claim_token===null)throw cS();return{job:n.job,claimToken:n.row.claim_token,recoveryCount:n.row.recovery_count}}),reconcileDisappearedClaim:n=>lS(()=>e.transactionSync(()=>{let r=fS(e,n.job.jobId);if(r===void 0)return{status:`missing`};if(r.job.state!==`running`||r.row.claim_token!==n.claimToken||r.row.recovery_count!==n.recoveryCount)return{status:`conflict`};let i=n.requeue?{kind:`requeue`,recoveryCount:r.row.recovery_count,windowStartedAt:r.row.recovery_window_started_at}:Hx(r.job.recovery,r.row.recovery_count,r.row.recovery_window_started_at,Date.now());if(i.kind===`requeue`&&r.row.cancellation_id===null)return e.sql.exec(`UPDATE watchdog_jobs
|
|
112
|
-
SET state = 'queued', claim_token = NULL,
|
|
113
|
-
recovery_count = ?, recovery_window_started_at = ?
|
|
114
|
-
WHERE job_id = ? AND state = 'running' AND claim_token = ?`,i.recoveryCount,i.windowStartedAt,n.job.jobId,n.claimToken),gS(e,t,n.job.queue),{status:`requeued`};let a=r.row.cancellation_id!==null,o=a?null:r.job.recovery===void 0?`Execution disappeared without a recovery policy`:`Restart recovery budget exhausted (${String(r.job.recovery.maxRecoveries)} recoveries)`;e.sql.exec(`UPDATE watchdog_jobs
|
|
115
|
-
SET state = 'settled', outcome = ?, failure_reason = ?
|
|
116
|
-
WHERE job_id = ? AND state = 'running' AND claim_token = ?`,a?`cancelled`:`interrupted`,o,n.job.jobId,n.claimToken);let s=fS(e,n.job.jobId)?.job;return s?.state===`settled`?(gS(e,t,s.queue,s),{status:`settled`,job:s}):{status:`conflict`}}))})};return Object.freeze({store:i(n),partition:i,transactional:r})}var wS=Y.check(Ta(1),J(256)),TS=Y.check(Ta(1),J(200)),ES=Xo.check(Yo(-(2**53-1)),bo(2**53-1)),DS=Xo.check(Yo(0),bo(2**53-1)),OS=G({maxRecoveries:DS,windowMs:Ca(Xo.check(Go(0),bo(2**53-1)))}),kS={jobId:wS,queue:wS,lane:Ux,priority:ES,payload:za,notBefore:Ca(DS),recovery:ba(OS)},AS=G({...kS,state:X(`queued`)}),jS=Ra([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`]),MS={...kS,outcome:jS,failureReason:Ca(TS)},NS=G({...MS,state:X(`completing`)}),PS=G({...MS,state:X(`settled`)}),FS=G({...kS,state:X(`running`)}),IS=q([AS,FS,NS,PS]);q([G({kind:X(`retry`)}),G({kind:X(`completed`)}),G({kind:X(`failed`),reason:Ca(TS)}),G({kind:X(`cancelled`)}),G({kind:X(`outcome_unknown`)})]);var LS=G({jobId:wS,cancellationId:wS,onlyIfQueued:ba(Ko)}),RS=q([G({status:X(`absent`)}),G({status:X(`present`),cancellation:LS})]);q([G({status:X(`found`),job:IS,cancellation:RS}),G({status:X(`missing`)})]),q([G({state:X(`idle`)}),G({state:Ra([`queued`,`running`]),jobId:wS,cancellationRequested:Ko})]),q([G({status:X(`queued`)}),G({status:X(`duplicate`)})]),q([G({status:X(`decided`),outcome:jS}),G({status:Ra([`recorded`,`replayed`])}),G({status:Ra([`conflict`,`missing`])})]);var zS=q([zo(ArrayBuffer),Y,Da,pa]);Aa(Y,zS);function BS(e){return aa({try:()=>{let t=e.concurrentLane===void 0?void 0:oo(Ux)(e.concurrentLane),n=CS(e.owner,e.project,t===void 0?void 0:{lane:t,include:!1}),r=Vx(e,n.store),i={...r,transactional:n.transactional};if(t===void 0)return Object.freeze(i);let a=Vx(e,n.partition({lane:t,include:!0}));return Object.freeze({...i,tickConcurrent:a.tick,close:Fi([Ni(r.close),Ni(a.close)],{concurrency:2}).pipe(oa(e=>{let t=e.find(Qo);return t===void 0?na:vi(t.cause)})),failLane:e=>e.lane===t?a.failLane(e):r.failLane(e),cancel:e=>r.read(e.jobId).pipe(oa(n=>n.status===`found`&&n.job.lane===t?a.cancel(e):r.cancel(e)))})},catch:e=>e instanceof Rx?e:new Rx(`store_unavailable`,e)})}var VS=e=>({owner:e.owner,project:e.project,isAlive:t=>Ci({try:()=>e.isAlive(t),catch:e=>new Rx(`liveness_unavailable`,e)}),executor:{retryPolicy:t=>{let n=e.retryPolicy;return n===void 0?qi(void 0):Ci({try:()=>n(t),catch:e=>new Rx(`execution_failed`,e)})},execute:(t,n)=>Ci({try:r=>e.execute(t,r,n),catch:()=>new Rx(`execution_failed`)})},wake:{recompute:()=>Ci({try:()=>e.wake.recompute(),catch:()=>new Rx(`wake_unavailable`)})}}),HS=e=>Li(e).then(e=>{if(ga(e))return e.value;let t=Ii(Sa(e.cause))??Pa(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))});function US(e){let t=VS(e);return e.concurrentLane===void 0?HS(BS(t)).then(WS):HS(BS({...t,concurrentLane:e.concurrentLane})).then(e=>Object.freeze({...WS(e),tickConcurrent:()=>HS(e.tickConcurrent())}))}function WS(e){return Object.freeze({wakeState:t=>HS(e.wakeState(t)),ingest:t=>HS(e.ingest(t)),read:t=>HS(e.read(t)),readQueueHead:t=>HS(e.readQueueHead(t)),tick:()=>HS(e.tick()),cancel:t=>HS(e.cancel(t)),failLane:t=>HS(e.failLane(t)),purge:t=>HS(e.purge(t)),transactional:e.transactional})}Object.freeze({make:US});function GS(e){return gi(()=>mc(()=>import(`./runtime-core-U8lOfyYX.js`).then(e=>e.t),__vite__mapDeps([0,1,2,3,4,5,6,7]))).pipe(oa(({openRuntimeCore:t})=>t(e)),$r(({agent:e})=>e))}function KS(e){try{e.release?.()}catch(e){fa(`late-instruction-release`,e)}}function qS(e,t,n){return Bi((r,i)=>{if(i.aborted)return;let a;try{a=Promise.resolve(e(i))}catch{r(ki(t()));return}let o=a.then(e=>{i.aborted?KS(e):r(qi(e))},e=>{i.aborted?fa(`late-instruction-acquisition`,e):r(ki(t()))});return Pi(()=>{n?.(o)})})}var JS=Ra([`Error`,`TypeError`,`RangeError`,`SyntaxError`,`ReferenceError`,`URIError`,`EvalError`,`AggregateError`,`AbortError`,`TimeoutError`]),YS=Ra([`EACCES`,`EPERM`,`ENOENT`,`EISDIR`,`ENOTDIR`,`EIO`,`EMFILE`,`ENFILE`,`ELOOP`,`ENOSPC`,`EROFS`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`ENOTFOUND`,`EAI_AGAIN`]);function XS(e){if(e instanceof xo)return e;let t=e instanceof Error?eo(JS)(e.name)?e.name:`OtherError`:`NonErrorThrown`,n=e instanceof Error&&`code`in e?e.code:void 0,r=eo(YS)(n)?{errorName:t,errorCode:n}:{errorName:t};return fa(`model-acquisition`,e,r),new xo(`model`,`rejected`,`Model acquisition failed`,void 0,e)}function ZS(e){return new xo(`model`,`rejected`,`Model release failed`,void 0,e)}function QS(e){let t=Ci({try:()=>e.release(),catch:ZS}),n={model:e.model,release:t,retryable:e.retryable};return e.failureReason!==void 0&&(n={...n,failureReason:e.failureReason}),e.providerError!==void 0&&(n={...n,providerError:e.providerError}),e.rejection!==void 0&&(n={...n,rejection:e.rejection}),e.stream===void 0?e.retryAfterMs===void 0?Object.freeze(n):Object.freeze({...n,retryAfterMs:e.retryAfterMs}):e.retryAfterMs===void 0?Object.freeze({...n,stream:e.stream}):Object.freeze({...n,stream:e.stream,retryAfterMs:e.retryAfterMs})}function $S(e){return Bi((t,n)=>{if(n.aborted)return;let r;try{r=Promise.resolve(e(n))}catch(e){t(ki(XS(e)));return}let i=r.then(e=>{if(n.aborted)return Promise.resolve(e.release()).then(()=>void 0);t(qi(QS(e)))},e=>{n.aborted?fa(`late-model-acquisition`,e):t(ki(XS(e)))});return Ci({try:()=>i,catch:ZS}).pipe(mi)})}function eC(e){let t,n=Kr(n=>oa(n(e),e=>Pi(()=>(t=e,e))));return $i(n,()=>t===void 0?na:t.release.pipe(mi),{interruptible:!0})}function tC(e){let t=({sessionId:t,preference:n})=>$S(r=>e.acquire({sessionId:t,preference:n,signal:r})),n=e.describe;return Object.freeze(n===void 0?{acquire:t}:{acquire:t,describe:({sessionId:e,preference:t})=>Ci({try:r=>n({sessionId:e,preference:t,signal:r}),catch:XS})})}function nC(e,t){return new xo(e,`rejected`,t)}var rC=Y.pipe(K(Ta(1)),K(J(256))),iC=Y.pipe(K(Ta(1)),K(Ha(e=>new TextEncoder().encode(e).byteLength<=32e3))),aC=G({revision:rC,text:iC,modules:Ca(wa(e=>Array.isArray(e)&&e.every(ia)))}),oC=wa(e=>ji(e)),sC=wa(e=>ji(e)),cC=G({bind:oC}),lC=wa(e=>ji(e)),uC=G({commit:lC,requestWake:sC,close:sC}),dC=G({close:sC}),fC=da(aC),pC=da(cC),mC=da(uC),hC=da(dC);function gC(e){return new xo(`runtime`,`invalid`,`Runtime host is invalid`,void 0,e)}function _C(){return new xo(`runtime`,`unavailable`,`Runtime host is unavailable`)}function vC(e,t){return aa({try:()=>t.call(e),catch:_C}).pipe(oa(e=>Ci({try:()=>Promise.resolve(e),catch:_C})),oa(e=>e===void 0?na:ki(gC())))}function yC(e,t,n){let r=hC({close:t});return r._tag===`Failure`?ki(gC(n)):si(vC(e,r.success.close)).pipe(ui({onFailure:e=>ki(gC({cause:n,cleanup:e})),onSuccess:()=>ki(gC(n))}))}function bC(e){return Wi(()=>{if(!ia(e))return ki(gC());let t=e,n;try{n=t.close}catch(e){return ki(gC(e))}let r;try{r=t.requestWake}catch(e){return yC(t,n,e)}let i=mC({commit:t.commit,requestWake:r,close:n});return i._tag===`Failure`?yC(t,n):qi(Object.freeze({commit:e=>Ci({try:()=>t.commit(()=>Mo(e)),catch:e=>e instanceof xo?e:_C()}),requestWake:vC(t,i.success.requestWake),close:vC(t,i.success.close)}))})}function xC(e){return aa({try:()=>{let t=e.runtime;if(!ia(t))throw gC();let n=pC(t);if(n._tag===`Failure`)throw gC();return{receiver:t,bind:n.success.bind}},catch:gC}).pipe($r(({receiver:e,bind:t})=>Object.freeze({bind:({reconcile:n,reconcileHost:r,pendingWork:i})=>aa({try:()=>t.call(e,{reconcile:()=>Mo(n),reconcileHost:r===void 0?void 0:()=>Mo(r),pendingWork:()=>Mo(i)}),catch:_C}).pipe(oa(e=>Ci({try:()=>Promise.resolve(e),catch:_C})),oa(bC))})))}function SC(e){return{lane:e.lane,open:t=>{let n=e.open({transactional:t.transactional,readJob:e=>Mo(t.read(e)),tickConcurrent:()=>Mo(t.tickConcurrent())});return{retryPolicy:e=>{let t=n.retryPolicy;return t===void 0?qi(void 0):Ci({try:()=>t(e),catch:e=>new Rx(`execution_failed`,e)})},execute:(e,t)=>Ci({try:r=>n.execute(e,r,t),catch:e=>new Rx(`execution_failed`,e)})}}}}function CC(e,t){let n={store:e.store,runtime:t,extensions:e.extensions,instructions:{load:({sessionId:t,commandId:n,track:r})=>qS(r=>e.instructions.load({sessionId:t,commandId:n,signal:r}),()=>nC(`instructions`,`Instruction acquisition failed`),r).pipe(oa(e=>{let t=fC(e);return t._tag===`Success`?qi(t.success):ki(new xo(`contract`,`invalid`,`Instruction revision is invalid`))}))},model:tC(e.model)},r=e.recipientStatus,i=e.recipientParent;i!==void 0&&Object.assign(n,{recipientParent:e=>Ci(()=>i(e)).pipe(Ti(e=>Yr(`recipient.parent_unavailable`,Jo(e)).pipe(bi(ki(new Vs({reason:`unavailable`,message:`Recipient parent is unavailable`}))))))}),r!==void 0&&Object.assign(n,{recipientStatus:e=>Ci(()=>r(e)).pipe(Ti(e=>Yr(`recipient.status_unavailable`,Jo(e)).pipe(Zi(`unknown`))))}),e.hostJobs!==void 0&&Object.assign(n,{hostJobs:SC(e.hostJobs)}),e.meta!==void 0&&Object.assign(n,{meta:e.meta}),e.storagePressure!==void 0&&Object.assign(n,{storagePressure:e.storagePressure}),e.admission!==void 0&&Object.assign(n,{admission:e.admission}),e.compaction!==void 0&&Object.assign(n,{compaction:e.compaction}),e.createdBy!==void 0&&Object.assign(n,{createdBy:e.createdBy});let a=e.tools;return a===void 0?n:{...n,tools:co(a)}}function wC(e,t){return Mo(xC(e).pipe(oa(n=>t(CC(e,n))))).then(To)}Object.freeze({make:e=>wC(e,GS)});var TC=200,EC=Si({action:Ki(`list`)}),DC=sa(ra(),Ei()).parse(structuredClone(ai(EC))),OC=120,kC=Si({title:ra()}).optional().transform(e=>e?.title.trim().replaceAll(/\s+/gu,` `)??``),AC=4096,jC=Si({instructions:ra()}).optional().transform(e=>e?.instructions.trim()??``);function MC(e,t){return e?.notify({type:`info`,message:t}),t}function NC(e,t){let n=e=>{throw Error(`${e} is unavailable in this host.`)};return{sourceId:t.sourceId,namespace:t.namespace,commands:[{id:`session`,title:`Session status`,category:`Advanced`,projections:{help:{order:1},palette:{order:1},slash:{aliases:[`session`],order:1}},handler:async({interaction:t})=>{let n=await e.read();return MC(t,`Session ${n.sessionId} is ${je(j(n))}; ${String(n.pending.prompts.length)} queued prompt${n.pending.prompts.length===1?``:`s`}.`)}},{id:`queue`,title:`Queued prompts`,category:`Advanced`,projections:{help:{order:3},palette:{order:3},slash:{aliases:[`queue`],order:3,arguments:{hint:`list`,words:[{word:`list`,description:`List accepted queued prompts`,arguments:{action:`list`}}]}}},action:{inputSchema:DC},handler:async({arguments:t,interaction:n})=>{if(!EC.safeParse(t??{action:`list`}).success)throw Error(`/queue requires list.`);let r=await e.read(),i=r.pending.prompts,a=r.terminals.map(e=>`${e.outcome} · ${e.commandId}`);MC(n,i.length===0&&a.length===0?`No queued prompts.`:[...i.map((e,t)=>`${String(t+1)}. queued · accepted: ${e.text}`),...a,...r.pending.hasMore===!0?[`More accepted prompts are waiting outside this view.`]:[]].join(`
|
|
117
|
-
`))}},{id:`resume`,title:`Resume a conversation`,category:`Conversation`,projections:{help:{order:5},palette:{order:5},slash:{aliases:[`resume`],order:5}},handler:async()=>{if(!t.sessionResumeAvailable||t.sessionResume===void 0){n(`/resume`);return}await t.sessionResume()}},{id:`fork`,title:`Fork conversation`,category:`Conversation`,projections:{help:{order:7},palette:{order:7},slash:{aliases:[`fork`],order:7}},handler:async({interaction:r})=>{let i=t.onForked;if(!t.forkAvailable||i===void 0){n(`/fork`);return}let a=await e.read();if(je(j(a))!==`idle`)throw Error(`Wait for the current run to finish, then fork.`);let o=zr(a.messages??[],a.compactions??[]).items.filter(e=>e.kind===`user_message`);if(o.length===0)throw Error(`No messages to fork from.`);if(r===void 0)throw Error(`Forking a Session needs a person.`);let s=[...o].reverse().slice(0,TC),c=Date.now(),l=await r.prompt({type:`choice`,message:`Fork from which message?`,summary:`Start a new conversation from your message.`,options:s.map(e=>({value:e.id,label:hx(e.text,44)||`(empty message)`,description:e.at===void 0?void 0:mx(e.at,c)}))}),u=await r.run(async()=>{try{return await e.command({type:`fork`,entryId:l})}catch(e){if(e instanceof xo){if(e.boundary===`runtime`&&e.cause===`conflict`)throw Error(`Wait for the current run to finish, then fork.`,{cause:e});if(e.boundary===`store`&&e.cause===`unavailable`)throw Error(`That message is no longer available to fork from.`,{cause:e});if(e.boundary===`runtime`&&e.cause===`rejected`)throw Error(`This Session is bound to a channel and cannot be forked.`,{cause:e})}throw e}});await r.run(async()=>{await i(u.sessionId)})}},{id:`compact`,title:`Compact conversation`,category:`Conversation`,description:`Summarize older context now; optional text sets its focus`,projections:{help:{order:8},palette:{order:8},slash:{aliases:[`compact`],order:8,arguments:{hint:`[instructions]`,text:{field:`instructions`,arguments:{}}}}},handler:async({arguments:t})=>{let n=jC.safeParse(t);if(!n.success)throw Error(`Use /compact, or /compact <what to focus on>.`);let r=n.data;if(r.length>AC)throw Error(`Compaction instructions are at most ${String(AC)} characters.`);return await e.command(r.length===0?{type:`compact`,requestId:po()}:{type:`compact`,requestId:po(),instructions:r}),`Compaction queued; it runs after any current work.`}},{id:`name`,title:`Name conversation`,category:`Conversation`,description:`Set the conversation title; no text restores it`,projections:{help:{order:9},palette:{order:9},slash:{aliases:[`name`],order:9,arguments:{hint:`[title]`,text:{field:`title`,arguments:{}}}}},handler:async({arguments:n})=>{let r=kC.safeParse(n);if(!r.success)throw Error(`Use /name <title>, or /name to clear it.`);let i=r.data;if(Array.from(i).length>OC)throw Error(`A conversation title is at most ${String(OC)} characters.`);let a=i.length===0?null:i;return await e.command({type:`title`,title:a}),await t.onTitled?.(a),a===null?`Conversation title cleared; it follows the first prompt again.`:`Conversation named "${a}".`}}]}.commands}var PC=Br(`Ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),FC=Br(`EyeOff`,[[`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,key:`ct8e1f`}],[`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`,key:`151rxh`}],[`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,key:`13bj9a`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),IC=Br(`Eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),LC=Br(`FileImage`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`10`,cy:`12`,r:`2`,key:`737tya`}],[`path`,{d:`m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22`,key:`wt3hpn`}]]),RC=Br(`NotebookPen`,[[`path`,{d:`M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4`,key:`re6nr2`}],[`path`,{d:`M2 6h4`,key:`aawbzj`}],[`path`,{d:`M2 10h4`,key:`l0bgd4`}],[`path`,{d:`M2 14h4`,key:`1gsvsf`}],[`path`,{d:`M2 18h4`,key:`1bu2t1`}],[`path`,{d:`M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z`,key:`pqwjuv`}]]),zC=Br(`PanelLeftOpen`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`m14 9 3 3-3 3`,key:`8010ee`}]]),BC=Br(`Pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),VC=Br(`RotateCcw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),HC=Br(`SquarePen`,[[`path`,{d:`M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7`,key:`1m0v6g`}],[`path`,{d:`M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z`,key:`ohrbg2`}]]),UC=Br(`Trash2`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6`,key:`4alrt4`}],[`path`,{d:`M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2`,key:`v07s0e`}],[`line`,{x1:`10`,x2:`10`,y1:`11`,y2:`17`,key:`1uufr5`}],[`line`,{x1:`14`,x2:`14`,y1:`11`,y2:`17`,key:`xtxkd`}]]),WC=(0,Q.memo)(function({avatar:e,className:t=`h-12 w-12 shrink-0`,service:n=ir,state:r}){let i=(0,Q.useMemo)(()=>e?hn(e):void 0,[e]);return(0,$.jsx)(At,{"aria-hidden":`true`,className:t,service:n,src:i?.src??{local:`mushroom`},...i?{appearance:i.appearance,renderStyle:i.renderStyle}:{},...r})}),GC=3e4;function KC(e){let t=new Set,n=e=>{let n=e.then(()=>{t.delete(n)},()=>{t.delete(n)});t.add(n)};function r(t){let r=e.command(t);return n(r),r}return{session:{...e,command:r,withdraw:t=>{let r=e.withdraw(t);return n(r),r}},settled:async()=>{let e,n=new Promise(t=>{e=setTimeout(t,GC)});await Promise.race([Promise.all(t),n]),clearTimeout(e)}}}function qC(e,t){let n=!1,r=async()=>{try{return await t.read()}catch(e){if(!(e instanceof xo)||e.boundary!==`runtime`||e.cause!==`unavailable`)throw e;if(await new Promise(e=>setTimeout(e,150)),n)throw Error(`Conversation opening cancelled`,{cause:e});return t.read()}},i,a=new Promise((e,t)=>{i=()=>{t(Error(`Conversation opening cancelled`))}});return{ready:Promise.race([r(),a]).then(r=>{if(n)throw Error(`Conversation opening cancelled`);kt(e,t,r)}),close:()=>{n=!0,i()}}}function JC(e){return class{#e;constructor(t){this.#e=new Up(t,{fetch:(t,n)=>e(t,n)})}get readyState(){return this.#e.readyState}addEventListener(e,t,n){this.#e.addEventListener(e,t,n)}close(){this.#e.close()}}}function YC(e){let{connection:t,queryClient:n,services:r}=e,i=null,a=null,o=null,s=!1,c=(e,t)=>e?.agentId===t.agentId&&e.sessionId===t.sessionId,l=e=>!s&&i===e,u=(u,d,f=!1)=>{if(s)return;let p={agentId:u,sessionId:d};if(c(i,p)||(i?.close(),i=null,e.onPending(null),e.onError(null),c(a,p)))return;let m=null,h=!1,g={...p,close:()=>{h||(h=!0,m?.())}};i=g,e.onPending(p),(async()=>{try{let s=await r.openAgent(t.capabilities,{agentId:u});if(!l(g)){await s.close();return}let c=r.createClient({baseUrl:s.baseUrl,eventSource:JC(s.fetch),fetch:s.fetch}),f=KC(c.session(d)),p=f.session,h=qC(n,p);if(m=()=>{h.close(),f.settled().then(()=>Promise.allSettled([c.close(),s.close()]))},await h.ready,e.reportsSelection!==!1&&await t.ui.reportAgentSessionSelection({agentId:u,sessionId:d}),!l(g))return;let _={agentId:u,sessionId:d,session:p},v=o;i=null,a=_,o=g.close,e.onConversation(_),e.onPending(null),v?.()}catch(t){console.error(`Chat Session opening failed`,t),g.close(),l(g)&&(i=null,e.onPending(null),e.onError(f?`That Session could not be opened. ${a?`The current conversation remains open.`:`Choose another Session from the list.`}`:`Could not open this Session${t instanceof Error?`: ${t.message}`:``}. ${a?`The previous conversation remains open.`:`Try opening it again.`}`))}})()},d=()=>{if(s)return;let n=i!==null||a!==null;i?.close(),i=null,o?.(),o=null,a=null,e.onPending(null),e.onConversation(null),e.onError(null),!(!n||e.reportsSelection===!1)&&t.ui.reportAgentSessionSelection(null).catch(e=>{console.error(`Chat Session selection could not be reported`,e)})};return{select:u,clear:d,close:()=>{d(),s=!0}}}var XC={view:{kind:`none`},creating:null,awaitingRoute:void 0,route:null,nextTicket:1},ZC=(e,t)=>e===t||!!e&&!!t&&e.agentId===t.agentId&&e.sessionId===t.sessionId;function QC(e,t){return e.awaitingRoute!==void 0||!ZC(e.route,t)?{awaitingRoute:t,effects:[{type:`navigate`,target:t}]}:{awaitingRoute:void 0,effects:[]}}function $C(e){return e.kind===`opening`?e.target:e.kind===`open`?e.conversation:null}function ew(e){return e.kind===`open`?e.conversation:e.kind===`opening`?e.previous:null}function tw(e,t=[],n=!0,r=null){return{state:e,effects:t,accepted:n,ticket:r}}function nw(e,t,n){let r=$C(e.view),i=n===`host`;if(ZC(r,t)){let n=QC(e,t);return tw({...e,creating:null,awaitingRoute:n.awaitingRoute},n.effects)}let a=ew(e.view);if(n!==`route`&&a!==null&&ZC(a,t)){let n=QC(e,t);return tw({...e,view:{kind:`open`,conversation:a},creating:null,awaitingRoute:n.awaitingRoute},[{type:`open`,target:t,fromHost:i},...n.effects])}let o=n===`route`?null:QC(e,t);return tw({...e,view:{kind:`opening`,target:t,cause:n,previous:ew(e.view)},creating:null,awaitingRoute:o?o.awaitingRoute:void 0},[{type:`open`,target:t,fromHost:i},...o?o.effects:[]])}function rw(e,t){switch(t.type){case`select`:return nw(e,t.target,t.cause);case`route`:{let n={...e,route:t.target},r=n.awaitingRoute;return r===void 0?t.target===null?n.view.kind===`none`||n.creating?.cause===`person`?tw(n):tw({...n,view:{kind:`none`},creating:null},[{type:`clear`}]):ZC($C(n.view),t.target)||n.creating?.cause===`person`?tw(n):nw(n,t.target,`route`):tw(ZC(r,t.target)?{...n,awaitingRoute:void 0}:n)}case`route-confirmed`:{let n={...e,route:t.target};return tw(ZC(n.awaitingRoute,t.target)?{...n,awaitingRoute:void 0}:n)}case`create`:{if(t.cause===`auto`&&(e.view.kind!==`none`||e.creating!==null||e.awaitingRoute!==void 0))return tw(e,[],!1);let n=e.nextTicket;return tw({...e,creating:{ticket:n,cause:t.cause},nextTicket:n+1},[],!0,n)}case`created`:{if(e.creating?.ticket!==t.ticket)return tw(e,[],!1);let n=e.creating.cause;return n===`auto`&&e.view.kind!==`none`?tw({...e,creating:null},[],!1):nw({...e,creating:null},t.target,n)}case`create-failed`:return e.creating?.ticket===t.ticket?tw({...e,creating:null}):tw(e,[],!1);case`opened`:{let n=e.view;return n.kind!==`opening`||!ZC(n.target,t.conversation)?tw(e,[],!1):tw({...e,view:{kind:`open`,conversation:t.conversation}})}case`open-failed`:{let t=e.view;if(t.kind!==`opening`)return tw(e,[],!1);let n=t.previous,r=QC(e,n);return tw({...e,view:n?{kind:`open`,conversation:n}:{kind:`none`},awaitingRoute:r.awaitingRoute},r.effects)}case`leave`:{let n=t.navigate?QC(e,null):null;return tw({...e,view:{kind:`none`},creating:null,awaitingRoute:n?n.awaitingRoute:void 0},[{type:`clear`},...n?n.effects:[]])}case`reset`:return tw({...e,view:{kind:`none`},creating:null,awaitingRoute:void 0})}}function iw(e){return ew(e.view)}function aw(e){return e.view.kind===`opening`?e.view.target:null}function ow(e){let t={state:XC,error:null},n=!1,r=new Set,i=e=>{t={...t,...e};for(let e of r)e()},a=YC({connection:e.connection,queryClient:e.queryClient,services:e.services,onPending:()=>void 0,onConversation:e=>{e!==null&&s({type:`opened`,conversation:e})},onError:e=>{i({error:e}),e!==null&&s({type:`open-failed`})}}),o=t=>{if(t.type===`open`)a.select(t.target.agentId,t.target.sessionId,t.fromHost);else if(t.type===`clear`)a.clear();else if(e.navigate!==void 0){let n=()=>{s({type:`route-confirmed`,target:e.shownRoute?.()??null})};e.navigate(t.target).then(n,n)}};function s(e){if(n)return{accepted:!1,ticket:null};let r=rw(t.state,e);i({state:r.state});for(let e of r.effects)o(e);return{accepted:r.accepted,ticket:r.ticket}}return{snapshot:()=>t,subscribe:e=>(r.add(e),()=>{r.delete(e)}),select:(e,t=`person`)=>s({type:`select`,target:e,cause:t}),observeRoute:e=>s({type:`route`,target:e}),create:(e=`person`)=>s({type:`create`,cause:e}),created:(e,t)=>s({type:`created`,ticket:e,target:t}),createFailed:e=>s({type:`create-failed`,ticket:e}),leave:e=>s({type:`leave`,navigate:e}),close:()=>{n||(s({type:`reset`}),n=!0,a.close(),r.clear())}}}Io()([],()=>(e,t,n)=>aa({try:()=>wm(e,n.onExcessProperty===`error`),catch:()=>new va(t,e,n)}));var sw={artifactRef:Th,digest:Oh,version:Y.pipe(K(Ta(1))),byteLength:Da.pipe(K(La()),K(Go(0)),K(Ha(Number.isSafeInteger)))},cw=G({...sw,mediaType:Ra([`text/html; charset=utf-8`,`application/vnd.fungi.app-assets+json`])}),lw=G({...sw,mediaType:X(`application/vnd.fungi.app-backend+json`)}),uw={declaration:Ca(dh)},dw=q([G({format:X(`fungi-app-v1`),ui:cw,backend:lw,...uw}),G({format:X(`fungi-app-v1`),ui:cw,...uw}),G({format:X(`fungi-app-v1`),backend:lw,...uw})]).pipe(K(Ha(e=>e.declaration?.api===void 0||`backend`in e,{message:`An App API requires a backend`})));ko(dw);var fw=Ra([`invalid`,`undeclared_key`,`scope_not_declared`,`owner_required`,`too_large`,`quota_exceeded`,`conflict`,`unavailable`]),pw=class extends Error{code;constructor(e,t){super(e,t),this.code=e}},mw=Xo.check(Go(0)),hw=G({value:Ia,revision:mw}),gw=G({value:Ia,source:Ra([`member`,`team`,`none`]),team:vo(hw),member:vo(hw),canWriteTeam:Ko}),_w={key:ih,scope:Ra(sm),basedOn:vo(mw)},vw=G({..._w,value:Ia}),yw=G(_w),bw=G({revision:mw}),xw=G({appId:Y,key:ih,scope:Ra(sm),revision:mw}),Sw=q([G({kind:X(`accepted`),value:gw}),G({kind:X(`rejected`),code:fw})]),Cw=q([G({kind:X(`accepted`),value:bw}),G({kind:X(`rejected`),code:fw})]),ww=G({error:Y});q([Sw,ww]),q([Cw,ww]);var Tw=e=>cc(ci().transform(t=>oo(e,{onExcessProperty:`error`})(t))),Ew=as({read:is(Tw(Sw)),write:is(Tw(Cw)),reset:is(Tw(Cw)),openEvents:is(bs)}),Dw=e=>{if(e.kind===`rejected`)throw new pw(e.code);return e.value},Ow=(e,t)=>{let n=da(e,{onExcessProperty:`error`})(t);if(n._tag===`Failure`)throw new pw(`invalid`,{cause:n.failure});return n.success},kw=e=>Ow(ih,e);function Aw(e){let t=async t=>Dw(await e.read(kw(t)));return{read:t,write:async t=>Dw(await e.write(Ow(vw,t))),reset:async t=>Dw(await e.reset(Ow(yw,t))),async watch(n){let r=kw(n),i=await e.openEvents(r),a=!1,o=()=>a,s,c=!1,l=()=>c&&!o(),u,d=()=>void 0,f=()=>void 0,p=new Promise((e,t)=>{d=e,f=t}),m=new Up(`https://app-storage.fungi.invalid/events`,{fetch:async(e,t)=>{let n=await i.fetch(new Request(e,t));if(!n.ok){let e=da(Sw)(await n.json()),t=new pw(e._tag===`Success`&&e.success.kind===`rejected`?e.success.code:`unavailable`);throw g(t),t}return n}}),h=()=>{a||(a=!0,m.close(),f(new pw(`unavailable`)),i.close().catch(e=>{dc(`storage.watch.close`,e)}).finally(()=>{i[Symbol.dispose]()}))},g=e=>{f(e instanceof pw?e:new pw(`unavailable`,{cause:e})),!a&&u!==void 0&&dc(`storage.watch`,e),h()},_=()=>{c=!0,!(s!==void 0||a)&&(s=(async()=>{for(;l();){c=!1;let e=await t(r);if(o())return;if(u===void 0){let t=ps(e);u=t,d({get:()=>t.get(),subscribe:e=>t.subscribe(e),close:h,[Symbol.dispose]:h})}else u.update(e)}})().catch(g).finally(()=>{s=void 0,c&&!a&&_()}))};return m.addEventListener(`ready`,_),m.addEventListener(`changed`,e=>{let t=da(ko(xw),{onExcessProperty:`error`})(e.data);t._tag===`Failure`?g(t.failure):t.success.key===r?_():g(new pw(`invalid`))}),m.onerror=e=>{(u===void 0||m.readyState===Up.CLOSED)&&g(e)},p}}}var jw=Ws(`app.storage`,1,Di(()=>Ew.transform(Aw))),Mw=Q.createContext(void 0);function Nw(){let e=Q.useContext(Mw);if(e===void 0)throw Error(U(53));return e}function Pw(e,t,n){if(!e)return 0;let r=getComputedStyle(e),i=`${t}${n===`x`?`Inline`:`Block`}`,a=parseFloat(r[`${i}Start`]);return n===`x`&&t===`margin`?a*2:a+parseFloat(r[`${i}End`])}var Fw=`base-ui-disable-scrollbar`,Iw={className:Fw,getElement(e){return(0,$.jsx)(`style`,{nonce:e,href:Fw,precedence:`base-ui:low`,children:`.${Fw}{scrollbar-width:none}.${Fw}::-webkit-scrollbar{display:none}`})}},Lw=`data-has-overflow-x`,Rw=`data-has-overflow-y`,zw=`data-overflow-x-start`,Bw=`data-overflow-x-end`,Vw=`data-overflow-y-start`,Hw=`data-overflow-y-end`,Uw=e=>t=>t?{[e]:``}:null,Ww={hasOverflowX:Uw(Lw),hasOverflowY:Uw(Rw),overflowXStart:Uw(zw),overflowXEnd:Uw(Bw),overflowYStart:Uw(Vw),overflowYEnd:Uw(Hw),cornerHidden:()=>null},Gw=Q.createContext(void 0),Kw={disableStyleElements:!1};function qw(){return Q.useContext(Gw)??Kw}var Jw=`--scroll-area-corner-height`,Yw=`--scroll-area-corner-width`,Xw=`data-orientation`,Zw={x:0,y:0},Qw={width:0,height:0},$w={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},eT={x:!0,y:!0,corner:!0},tT=Q.forwardRef(function(e,t){let{render:n,className:r,overflowEdgeThreshold:i,style:a,...o}=e,{xStart:s,xEnd:c,yStart:l,yEnd:u}=nT(i),d=D(),f=ln(),p=ln(),{nonce:m,disableStyleElements:h}=qw(),[g,_]=Q.useState(!1),[v,y]=Q.useState(!1),[b,x]=Q.useState(!1),[S,C]=Q.useState(!1),[w,T]=Q.useState(!1),[E,O]=Q.useState(Qw),[k,j]=Q.useState(Qw),[M,N]=Q.useState($w),[ee,te]=Q.useState(eT),ne=Q.useRef(null),P=Q.useRef(null),F=Q.useRef(null),re=Q.useRef(null),I=Q.useRef(null),L=Q.useRef(null),R=Q.useRef(null),z=Q.useRef(null),ie=Q.useRef(0),ae=Q.useRef(0),oe=Q.useRef(0),se=Q.useRef(0),B=Q.useRef(`vertical`),ce=Q.useRef(Zw),le=Q.useRef(null);function ue(e){let t=e?x:y,n=e?f:p;t(!0),n.start(500,()=>{t(!1)})}let V=A(e=>{let t=e.x-ce.current.x,n=e.y-ce.current.y;ce.current=e,n!==0&&ue(!0),t!==0&&ue(!1)}),de=A(()=>{let e=P.current;e&&le.current===null&&(le.current=e.style.scrollSnapType,e.style.scrollSnapType=`none`)}),H=A(e=>{if(e.button!==0||z.current!==null&&(B.current===`vertical`?I.current:L.current)?.hasPointerCapture(z.current))return;z.current=e.pointerId,ie.current=e.clientY,ae.current=e.clientX,B.current=e.currentTarget.getAttribute(Xw);let t=P.current;t&&(oe.current=t.scrollTop,se.current=t.scrollLeft,de()),(B.current===`vertical`?I.current:L.current)?.setPointerCapture(e.pointerId)}),fe=A(e=>{if(e.pointerId!==z.current)return;z.current=null,(B.current===`vertical`?x:y)(!1),le.current!==null&&(P.current&&(P.current.style.scrollSnapType=le.current),le.current=null);let t=B.current===`vertical`?I.current:L.current;t?.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId)}),pe=A(e=>{if(e.pointerId!==z.current)return;if(e.buttons%2==0){fe(e);return}let t=P.current;if(!t)return;let n=B.current===`vertical`,r=n?I.current:L.current,i=n?F.current:re.current;if(!r||!i)return;let a=n?`y`:`x`,o=Pw(i,`padding`,a),s=Pw(r,`margin`,a),c=n?r.offsetHeight:r.offsetWidth,l=(n?i.offsetHeight:i.offsetWidth)-c-o-s,u=n?e.clientY-ie.current:e.clientX-ae.current,d=l<=0?0:u/l,f=n?t.scrollHeight:t.scrollWidth,p=n?t.clientHeight:t.clientWidth,m=(n?oe.current:se.current)+d*(f-p);n?t.scrollTop=m:t.scrollLeft=m,e.preventDefault(),ue(n)});function me(e){C(e.pointerType===`touch`)}function he(e){if(me(e),e.pointerType!==`touch`){let t=jn(ne.current,e.target);_(t)}}let ge=Q.useMemo(()=>({scrolling:v||b,hasOverflowX:!ee.x,hasOverflowY:!ee.y,overflowXStart:M.xStart,overflowXEnd:M.xEnd,overflowYStart:M.yStart,overflowYEnd:M.yEnd,cornerHidden:ee.corner}),[v,b,ee.x,ee.y,ee.corner,M]),_e={role:`presentation`,onPointerEnter:he,onPointerMove:he,onPointerDown:me,onPointerLeave(){_(!1)},style:{position:`relative`,[Jw]:`${E.height}px`,[Yw]:`${E.width}px`}},U=Or(`div`,e,{state:ge,ref:[t,ne],props:[_e,o],stateAttributesMapping:Ww}),ve=Q.useMemo(()=>({handlePointerDown:H,handlePointerMove:pe,handlePointerUp:fe,handleScroll:V,disableViewportSnap:de,cornerSize:E,setCornerSize:O,thumbSize:k,setThumbSize:j,hasMeasuredScrollbar:w,setHasMeasuredScrollbar:T,touchModality:S,cornerRef:R,scrollingX:v,scrollingY:b,hovering:g,setHovering:_,viewportRef:P,scrollbarYRef:F,scrollbarXRef:re,thumbYRef:I,thumbXRef:L,rootId:d,hiddenState:ee,setHiddenState:te,overflowEdges:M,setOverflowEdges:N,viewportState:ge,overflowEdgeThreshold:{xStart:s,xEnd:c,yStart:l,yEnd:u}}),[H,pe,fe,V,de,E,k,w,S,v,b,g,d,ee,M,ge,s,c,l,u]);return(0,$.jsxs)(Mw.Provider,{value:ve,children:[!h&&Iw.getElement(m),U]})});function nT(e){let t=typeof e==`number`?{xStart:e,xEnd:e,yStart:e,yEnd:e}:e;return{xStart:Math.max(0,t?.xStart||0),xEnd:Math.max(0,t?.xEnd||0),yStart:Math.max(0,t?.yStart||0),yEnd:Math.max(0,t?.yEnd||0)}}function rT(e,t=-(2**53-1),n=2**53-1){return Math.max(t,Math.min(e,n))}var iT=Q.createContext(void 0);function aT(){let e=Q.useContext(iT);if(e===void 0)throw Error(U(55));return e}function oT(e,t){if(t<=0)return 0;let n=rT(e,0,t),r=n,i=t-n,a=r<=1,o=i<=1;return a&&o?r<=i?0:t:a?0:o?t:n}var sT=`--scroll-area-overflow-x-start`,cT=`--scroll-area-overflow-x-end`,lT=`--scroll-area-overflow-y-start`,uT=`--scroll-area-overflow-y-end`,dT=`--scroll-area-thumb-height`,fT=`--scroll-area-thumb-width`,pT=[sT,cT,lT,uT],mT=!1;function hT(){mT||Ee||(typeof CSS<`u`&&`registerProperty`in CSS&&pT.forEach(e=>{try{CSS.registerProperty({name:e,syntax:`<length>`,inherits:!1,initialValue:`0px`})}catch{}}),mT=!0)}var gT=Q.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{viewportRef:o,scrollbarYRef:s,scrollbarXRef:c,thumbYRef:l,thumbXRef:u,cornerRef:d,cornerSize:f,setCornerSize:p,setThumbSize:m,rootId:h,setHiddenState:g,hiddenState:_,setHasMeasuredScrollbar:v,handleScroll:y,touchModality:b,setHovering:x,setOverflowEdges:S,overflowEdgeThreshold:C,viewportState:w}=Nw(),T=rb(),E=Q.useRef(!0),D=Q.useRef([NaN,NaN,NaN,NaN]),O=ln(),k=ln(),j=A(()=>{let e=o.current,t=s.current,n=c.current,r=l.current,i=u.current,a=d.current;if(!e)return;let h=e.scrollHeight,_=e.scrollWidth,y=e.clientHeight,b=e.clientWidth,x=e.scrollTop,w=e.scrollLeft,E=D.current,O=Number.isNaN(E[0]);if(E[0]=y,E[1]=h,E[2]=b,E[3]=_,O&&v(!0),h===0||_===0)return;let k=_T(e),A=k.y,j=k.x,M=b/_,N=y/h,ee=Math.max(0,_-b),te=Math.max(0,h-y),ne=0,P=0;j||(ne=oT(T===`rtl`?-w:w,ee),P=ee-ne);let F=A?0:oT(x,te),re=A?0:te-F,I=j?0:b,L=A?0:y,R=0,z=0;!j&&!A&&(R=t?.offsetWidth||0,z=n?.offsetHeight||0);let ie=f.width===0&&f.height===0,ae=ie?R:0,oe=ie?z:0,se=Pw(n,`padding`,`x`),B=Pw(t,`padding`,`y`),ce=Pw(i,`margin`,`x`),le=Pw(r,`margin`,`y`),ue=I-se-ce,V=L-B-le,de=n?Math.min(n.offsetWidth-ae,ue):ue,H=t?Math.min(t.offsetHeight-oe,V):V,fe=Math.max(16,de*M),pe=Math.max(16,H*N);if(m(e=>vT(e,{width:fe,height:pe})),t&&r){let e=yT(r,dT,x,te,h,pe,t.offsetHeight-pe-B-le);r.style.transform=`translate3d(0,${e}px,0)`}if(n&&i){let e=n.offsetWidth-fe-se-ce,t=yT(i,fT,T===`rtl`?-w:w,ee,_,fe,e);i.style.transform=`translate3d(${T===`rtl`?-t:t}px,0,0)`}let me=[ne,P,F,re];pT.forEach((t,n)=>{e.style.setProperty(t,`${me[n]}px`)}),a&&p(e=>vT(e,{width:R,height:z})),g(e=>vT(e,k));let he={xStart:!j&&ne>C.xStart,xEnd:!j&&P>C.xEnd,yStart:!A&&F>C.yStart,yEnd:!A&&re>C.yEnd};S(e=>vT(e,he))});Ae(()=>{hT()},[]),Ae(()=>{queueMicrotask(j)},[j,_,T,C.xStart,C.xEnd,C.yStart,C.yEnd]),Ae(()=>{o.current?.matches(`:hover`)&&x(!0)},[o,x]),Ae(()=>{let e=o.current;if(typeof ResizeObserver>`u`||!e)return;let t=!1,n=new ResizeObserver(()=>{if(!t){t=!0;let n=D.current;if(n[0]===e.clientHeight&&n[1]===e.scrollHeight&&n[2]===e.clientWidth&&n[3]===e.scrollWidth)return}j()});return n.observe(e),k.start(0,()=>{let t=Rr(e,{subtree:!0});t.length!==0&&Promise.allSettled(t.map(e=>e.finished.then(Tn))).then(j).catch(()=>{})}),()=>{n.disconnect(),k.clear()}},[j,o,k]);function M(){E.current=!1}let N={...h&&{"data-id":`${h}-viewport`},tabIndex:_.x&&_.y?-1:0,className:Iw.className,style:{overflow:`scroll`},onScroll(){o.current&&(j(),(b||!E.current)&&y({x:o.current.scrollLeft,y:o.current.scrollTop}),O.start(100,()=>{E.current=!0}))},onWheel:M,onPointerMove:M,onPointerEnter:M,onKeyDown:M},ee=Or(`div`,e,{ref:[t,o],state:w,props:[N,a],stateAttributesMapping:Ww}),te=Q.useMemo(()=>({computeThumbPosition:j}),[j]);return(0,$.jsx)(iT.Provider,{value:te,children:ee})});function _T(e){let t=e.clientHeight>=e.scrollHeight,n=e.clientWidth>=e.scrollWidth;return{y:t,x:n,corner:t||n}}function vT(e,t){for(let n in t)if(e[n]!==t[n])return t;return e}function yT(e,t,n,r,i,a,o){let s=rT(n,0,r),c=n-s,l=Math.max(16,a*i/(i+Math.abs(c)));return e.style.setProperty(t,c?`${l}px`:``),(r?s/r*o:0)+(c>0?a-l:0)}var bT=Q.createContext(void 0);function xT(){let e=Q.useContext(bT);if(e===void 0)throw Error(U(54));return e}var ST=Q.forwardRef(function(e,t){let{render:n,className:r,orientation:i=`vertical`,keepMounted:a=!1,style:o,...s}=e,{hovering:c,scrollingX:l,scrollingY:u,hiddenState:d,scrollbarYRef:f,scrollbarXRef:p,viewportRef:m,thumbYRef:h,thumbXRef:g,handlePointerDown:_,handlePointerUp:v,handleScroll:y,disableViewportSnap:b,rootId:x,thumbSize:S,hasMeasuredScrollbar:C,viewportState:w}=Nw(),T=i===`vertical`,E={...w,hovering:c,scrolling:T?u:l,orientation:i},D=rb(),O=!C&&!a,k=T?d.y:d.x,A=a||!k;Q.useEffect(()=>{if(!A)return;let e=m.current,t=T?f.current:p.current;if(!t)return;function n(t){if(!e||t.ctrlKey)return;let n=!T,r=n?`scrollLeft`:`scrollTop`,i=n?t.deltaX:t.deltaY;if(i===0)return;let a=n?e.scrollWidth-e.clientWidth:e.scrollHeight-e.clientHeight,o=n&&D===`rtl`?-a:0,s=n&&D===`rtl`?0:a,c=e[r];c<=o&&i<0||c>=s&&i>0||(t.preventDefault(),e[r]=Math.min(s,Math.max(o,c+i)),y({x:e.scrollLeft,y:e.scrollTop}))}return dt(t,`wheel`,n,{passive:!1})},[D,y,T,p,f,A,m]);let j={...x&&{"data-id":`${x}-scrollbar`},"aria-hidden":!0,onPointerDown(e){if(e.button!==0)return;let t=br(e.nativeEvent),n=T?h.current:g.current;if(n&&jn(n,t))return;let r=m.current;if(!r)return;let i=T?f.current:p.current;if(!n||!i)return;let a=T?`y`:`x`,o=Pw(n,`margin`,a),s=Pw(i,`padding`,a),c=T?n.offsetHeight:n.offsetWidth,l=i.getBoundingClientRect(),u=T?e.clientY-l.top-c/2-s+o/2:e.clientX-l.left-c/2-s+o/2,d=T?r.scrollHeight:r.scrollWidth,v=T?r.clientHeight:r.clientWidth,x=(T?i.offsetHeight:i.offsetWidth)-c-s-o;if(x<=0)return;let S=u/x,C=d-v;b(),T?r.scrollTop=S*C:r.scrollLeft=D===`rtl`?-(1-S)*C:S*C,y({x:r.scrollLeft,y:r.scrollTop}),_(e)},onMouseDown(e){e.preventDefault()},onPointerUp:v,onPointerCancel:v,style:{position:`absolute`,touchAction:`none`,WebkitUserSelect:`none`,userSelect:`none`,visibility:O?`hidden`:void 0,...T?{top:0,bottom:`var(${Jw})`,insetInlineEnd:0,[dT]:`${S.height}px`}:{insetInlineStart:0,insetInlineEnd:`var(${Yw})`,bottom:0,[fT]:`${S.width}px`}}},M=Or(`div`,e,{ref:[t,T?f:p],state:E,props:[j,s],stateAttributesMapping:Ww});return A?(0,$.jsx)(bT.Provider,{value:i,children:M}):null}),CT=Q.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{computeThumbPosition:o}=aT(),{hasMeasuredScrollbar:s,viewportState:c}=Nw(),l=Q.useRef(null),u=Q.useRef(s);return Ae(()=>{if(typeof ResizeObserver>`u`)return;let e=!1,t=new ResizeObserver(()=>{!e&&(e=!0,!u.current)||o()});return l.current&&t.observe(l.current),()=>{t.disconnect()}},[o]),Or(`div`,e,{ref:[t,l],state:c,stateAttributesMapping:Ww,props:[{role:`presentation`,style:{minWidth:`fit-content`}},a]})}),wT=Q.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{thumbYRef:o,thumbXRef:s,handlePointerDown:c,handlePointerMove:l,handlePointerUp:u,scrollingX:d,scrollingY:f,hasMeasuredScrollbar:p}=Nw(),m=xT(),h=m===`vertical`;return Or(`div`,e,{ref:[t,h?o:s],state:{scrolling:h?f:d,orientation:m},props:[{onPointerDown:c,onPointerMove:l,onPointerUp:u,onPointerCancel:u,style:{visibility:p?void 0:`hidden`,...h?{height:`var(--scroll-area-thumb-height)`}:{width:`var(--scroll-area-thumb-width)`}}},a]})});function TT(e,t,n){let r=(Math.abs(t)-Math.abs(e))/Math.max(16,n);if(Math.abs(r)<.035)return null;let i=Math.min(.04,Math.abs(r)*.3),a=r>0,o=Math.sign(t||e);return{scaleY:1+(a?i:-i),scaleX:1+(a?-i/2:i/2),origin:(a?o>0:o<0)?`center top`:`center bottom`}}function ET(e,t,n){if(t<=0||Math.abs(n)<4)return null;let r=e<=0&&n<0,i=e>=t-1&&n>0;if(!r&&!i)return null;let a=Math.min(.06,Math.abs(n)/120*.06);return{scaleY:1-a,scaleX:1+a/2,origin:r?`center top`:`center bottom`}}var DT=(0,Q.forwardRef)(function({children:e,className:t,surface:n=!1,surfaceSize:r,surfaceDepth:i,screen:a=!1,...o},s){let c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),u=at();(0,Q.useEffect)(()=>{let e=c.current,t=e?.querySelector(`.caps-scroll-viewport`);if(!t||!e)return;let n=null,r,i=t.scrollTop,a=performance.now(),o=0,s=e=>{let t=l.current;if(!e||u||!t)return;n?.cancel(),t.style.transformOrigin=e.origin;let r=F(t),i=Hn(r,{ease:`outQuad`,duration:45}),a=cr(r,{bounce:.18,duration:180});n=pc(t,{scaleY:[{to:e.scaleY,...i},{to:1,...a}],scaleX:[{to:e.scaleX,...i},{to:1,...a}]})},d=(e,t)=>{let n=TT(o,e,t);o=e,s(n)},f=e=>{if(e.ctrlKey||Math.abs(e.deltaX)>Math.abs(e.deltaY))return;let n=e.deltaMode===1?16:e.deltaMode===2?t.clientHeight:1,i=ET(t.scrollTop,t.scrollHeight-t.clientHeight,e.deltaY*n);i&&(clearTimeout(r),o=0,s(i))},p=()=>{let e=performance.now(),n=e-a,s=n>100?16:Math.max(16,n),c=t.scrollTop-i;n>100&&(o=0),d(c/s,s),i=t.scrollTop,a=e,clearTimeout(r),r=setTimeout(()=>{d(0,32)},64)};return t.addEventListener(`scroll`,p,{passive:!0}),e.addEventListener(`wheel`,f,{passive:!0}),()=>{clearTimeout(r),n?.cancel(),l.current&&(l.current.style.transform=`none`),t.removeEventListener(`scroll`,p),e.removeEventListener(`wheel`,f)}},[a,n,u]);let d=(0,$.jsx)(gT,{render:a?(0,$.jsx)(Yn,{}):(0,$.jsx)(`div`,{}),...o,ref:s,className:`caps-scroll-viewport`,children:(0,$.jsx)(CT,{style:{minWidth:0},children:e})});return(0,$.jsxs)(tT,{render:n?(0,$.jsx)(Mn,{size:r??`md`,depth:i??`shallow`}):(0,$.jsx)(`div`,{}),ref:c,className:N(`caps-scroll-area`,t),children:[a?(0,$.jsx)(`div`,{className:`caps-display-gasket caps-scroll-display`,children:d}):d,(0,$.jsx)(Mn,{size:`sm`,depth:`deep`,placement:`embedded`,className:`caps-scroll-track-surface`,children:(0,$.jsx)(ST,{className:`caps-scroll-track`,children:(0,$.jsx)(wT,{className:`caps-scroll-thumb`,children:(0,$.jsx)(`span`,{className:`caps-scroll-thumb-surface`,ref:l})})})})]})}),OT=Q.createContext(void 0);function kT(e){let t=Q.useContext(OT);if(t===void 0&&!e)throw Error(U(72));return t}var AT={...Bn,disabled:e=>e.disabled,instantType:e=>e.instantType,isInstantPhase:e=>e.isInstantPhase,trackCursorAxis:e=>e.trackCursorAxis,disableHoverablePopup:e=>e.disableHoverablePopup,lastOpenChangeReason:e=>e.openChangeReason,closeOnClick:e=>e.closeOnClick,appliedTriggerProps:(e,t)=>t?e.activeTriggerProps:void 0,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin},jT=class extends or{constructor(e,t,n){let r=new dr;super(MT(e,r,t,n),NT(r),AT)}setOpen=(e,t)=>{yr(this,e,t,{extraState:{openChangeReason:t.reason}})};cancelPendingOpen(e){this.state.floatingRootContext.dispatchOpenChange(!1,Ar(fn,e))}};function MT(e,t,n,r=!1){return{...hr(t,n,r),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:`none`,disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,adaptiveOrigin:void 0,...e}}function NT(e){return{popupRef:Q.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}var PT=vn(function(e){let{disabled:t=!1,defaultOpen:n=!1,open:r,disableHoverablePopup:i=!1,trackCursorAxis:a=`none`,actionsRef:o,onOpenChange:s,onOpenChangeComplete:c,handle:l,triggerId:u,defaultTriggerId:d=null,children:f}=e,p=Dt((e,t)=>new jT({open:n,openProp:r,activeTriggerId:d,triggerIdProp:u},e,t));p.useControlledProp(`openProp`,r),p.useControlledProp(`triggerIdProp`,u),p.useContextCallback(`onOpenChange`,s),p.useContextCallback(`onOpenChangeComplete`,c);let m=p.useState(`open`),h=!t&&m,g=p.useState(`activeTriggerId`),_=p.useState(`mounted`),v=p.useState(`payload`);p.useSyncedValues({trackCursorAxis:a,disableHoverablePopup:i,disabled:t}),Fn(p,{closeOnActiveTriggerUnmount:!0});let{forceUnmount:y,transitionStatus:b}=pn(h,p),x=p.useState(`isInstantPhase`),S=p.useState(`instantType`),C=p.useState(`lastOpenChangeReason`),w=Q.useRef(null);Ae(()=>{m&&t&&p.setOpen(!1,Ar(zn))},[m,t,p]),Ae(()=>{b===`ending`&&C===`none`||b!==`ending`&&x?(S!==`delay`&&(w.current=S),p.set(`instantType`,`delay`)):w.current!==null&&(p.set(`instantType`,w.current),w.current=null)},[b,x,C,S,p]),Ae(()=>{h&&(g??p.set(`payload`,void 0))},[p,g,h]),Q.useImperativeHandle(o,()=>({unmount:y,close:()=>p.setOpen(!1,Ar(Mt))}),[y,p]);let T=h||_||!t&&a!==`none`;return(0,$.jsxs)(OT.Provider,{value:p,children:[l&&(0,$.jsx)(An,{handle:l,store:p}),T&&(0,$.jsx)(FT,{store:p,disabled:t,trackCursorAxis:a}),typeof f==`function`?f({payload:v}):f]})});function FT({store:e,disabled:t,trackCursorAxis:n}){let r=e.useState(`floatingRootContext`),i=Nr(r,{enabled:!t,referencePress:()=>e.select(`closeOnClick`)}),a=lv(r,{enabled:!t&&n!==`none`,axis:n===`none`?void 0:n}),o=Q.useMemo(()=>qe(a.reference,i.reference),[a.reference,i.reference]);return cn(e,{activeTriggerProps:o,inactiveTriggerProps:o,popupProps:i.floating??we}),null}var IT=Q.createContext(void 0);function LT(){let e=Q.useContext(IT);if(e===void 0)throw Error(U(70));return e}var RT=Q.forwardRef(function(e,t){let{children:n,container:r,className:i,render:a,style:o,...s}=e,{node:c,subtree:l}=Sn({container:r,ref:t,componentProps:e,elementProps:s});return!l&&!c?null:(0,$.jsxs)(Q.Fragment,{children:[l,c&&vv.createPortal(n,c)]})}),zT=Q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return kT().useState(`mounted`)||n?(0,$.jsx)(IT.Provider,{value:n,children:(0,$.jsx)(RT,{ref:t,...r})}):null}),BT=Q.createContext(void 0);function VT(){let e=Q.useContext(BT);if(e===void 0)throw Error(U(71));return e}var HT=Q.forwardRef(function(e,t){let{render:n,className:r,anchor:i,positionMethod:a=`absolute`,side:o=`top`,align:s=`center`,sideOffset:c=0,alignOffset:l=0,collisionBoundary:u=`clipping-ancestors`,collisionPadding:d=5,arrowPadding:f=5,sticky:p=!1,disableAnchorTracking:m=!1,collisionAvoidance:h=k,style:g,..._}=e,v=kT(),y=LT(),b=v.useState(`open`),x=v.useState(`mounted`),S=v.useState(`trackCursorAxis`),C=v.useState(`disableHoverablePopup`),w=v.useState(`floatingRootContext`),T=v.useState(`instantType`),E=v.useState(`transitionStatus`),D=_b({anchor:i,positionMethod:a,floatingRootContext:w,mounted:x,side:o,sideOffset:c,align:s,alignOffset:l,collisionBoundary:u,collisionPadding:d,sticky:p,arrowPadding:f,disableAnchorTracking:m,keepMounted:y,collisionAvoidance:h,adaptiveOrigin:v.useState(`adaptiveOrigin`)}),O=Ob(e,Q.useMemo(()=>({open:b,side:D.side,align:D.align,anchorHidden:D.anchorHidden,instant:S===`none`?T:`tracking-cursor`}),[b,D.side,D.align,D.anchorHidden,S,T]),{styles:D.positionerStyles,transitionStatus:E,props:_,refs:[t,v.useStateSetter(`positionerElement`)],hidden:!x,inert:!b||S===`both`||C});return(0,$.jsx)(BT.Provider,{value:D,children:O})}),UT=Q.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,o=kT(),{side:s,align:c}=VT(),l=o.useState(`open`),u=o.useState(`instantType`),d=o.useState(`transitionStatus`),f=o.useState(`popupProps`),p=o.useState(`floatingRootContext`),m=o.useState(`disabled`),h=o.useState(`closeDelay`);Ot({open:l,ref:o.context.popupRef,onComplete(){l&&o.context.onOpenChangeComplete?.(!0)}}),_v(p,{enabled:!m,closeDelay:h});let g=o.useStateSetter(`popupElement`);return Or(`div`,e,{state:{open:l,side:s,align:c,instant:u,transitionStatus:d},ref:[t,o.context.popupRef,g],props:[Ht,f,Hy(d),a],stateAttributesMapping:Et})}),WT={open:0,warm:!1,cooling:void 0},GT=600,KT=(0,Q.createContext)(null);function qT(){let e=(0,Q.useContext)(KT);if(!e)throw Error(`Tooltip parts must be used inside <Tooltip>`);return e}var JT=(0,Q.forwardRef)(function({children:e,className:t,defaultOpen:n=!1,delayDuration:r=300,onOpenChange:i,open:a,side:o=`top`,...s},c){let l=(0,Q.useRef)(null),[u,d]=(0,Q.useState)(n),[f,p]=(0,Q.useState)(!1),m=a??u;(0,Q.useEffect)(()=>{if(m)return WT.open+=1,WT.warm=!0,clearTimeout(WT.cooling),()=>{--WT.open,!(WT.open>0)&&(WT.cooling=setTimeout(()=>{WT.warm=!1},GT))}},[m]);let h=`${(0,Q.useId)()}-content`,g=(0,Q.useRef)(null),_=()=>{g.current!==null&&(clearTimeout(g.current),g.current=null)},v=e=>{_(),a===void 0&&d(e),i?.(e)};return ne(()=>{v(!1)}),(0,Q.useEffect)(()=>_,[]),(0,$.jsx)(KT.Provider,{value:{arrivedWarm:f,cancelClose:_,contentId:h,open:m,scheduleClose:()=>{_(),m&&(g.current=setTimeout(()=>{v(!1)},0))},scheduleOpen:()=>{if(_(),m)return;let e=WT.warm;g.current=setTimeout(()=>{p(e),v(!0)},e?0:Math.max(0,r))},side:o,trigger:l},children:(0,$.jsx)(PT,{open:m,onOpenChange:v,children:(0,$.jsx)(`span`,{...s,className:N(`relative inline-flex`,t),ref:c,children:e})})})}),YT=(0,Q.forwardRef)(function({asChild:e=!1,children:t,className:n,onBlur:r,onFocus:i,onPointerEnter:a,onPointerLeave:o,...s},c){let l=qT(),u=(0,Q.useCallback)(e=>{l.trigger.current=e},[l.trigger]);(0,Q.useImperativeHandle)(c,()=>l.trigger.current);let{"aria-describedby":d,...f}=s,p={...f,"aria-describedby":[d,l.open?l.contentId:void 0].filter(Boolean).join(` `)||void 0,"data-state":l.open?`open`:`closed`,onBlur:e=>{r?.(e),e.defaultPrevented||l.scheduleClose()},onFocus:e=>{i?.(e),e.defaultPrevented||l.scheduleOpen()},onPointerEnter:e=>{a?.(e),e.defaultPrevented||l.scheduleOpen()},onPointerLeave:e=>{o?.(e),e.defaultPrevented||l.scheduleClose()}};return e?(0,$.jsx)(se,{...p,className:N(n),ref:u,children:t}):(0,$.jsx)(`button`,{...p,className:N(`btn`,n),ref:u,type:s.type??`button`,children:t})}),XT=(0,Q.forwardRef)(function({children:e,className:t,onPointerEnter:n,onPointerLeave:r,...i},a){let o=qT(),s=fe(`tooltip`),[c,l]=(0,Q.useState)(null);return(0,Q.useImperativeHandle)(a,()=>c,[c]),(0,Q.useLayoutEffect)(()=>{let e=c;if(!o.open||!e||!f(e))return;let t=F(e),n=o.arrivedWarm?0:t.distance,r={bottom:`0 ${String(-n)}px`,left:`${String(n)}px 0`,right:`${String(-n)}px 0`,top:`0 ${String(n)}px`}[o.side],i=e.animate([{opacity:0,translate:r},{opacity:1,translate:`0 0`}],{duration:o.arrivedWarm?t.fast:t.normal,easing:tt(t,t.ease),composite:`add`});return()=>{i.cancel()}},[c,o.open,o.arrivedWarm,o.side]),!o.open||!s?null:(0,$.jsx)(zT,{container:s,children:(0,$.jsx)(HT,{anchor:o.trigger,side:o.side,sideOffset:8,collisionPadding:8,collisionBoundary:s===document.body?void 0:s,className:`pointer-events-auto z-(--stipe-layer-tooltip)`,children:(0,$.jsx)(UT,{...i,"aria-live":`polite`,className:N(`pointer-events-auto max-w-(--container-xs) rounded-box bg-base-content px-md py-sm text-xs text-base-100 shadow-lg`,t),id:o.contentId,onPointerEnter:e=>{n?.(e),e.defaultPrevented||o.cancelClose()},onPointerLeave:e=>{r?.(e),e.defaultPrevented||o.scheduleClose()},ref:l,role:`tooltip`,children:e})})})}),ZT={needs_you:`Waiting for you`,running:`Working`,errored:`Failed`,done:`Done`},QT={needs_you:0,errored_unseen:1,running:2,recent:3};function $T(e){return e===`running`||e===`needs_you`}function eE(e,t){return e!==void 0&&(t===void 0||e>t)}function tE(e,t){switch(e){case`needs_you`:return`needs_you`;case`running`:return`running`;case`errored`:return t?`errored_unseen`:`recent`;case`done`:return`recent`}}function nE(e,t){return QT[e.tier]-QT[t.tier]||(t.settledAt??t.createdAt)-(e.settledAt??e.createdAt)||e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId)}var rE=[`Needs you`,`Working`,`Ready`,`Finished`];function iE(e){return e.tier===`running`?`Working`:e.shelf===`active`?`Needs you`:e.ready?`Ready`:`Finished`}function aE(e){return{key:dE(e.agentId,e.sessionId),shelf:iE(e),attention:e.tier===`needs_you`||e.tier===`errored_unseen`?`${e.tier}:${String(e.settledAt??e.createdAt)}`:null}}function oE(e,t,n){let r=new Map(t.map(e=>[dE(e.agentId,e.sessionId),e]));if(e!==null&&e.length>0&&n.held)return e;let i=[...t].sort((e,t)=>(t.settledAt??t.createdAt)-(e.settledAt??e.createdAt)||e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId)),a=new Map(e?.map(e=>[e.key,e])),o=i.map(aE).filter(e=>{let t=a.get(e.key);return t===void 0||e.key!==n.openKey&&e.attention!==null&&e.attention!==t.attention}),s=new Set(o.map(e=>e.key)),c=a.get(n.openKey??``),l=c===void 0?-1:(e??[]).filter(e=>e.shelf===c.shelf).findIndex(e=>e.key===c.key),u=rE.flatMap(t=>{let a;a=e===null||n.reorder?i.map(aE).filter(e=>e.shelf===t):[...o.filter(e=>e.shelf===t),...e.filter(e=>e.shelf===t&&!s.has(e.key)).flatMap(e=>{let t=r.get(e.key);return t===void 0?[]:[{...e,attention:aE(t).attention}]})];let u=c===void 0?void 0:r.get(c.key);return c!==void 0&&u!==void 0&&(a=a.filter(e=>e.key!==c.key),c.shelf===t&&a.splice(Math.min(l,a.length),0,{...c,attention:aE(u).attention})),a});return e!==null&&u.length===e.length&&u.every((t,n)=>t.key===e[n]?.key&&t.shelf===e[n]?.shelf&&t.attention===e[n]?.attention)?e:u}function sE(e,t){switch(e.kind){case`idle`:case`waiting_for_you`:return t===`needs_you`?`needs_you`:`done`;case`error`:return`errored`;default:return`running`}}function cE(e,t,n=null,r){let i=new Set(e.map(e=>e.agentId));return lE(t.filter(e=>!(`kind`in e)&&i.has(e.agentId)&&(n===null||e.agentId===n)),r)}function lE(e,t){let n=[],r=[];for(let i of e){if(`kind`in i)continue;if(i.state===`unavailable`){r.push({agentId:i.agentId,sessionId:i.sessionId});continue}let e=eE(i.settledAt,i.visitedAt),a=t?.agentId===i.agentId&&t.sessionId===i.sessionId?t.state:void 0,o=a?sE(a,i.state):i.state,s=a?a.kind===`idle`:o===`done`&&i.settledAt===void 0,c=tE(o,e);n.push({...i,state:o,ready:s,unseen:e,tier:c,shelf:c===`recent`?`settled`:`active`})}return n.sort(nE),{active:n.filter(e=>e.shelf===`active`),settled:n.filter(e=>e.shelf===`settled`),unavailable:r.sort((e,t)=>e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId))}}function uE(e){return[...e.active,...e.settled].filter(e=>!(e.title===``&&e.ready))}function dE(e,t){return`${e}\u0000${t}`}function fE(e){return e.name}var pE=`Connect a model first`;function mE({children:e}){return(0,$.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:e})}function hE({open:e,agents:t,agentActivity:n,agentFilterId:r,websitesSelected:i,websitesVisible:a,canCreate:o,modelsMissing:s,createOpen:c,onAll:l,onWebsites:u,onAgent:d,onCreate:f}){let[p,m]=(0,Q.useState)(null),h=`grove-rail-cell relative size-12 rounded-field p-0`,g=r===null&&!(i&&a);return(0,$.jsxs)(`nav`,{id:`grove-agent-rail`,"aria-label":`Agents`,className:`grove-rail min-h-0 w-16 flex-none flex-col items-center gap-1 border-r border-base-300 py-2 ${e?`flex`:`flex @min-[900px]/grove:hidden`}`,children:[(0,$.jsx)(W,{variant:`ghost`,"aria-label":`All Agents`,"aria-pressed":g,className:`${h} text-xs ${g?`bg-base-300`:``}`,onClick:l,children:(0,$.jsx)(mE,{children:`All`})}),a?(0,$.jsx)(W,{variant:`ghost`,"aria-label":`Websites`,"aria-pressed":i,className:`${h} ${i?`bg-base-300`:``}`,onClick:u,children:(0,$.jsx)(mE,{children:(0,$.jsx)(Un,{name:`internet`,size:28})})}):null,(0,$.jsx)(DT,{className:`w-full flex-1`,style:{width:`100%`},children:(0,$.jsx)(`div`,{className:`flex flex-col items-center gap-1 py-1`,children:t.map(e=>(0,$.jsx)(W,{variant:`ghost`,"aria-label":fE(e),title:fE(e),"aria-pressed":r===e.agentId&&!i,"data-agent-id":e.agentId,className:`${h} ${r===e.agentId&&!i?`bg-base-300`:``}`,onPointerEnter:()=>{m(e.agentId)},onPointerLeave:()=>{m(null)},onFocus:()=>{m(e.agentId)},onBlur:()=>{m(null)},onClick:()=>{d(e.agentId)},children:(0,$.jsx)(mE,{children:(0,$.jsx)(Ln,{activity:n.get(e.agentId)??(p===e.agentId?`thinking`:`idle`),avatar:e.avatar,name:fE(e),size:32})})},e.agentId))})}),o?(0,$.jsxs)(JT,{side:`right`,children:[(0,$.jsx)(YT,{asChild:!0,children:(0,$.jsx)(W,{variant:`ghost`,"aria-label":`New Agent`,"aria-disabled":s,"aria-expanded":c,"aria-haspopup":`dialog`,className:`${h} mt-auto ${s?`opacity-50`:``}`,onClick:f,children:(0,$.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:(0,$.jsx)(L,{size:20})})})}),s?(0,$.jsx)(XT,{children:pE}):null]}):null]})}function gE({app:e}){let[t,n]=(0,Q.useState)(null),r=Uc({queryKey:Vg.of(e,`team-inbox-notices`,t),enabled:e!==null&&(e.capabilities.has(Zs)||e.capabilities.has(qs)),queryFn:async()=>{if(!e)throw Error(`No App connection`);let n=await uc(e.capabilities);try{return await Og(n,t)}finally{await n.close()}}});return!r.isError&&!r.data?.items.length?null:(0,$.jsx)(`section`,{"aria-label":`Team notices`,className:`min-h-0 shrink-0`,children:(0,$.jsxs)(DT,{className:`max-h-52 border-b border-base-300`,children:[r.isError?(0,$.jsx)(`p`,{role:`alert`,className:`text-sm`,children:`Team notices unavailable.`}):(0,$.jsx)(Ge,{density:`compact`,className:`px-3 py-2`,children:r.data.items.map(e=>(0,$.jsx)(b,{children:(0,$.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-[var(--spacing-xs)]`,children:[(0,$.jsx)(_r,{className:`col-span-2 grid grid-cols-subgrid`,size:`compact`,tone:`warning`,label:`kind`in e?`Seller closed`:`Installed App safety notice`}),(0,$.jsx)(`p`,{className:`m-0 col-start-2 text-sm [overflow-wrap:anywhere]`,children:`kind`in e?`${e.sellerName} closed. Your installation of ${e.displayName} continues; no new purchases are available.`:`${e.displayName} was removed. Fungi will disable it on your Team.`})]})},e.dispositionId))}),r.data?.next?(0,$.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>{n(r.data.next)},children:`Older notices`}):null,t===null?null:(0,$.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>{n(null)},children:`Newest notices`})]})})}var _E=900;function vE(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let r=e=>{n(e===0||e>=_E)};r(t.getBoundingClientRect().width);let i=`ResizeObserver`in globalThis?new ResizeObserver(([e])=>{r(e.contentRect.width)}):void 0;return i?.observe(t),()=>{i?.disconnect()}},[e]),t}function yE({open:e,onOpenChange:t,returnFocus:n,desktop:r,children:i}){let[a,o]=(0,Q.useState)(null);return(0,$.jsxs)(d,{open:r||e,modal:!r,disablePointerDismissal:r,onOpenChange:e=>{r||t(e)},children:[(0,$.jsx)(`div`,{ref:o,className:`contents`}),(0,$.jsxs)(oe,{container:a,keepMounted:!0,className:`contents`,children:[r?null:(0,$.jsx)(et,{className:`grove-nav-scrim z-30 bg-base-200`}),(0,$.jsx)(er,{id:`grove-nav`,role:r?`presentation`:`dialog`,"aria-label":r?void 0:`Agents and conversations`,initialFocus:!r&&void 0,finalFocus:!r&&n,className:`grove-nav min-h-0 flex-none rounded-none p-0 overflow-visible max-w-none max-h-none ${r?`static flex w-auto shadow-none`:`fixed inset-y-0 left-0 z-40 w-[min(22rem,88cqw)] data-[open]:flex`}`,children:i})]})]})}function bE({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function xE(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var SE=[],CE=0,{link:wE,unlink:TE,propagate:EE,checkDirty:DE,shallowPropagate:OE}=bE({update(e){return e._update()},notify(e){SE[AE++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,PE(e))}}),kE=0,AE=0,jE,ME=0;function NE(e){try{++ME,e()}finally{--ME||FE()}}function PE(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=TE(n,e)}function FE(){if(!(ME>0)){for(;kE<AE;){let e=SE[kE];SE[kE++]=void 0,e.notify()}kE=0,AE=0}}function IE(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return jE!==void 0&&wE(i,jE,CE),i._snapshot},subscribe(e){let t=xE(e),n={current:!1},r=LE(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=jE,o=t?.compare??Object.is;if(n)jE=i,++CE,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{jE=a,n&&(i.flags&=-5),PE(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&DE(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&OE(e)}}else e&32&&(i.flags=e&-33);return jE!==void 0&&wE(i,jE,CE),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(EE(e),OE(e),FE())}},i}function LE(e){let t=()=>{let t=jE;jE=n,++CE,n.depsTail=void 0,n.flags=6;try{return e()}finally{jE=t,n.flags&=-5,PE(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&DE(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,PE(this)}};return t(),n}var RE=class{constructor(e,t){this.atom=IE(e),this.get=this.get.bind(this),this.setState=this.setState.bind(this),this.subscribe=this.subscribe.bind(this),t&&(this.actions=t(this))}setState(e){this.atom.set(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(xE(e))}},zE=class{constructor(e){this.atom=IE(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(xE(e))}};function BE(e,t){return typeof e==`function`?new zE(e):t?new RE(e,t):new RE(e)}var VE=class{constructor(e,t){this.fn=e,this.options=t,this.lastExecutionTime=0,this.isPending=!1,this.maybeExecute=(...e)=>{let t=Date.now()-this.lastExecutionTime;if(this.options.leading&&t>=this.options.wait)this.execute(...e);else if(this.lastArgs=e,!this.timeoutId&&this.options.trailing){let e=this.options.wait-t;this.isPending=!0,this.timeoutId=setTimeout(()=>{this.lastArgs!==void 0&&this.execute(...this.lastArgs)},e)}},this.execute=(...e)=>{this.fn(...e),this.options.onExecute?.(e,this),this.lastExecutionTime=Date.now(),this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.flush=()=>{this.isPending&&this.lastArgs&&this.execute(...this.lastArgs)},this.cancel=()=>{this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.clearTimeout=()=>{this.timeoutId&&=(clearTimeout(this.timeoutId),void 0)},this.options.leading===void 0&&this.options.trailing===void 0&&(this.options.leading=!0,this.options.trailing=!0)}};function HE(e,t){return new VE(e,t).maybeExecute}var UE=class{#e=!0;#t;#n;#r;#i;#a;#o;#s;#c=0;#l=5;#u=!1;#d=!1;#f=null;#p=()=>{this.debugLog(`Connected to event bus`),this.#a=!0,this.#u=!1,this.debugLog(`Emitting queued events`,this.#i),this.#i.forEach(e=>this.emitEventToBus(e)),this.#i=[],this.stopConnectLoop(),this.#n().removeEventListener(`tanstack-connect-success`,this.#p)};#m=()=>{if(this.#c<this.#l){this.#c++,this.dispatchCustomEvent(`tanstack-connect`,{});return}this.#n().removeEventListener(`tanstack-connect`,this.#m),this.#d=!0,this.debugLog(`Max retries reached, giving up on connection`),this.stopConnectLoop()};#h=()=>{this.#u||(this.#u=!0,this.#n().addEventListener(`tanstack-connect-success`,this.#p),this.#m())};constructor({pluginId:e,debug:t=!1,enabled:n=!0,reconnectEveryMs:r=300}){this.#t=e,this.#e=n,this.#n=this.getGlobalTarget,this.#r=t,this.debugLog(` Initializing event subscription for plugin`,this.#t),this.#i=[],this.#a=!1,this.#d=!1,this.#o=null,this.#s=r}startConnectLoop(){this.#o!==null||this.#a||(this.debugLog(`Starting connect loop (every ${this.#s}ms)`),this.#o=setInterval(this.#m,this.#s))}stopConnectLoop(){this.#u=!1,this.#o!==null&&(clearInterval(this.#o),this.#o=null,this.#i=[],this.debugLog(`Stopped connect loop`))}debugLog(...e){this.#r&&console.log(`🌴 [tanstack-devtools:${this.#t}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<`u`&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog(`Using global event target`),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<`u`&&window.addEventListener!==void 0)return this.debugLog(`Using window as event target`),window;let e=typeof EventTarget<`u`?new EventTarget:void 0;return e===void 0||e.addEventListener===void 0?(this.debugLog(`No event mechanism available, running in non-web environment`),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog(`Using new EventTarget as fallback`),e)}getPluginId(){return this.#t}dispatchCustomEventShim(e,t){try{let n=new Event(e,{detail:t});this.#n().dispatchEvent(n)}catch{this.debugLog(`Failed to dispatch shim event`)}}dispatchCustomEvent(e,t){try{this.#n().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog(`Emitting event to client bus`,e),this.dispatchCustomEvent(`tanstack-dispatch-event`,e)}createEventPayload(e,t){return{type:`${this.#t}:${e}`,payload:t,pluginId:this.#t}}emit(e,t){if(!this.#e){this.debugLog(`Event bus client is disabled, not emitting event`,e,t);return}if(this.#f&&(this.debugLog(`Emitting event to internal event target`,e,t),this.#f.dispatchEvent(new CustomEvent(`${this.#t}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#d){this.debugLog(`Previously failed to connect, not emitting to bus`);return}if(!this.#a){this.debugLog(`Bus not available, will be pushed as soon as connected`),this.#i.push(this.createEventPayload(e,t)),typeof CustomEvent<`u`&&!this.#u&&(this.#h(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,n){let r=n?.withEventTarget??!1,i=`${this.#t}:${e}`;if(r&&(this.#f||=new EventTarget,this.#f.addEventListener(i,e=>{t(e.detail)})),!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`,i),()=>{};let a=e=>{this.debugLog(`Received event from bus`,e.detail),t(e.detail)};return this.#n().addEventListener(i,a),this.debugLog(`Registered event to bus`,i),()=>{r&&this.#f?.removeEventListener(i,a),this.#n().removeEventListener(i,a)}}onAll(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}onAllPluginEvents(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;this.#t&&n.pluginId!==this.#t||e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}},WE=new class extends UE{constructor(){super({pluginId:`form-devtools`,reconnectEveryMs:1e3})}};function GE(e,t){return typeof e==`function`?e(t):e}function KE(e,t){return eD(t).reduce((e,t)=>{if(e===null)return null;if(e!==void 0)return e[t]},e)}function qE(e,t,n){let r=eD(t);function i(e){if(!r.length)return GE(n,e);let t=r.shift();if(typeof t==`string`||typeof t==`number`&&!Array.isArray(e))return typeof e==`object`?(e===null&&(e={}),{...e,[t]:i(e[t])}):{[t]:i()};if(Array.isArray(e)&&typeof t==`number`){let n=e.slice(0,t);return[...n.length?n:Array(t),i(e[t]),...e.slice(t+1)]}return[...Array(t),i()]}return i(e)}function JE(e,t){let n=eD(t);function r(e){if(!e)return;if(n.length===1){let t=n[0];if(Array.isArray(e)&&typeof t==`number`)return e.filter((e,n)=>n!==t);let{[t]:r,...i}=e;return i}let t=n.shift();if((typeof t==`string`||typeof t==`number`&&!Array.isArray(e))&&typeof e==`object`)return{...e,[t]:r(e[t])};if(typeof t==`number`&&Array.isArray(e)){if(t>=e.length)return e;let n=e.slice(0,t);return[...n.length?n:Array(t),r(e[t]),...e.slice(t+1)]}throw Error(`It seems we have created an infinite loop in deleteBy. `)}return r(e)}var YE=46,XE=91,ZE=93,QE=48,$E=57;function eD(e){if(Array.isArray(e))return[...e];if(typeof e!=`string`)throw Error(`Path must be a string.`);let t=e.length,n=[],r=+(t>0&&e.charCodeAt(0)===XE),i=!0,a=-1;for(let o=r;o<=t;o++){let s=o<t?e.charCodeAt(o):-1;if(o===t||s===YE||s===XE||s===ZE){let t=o-r;if(t>0){let a=i&&(t===1||e.charCodeAt(r)!==QE),s=e.slice(r,o);if(a){let e=parseInt(s,10);t<=15||String(e)===s?n.push(e):n.push(s)}else n.push(s)}else a!==ZE&&(a!==-1||s!==ZE)&&(a!==s||s!==YE&&s!==XE)&&n.push(``);r=o+1,i=!0}else(s<QE||s>$E)&&(i=!1);a=s}return n.length||n.push(``),n}function tD(e){return!(Array.isArray(e)&&e.length===0)}function nD(e,t){return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!1},runValidation:e=>e.validators.filter(Boolean).map(e=>({cause:e.cause,validate:e.fn}))})}function rD(e,t){let{asyncDebounceMs:n}=t,{onBlurAsyncDebounceMs:r,onChangeAsyncDebounceMs:i,onDynamicAsyncDebounceMs:a}=t.validators||{},o=n??0;return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!0},runValidation:t=>t.validators.filter(Boolean).map(t=>{let n=t?.cause||e,s=o;switch(n){case`change`:s=i??o;break;case`blur`:s=r??o;break;case`dynamic`:s=a??o;break;case`submit`:s=0}return e===`submit`&&(s=0),{cause:n,validate:t.fn,debounceMs:s}})})}var iD=e=>!!e&&typeof e==`object`&&`fields`in e;function aD(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length||n.length===0&&!Array.isArray(e)&&!Array.isArray(t)&&(Object.getPrototypeOf(e)!==Object.prototype||Object.getPrototypeOf(t)!==Object.prototype))return!1;for(let i of n)if(!r.includes(i)||!aD(e[i],t[i]))return!1;return!0}var oD=({newFormValidatorError:e,isPreviousErrorFromFormValidator:t,previousErrorValue:n})=>e?{newErrorValue:e,newSource:`form`}:t?{newErrorValue:void 0,newSource:void 0}:n?{newErrorValue:n,newSource:`field`}:{newErrorValue:void 0,newSource:void 0},sD=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:`field`}:e?{newErrorValue:e,newSource:`form`}:{newErrorValue:void 0,newSource:void 0};function cD(e,t){return e==null?t:{...e,...t}}for(var lD=256,uD=[],dD;lD--;)uD[lD]=(lD+256).toString(16).substring(1);function fD(){let e=0,t,n=``;if(!dD||lD+16>256){for(dD=Array(256),e=256;e--;)dD[e]=256*Math.random()|0;e=0,lD=0}for(;e<16;e++)t=dD[lD+e],n+=e===6?uD[t&15|64]:e===8?uD[t&63|128]:uD[t],e&1&&e>1&&e<11&&(n+=`-`);return lD++,n}var pD=HE(e=>WE.emit(`form-state`,{id:e.formId,state:e.store.state}),{wait:300});function mD(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let t=[];for(let n=0;n<e.length;n++)t[n]=mD(e[n]);return t}if(e instanceof Map){let t=new Map;return e.forEach((e,n)=>{t.set(n,mD(e))}),t}if(e instanceof Set){let t=new Set;return e.forEach(e=>{t.add(mD(e))}),t}let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=mD(e[n]));return t}function hD(e,t){return t===e||t.startsWith(`${e}.`)||t.startsWith(`${e}[`)}var gD=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let t=e.event.async,n=t?void 0:{fn:e.validators.onMount,cause:`mount`},r={fn:t?e.validators.onChangeAsync:e.validators.onChange,cause:`change`},i={fn:t?e.validators.onBlurAsync:e.validators.onBlur,cause:`blur`},a={fn:t?e.validators.onSubmitAsync:e.validators.onSubmit,cause:`submit`},o=t?void 0:{fn:()=>void 0,cause:`server`};switch(e.event.type){case`mount`:return e.runValidation({validators:[n],form:e.form});case`submit`:return e.runValidation({validators:[r,i,a,o],form:e.form});case`server`:return e.runValidation({validators:[],form:e.form});case`blur`:return e.runValidation({validators:[i,o],form:e.form});case`change`:return e.runValidation({validators:[r,o],form:e.form});default:throw Error(`Unknown validation event type: ${e.event.type}`)}};function _D(e,t){let n=new Map;for(let r of e){let e=r.path??[],i=t,a=``;for(let t=0;t<e.length;t++){let n=e[t];if(n===void 0)continue;let r=typeof n==`object`?n.key:n,o=Number(r);a+=Array.isArray(i)&&!Number.isNaN(o)?`[${o}]`:(t>0?`.`:``)+String(r),i=typeof i==`object`&&i?i[r]:void 0}n.set(a,(n.get(a)??[]).concat(r))}return Object.fromEntries(n)}var vD=(e,t)=>{let n=_D(e,t);return{form:n,fields:n}},yD={validate({value:e,validationSource:t},n){let r=n[`~standard`].validate(e);if(r instanceof Promise)throw Error(`async function passed to sync validator`);if(r.issues)return t===`field`?r.issues:vD(r.issues,e)},async validateAsync({value:e,validationSource:t},n){let r=await n[`~standard`].validate(e);if(r.issues)return t===`field`?r.issues:vD(r.issues,e)}},bD=e=>!!e&&`~standard`in e,xD={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{},_arrayVersion:0,_pendingValidationsCount:0};function SD(e){function t(t){let n=e.getFieldMeta(t)??xD;e.setFieldMeta(t,{...n,_arrayVersion:(n._arrayVersion||0)+1})}function n(n,r,i){t(n);let a=s(n,r,`move`,i),c=Math.min(r,i),u=Math.max(r,i);for(let e=c;e<=u;e++)a.push(o(n,e));let d=Object.keys(e.fieldInfo).reduce((t,i)=>(i.startsWith(o(n,r))&&t.set(i,e.getFieldMeta(i)),t),new Map);l(a,r<i?`up`:`down`),Object.keys(e.fieldInfo).filter(e=>e.startsWith(o(n,i))).forEach(t=>{let a=t.replace(o(n,i),o(n,r)),s=d.get(a);s&&e.setFieldMeta(t,s)})}function r(e,n){t(e),l(s(e,n,`remove`),`up`)}function i(n,r,i){t(n),s(n,r,`swap`,i).forEach(t=>{if(!t.toString().startsWith(o(n,r)))return;let a=t.toString().replace(o(n,r),o(n,i)),[s,c]=[e.getFieldMeta(t),e.getFieldMeta(a)];s&&e.setFieldMeta(a,s),c&&e.setFieldMeta(t,c)})}function a(n,r){t(n);let i=s(n,r,`insert`);l(i,`down`),i.forEach(t=>{t.toString().startsWith(o(n,r))&&e.setFieldMeta(t,u())})}function o(e,t){return`${e}[${t}]`}function s(t,n,r,i){let a=[o(t,n)];switch(r){case`swap`:a.push(o(t,i));break;case`move`:{let[e,r]=[Math.min(n,i),Math.max(n,i)];for(let n=e;n<=r;n++)a.push(o(t,n));break}default:{let r=e.getFieldValue(t),i=Array.isArray(r)?r.length:0;for(let e=n+1;e<i;e++)a.push(o(t,e));break}}return Object.keys(e.fieldInfo).filter(e=>a.some(t=>e.startsWith(t)))}function c(e,t){return e.replace(/\[(\d+)\]/,(e,n)=>{let r=parseInt(n,10);return`[${t===`up`?r+1:Math.max(0,r-1)}]`})}function l(t,n){(n===`up`?t:[...t].reverse()).forEach(t=>{let r=c(t.toString(),n),i=e.getFieldMeta(r);i?e.setFieldMeta(t,i):e.setFieldMeta(t,u())})}let u=()=>xD;return{bumpArrayVersion:t,handleArrayMove:n,handleArrayRemove:r,handleArraySwap:i,handleArrayInsert:a}}function CD(e){return{values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},formGroupStateBase:e.formGroupStateBase??{},isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var wD=class{constructor(e){this.options={},this.fieldInfo={},this.formGroupApis=new Set,this.mount=()=>{let e=this.store.subscribe(()=>{pD(this)}),t=WE.on(`request-form-state`,e=>{e.payload.id===this._formId&&WE.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}),n=WE.on(`request-form-reset`,e=>{e.payload.id===this._formId&&this.reset()}),r=WE.on(`request-form-force-submit`,e=>{e.payload.id===this._formId&&(this._devtoolsSubmissionOverride=!0,this.handleSubmit(),this._devtoolsSubmissionOverride=!1)}),i=()=>{r(),n(),t(),e.unsubscribe(),WE.emit(`form-unmounted`,{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});let{onMount:a}=this.options.validators||{};return WE.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options}),a&&this.validateSync(`mount`),i},this.update=e=>{if(!e)return;let t=this.options;this.options=e;let n=e.defaultValues&&!aD(e.defaultValues,t.defaultValues)&&!this.state.isTouched,r=!aD(e.defaultState,t.defaultState)&&!this.state.isTouched;if(!(!n&&!r)){if(NE(()=>{this.baseStore.setState(()=>CD(Object.assign({},this.state,r?e.defaultState:{},n?{values:e.defaultValues}:{})))}),n){let e=SD(this);for(let t of Object.keys(this.fieldInfo))Array.isArray(this.getFieldValue(t))&&e.bumpArrayVersion(t)}WE.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}},this.reset=(e,t)=>{let{fieldMeta:n}=this.state,r=this.resetFieldMeta(n);e&&!t?.keepDefaultValues&&(this.options={...this.options,defaultValues:e}),this.baseStore.setState(()=>{let t=e??this.options.defaultValues??this.options.defaultState?.values;return e||Object.values(this.fieldInfo).forEach(e=>{e.instance&&e.instance.options.defaultValue!==void 0&&(t=qE(t,e.instance.name,e.instance.options.defaultValue))}),CD({...this.options.defaultState,values:t,fieldMetaBase:r})})},this.validateAllFields=async e=>{let t=[];return NE(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let r=n.instance;t.push(Promise.resolve().then(()=>r.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.instance.store.state.meta.isTouched||n.instance.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null,a=[`${e}[${t}]`];for(let n=t+1;n<=(i??0);n++)a.push(`${e}[${n}]`);let o=Object.keys(this.fieldInfo).filter(e=>a.some(t=>e.startsWith(t))),s=[];return NE(()=>{o.forEach(e=>{s.push(Promise.resolve().then(()=>this.validateField(e,n)))})}),(await Promise.all(s)).flat()},this.validateField=(e,t)=>{let n=this.fieldInfo[e]?.instance;if(!n){let{hasErrored:n}=this.validateSync(t);return n&&!this.options.asyncAlways?this.getFieldMeta(e)?.errors??[]:this.validateAsync(t).then(()=>this.getFieldMeta(e)?.errors??[])}return n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0})),n.validate(t)},this.validateSync=(e,t)=>{let n=nD(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||gD}),r=!1,i={};return NE(()=>{for(let e of n){if(!e.validate)continue;let{formError:n,fieldErrors:a}=TD(this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`},type:`validate`})),o=ED(e.cause),s=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(a||{})]);t?.filterFieldNames&&(s=new Set([...s].filter(t.filterFieldNames)));for(let e of s){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!a?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??xD,r=a?.[e],{newErrorValue:s,newSource:c}=oD({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[o]===`form`,previousErrorValue:t?.[o]});c===`form`&&(i[e]={...i[e],[o]:r}),t?.[o]!==s&&this.setFieldMeta(e,(e=xD)=>({...e,errorMap:{...e.errorMap,[o]:s},errorSourceMap:{...e.errorSourceMap,[o]:c}}))}t?.dontUpdateFormErrorMap||this.state.errorMap?.[o]!==n&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:n}})),(n||a)&&(r=!0)}if(t?.dontUpdateFormErrorMap)return;let a=ED(`submit`);this.state.errorMap?.[a]&&e!==`submit`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[a]:void 0}}));let o=ED(`server`);this.state.errorMap?.[o]&&e!==`server`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:void 0}}))}),{hasErrored:r,fieldsErrorMap:i}},this.validateAsync=async(e,t)=>{let n=rD(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||gD});this.state.isFormValidating||this.baseStore.setState(e=>({...e,isFormValidating:!0}));let r=[],i;for(let e of n){if(!e.validate)continue;let n=ED(e.cause);this.state.validationMetaMap[n]?.lastAbortController.abort();let a=new AbortController;this.state.validationMetaMap[n]={lastAbortController:a},r.push(new Promise(async n=>{let r;try{r=await new Promise((t,n)=>{setTimeout(async()=>{if(a.signal.aborted)return t(void 0);try{t(await this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`,signal:a.signal},type:`validateAsync`}))}catch(e){n(e)}},e.debounceMs)})}catch(e){r=e}let{formError:o,fieldErrors:s}=TD(r);s&&(i=i?{...i,...s}:s);let c=ED(e.cause),l=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(i||{})]),u=Array.from(l);t?.filterFieldNames&&(u=u.filter(t.filterFieldNames));for(let e of u){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!i?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??xD,r=i?.[e],{newErrorValue:a,newSource:o}=oD({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[c]===`form`,previousErrorValue:t?.[c]});t?.[c]!==a&&this.setFieldMeta(e,(e=xD)=>({...e,errorMap:{...e.errorMap,[c]:a},errorSourceMap:{...e.errorSourceMap,[c]:o}}))}t?.dontUpdateFormErrorMap||this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[c]:o}})),n(i?{fieldErrors:i,errorMapKey:c}:void 0)}))}let a=[],o={};if(r.length){a=await Promise.all(r);for(let e of a)if(e?.fieldErrors){let{errorMapKey:t}=e;for(let[n,r]of Object.entries(e.fieldErrors))o[n]={...o[n]||{},[t]:r}}}return this.baseStore.setState(e=>({...e,isFormValidating:!1})),o},this.validate=(e,t)=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(e,t);return n&&!this.options.asyncAlways?r:this.validateAsync(e,t)},this._handleSubmit=async e=>{this.baseStore.setState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),NE(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance&&(e.instance.store.state.meta.isTouched||e.instance.setMeta(e=>({...e,isTouched:!0})))})});let t=e??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride&&this.baseStore.state.submissionAttempts<=1){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(e=>({...e,isSubmitting:!0}));let n=()=>{this.baseStore.setState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.state.isFieldsValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),WE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validateAllFields`,errors:Object.values(this.state.fieldMeta).map(e=>e.errors).flat()});return}if(await this.validate(`submit`),!this.state.isValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),WE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validate`,errors:this.state.errors});return}NE(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance?.triggerOnSubmitListener()})}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),NE(()=>{this.baseStore.setState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),WE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),n()})}catch(e){throw this.baseStore.setState(e=>({...e,isSubmitSuccessful:!1})),WE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`inflight`,onError:e}),n(),e}},this.getFieldValue=e=>KE(this.state.values,e),this.getFieldMeta=e=>this.state.fieldMeta[e],this.getFormGroupMeta=e=>this.formGroupMetaDerived.state[e],this.getFieldInfo=e=>this.fieldInfo[e]||={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.setFieldMeta=(e,t)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[e]:GE(t,n.fieldMetaBase[e])}}))},this.resetFieldMeta=e=>Object.keys(e).reduce((e,t)=>{let n=t;return e[n]=xD,e},{}),this.setFieldValue=(e,t,n)=>{let r=n?.dontUpdateMeta??!1,i=n?.dontRunListeners??!1,a=n?.dontValidate??!1;NE(()=>{r||this.setFieldMeta(e,e=>({...e,isTouched:!0,isDirty:!0,errorMap:{...e?.errorMap,onMount:void 0}})),this.baseStore.setState(n=>({...n,values:qE(n.values,e,t)}))}),i||this.getFieldInfo(e).instance?.triggerOnChangeListener(),a||this.validateField(e,`change`)},this.deleteField=e=>{let t=[...Object.keys(this.fieldInfo).filter(t=>{let n=e.toString();return t!==n&&t.startsWith(n)}),e];this.baseStore.setState(e=>{let n={...e};return t.forEach(e=>{n.values=JE(n.values,e),delete this.fieldInfo[e],delete n.fieldMetaBase[e]}),n})},this.pushFieldValue=(e,t,n)=>{this.setFieldValue(e,e=>[...Array.isArray(e)?e:[],t],n),SD(this).bumpArrayVersion(e)},this.insertFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>[...e.slice(0,t),n,...e.slice(t)],cD(r,{dontValidate:!0}));let i=r?.dontValidate??!1;i||await this.validateField(e,`change`),SD(this).handleArrayInsert(e,t),i||await this.validateArrayFieldsStartingFrom(e,t,`change`)},this.replaceFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>e.map((e,r)=>r===t?n:e),cD(r,{dontValidate:!0})),SD(this).bumpArrayVersion(e),(r?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.removeFieldValue=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(e,e=>e.filter((e,n)=>n!==t),cD(n,{dontValidate:!0})),SD(this).handleArrayRemove(e,t),i!==null){let t=`${e}[${i}]`;this.deleteField(t)}(n?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.swapFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=e[t],i=e[n];return qE(qE(e,`${t}`,i),`${n}`,r)},cD(r,{dontValidate:!0})),SD(this).handleArraySwap(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.moveFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=[...e];return r.splice(n,0,r.splice(t,1)[0]),r},cD(r,{dontValidate:!0})),SD(this).handleArrayMove(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.clearFieldValues=(e,t)=>{let n=this.getFieldValue(e),r=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(e,[],cD(t,{dontValidate:!0})),SD(this).bumpArrayVersion(e),r!==null)for(let t=0;t<=r;t++){let n=`${e}[${t}]`;this.deleteField(n)}(t?.dontValidate??!1)||this.validateField(e,`change`)},this.resetField=e=>{this.baseStore.setState(t=>{let n=this.getFieldInfo(e).instance?.options.defaultValue,r=KE(this.options.defaultValues,e),i=n??r;return{...t,fieldMetaBase:{...t.fieldMetaBase,[e]:xD},values:i===void 0?t.values:qE(t.values,e,i)}})},this.setErrorMap=e=>{NE(()=>{Object.entries(e).forEach(([e,t])=>{let n=e;if(iD(t)){let{formError:e,fieldErrors:r}=TD(t);for(let e of Object.keys(this.fieldInfo))this.getFieldMeta(e)&&this.setFieldMeta(e,t=>({...t,errorMap:{...t.errorMap,[n]:r?.[e]},errorSourceMap:{...t.errorSourceMap,[n]:`form`}}));this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[n]:e}}))}else this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[n]:t}}))})})},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((e,[t,n])=>(Object.keys(n).length&&n.errors.length&&(e[t]={errors:n.errors,errorMap:n.errorMap}),e),{})}),this.parseValuesWithSchema=e=>yD.validate({value:this.state.values,validationSource:`form`},e),this.parseValuesWithSchemaAsync=e=>yD.validateAsync({value:this.state.values,validationSource:`form`},e),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=e?.formId??fD(),this._devtoolsSubmissionOverride=!1;let t=CD({...e?.defaultState,values:e?.defaultValues??e?.defaultState?.values});if(e?.transform){t=e.transform({state:t}).state;for(let e of Object.keys(t.errorMap)){let n=t.errorMap[e];if(!(n===void 0||!iD(n)))for(let r of Object.keys(n.fields)){let i=n.fields[r];if(i===void 0)continue;let a=t.fieldMetaBase[r];t.fieldMetaBase[r]={isTouched:!1,isValidating:!1,isBlurred:!1,isDirty:!1,_arrayVersion:0,_pendingValidationsCount:0,...a??{},errorSourceMap:{...a?.errorSourceMap??{},onChange:`form`},errorMap:{...a?.errorMap??{},[e]:i}}}}}this.baseStore=BE(t);let n;this.fieldMetaDerived=BE(e=>{let t=this.baseStore.get(),r=0,i={};for(let a of Object.keys(t.fieldMetaBase)){let o=t.fieldMetaBase[a],s=n?.fieldMetaBase[a],c=e?.[a],l=KE(t.values,a),u=c?.errors;if(!s||o.errorMap!==s.errorMap){u=Object.values(o.errorMap??{}).filter(e=>e!==void 0);let e=this.getFieldInfo(a)?.instance;(!e||!e.options.disableErrorFlat)&&(u=u.flat(1))}let d=!tD(u),f=!o.isDirty,p=aD(l,this.getFieldInfo(a)?.instance?.options.defaultValue??KE(this.options.defaultValues,a));if(c&&c.isPristine===f&&c.isValid===d&&c.isDefaultValue===p&&c.errors===u&&o===s){i[a]=c,r++;continue}i[a]={...o,errors:u??[],isPristine:f,isValid:d,isDefaultValue:p}}return Object.keys(t.fieldMetaBase).length?e&&r===Object.keys(t.fieldMetaBase).length?e:(n=this.baseStore.get(),i):i}),this.formGroupMetaDerived=BE(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),r={};for(let i of this.formGroupApis){let a=i.name,o=t.formGroupStateBase[a]??{isSubmitted:!1,isSubmitting:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1},s=n[a],c=!1,l=!0,u=!1,d=!1,f=!0,p=!1;for(let e in n){if(e===a||!hD(a,e))continue;let t=n[e];t&&(t.isValidating&&(c=!0),t.isValid||(l=!1),t.isTouched&&(u=!0),t.isBlurred&&(d=!0),t.isDefaultValue||(f=!1),t.isDirty&&(p=!0))}let m=!p,h=!!c||o.isValidating,g=s?.errorMap??{},_=s?.errorSourceMap??{},v=!!(g.onMount||Object.entries(n).some(([e,t])=>t&&e!==a&&hD(a,e)&&t.errorMap.onMount)),y=e?.[a],b=y?.errors??[];(!y||y.__srcErrorMap!==g)&&(b=Object.values(g).reduce((e,t)=>{if(t===void 0)return e;if(t&&typeof t==`object`&&`fields`in t){let n=t.group;return n!==void 0&&e.push(n),e}return e.push(t),e},[]));let x=b.length===0,S=l&&x,C=i.options.canSubmitWhenInvalid??!1,w=o.submissionAttempts===0&&!u&&!v||!h&&!o.isSubmitting&&S||C;if(y&&y.errorMap===g&&y.errorSourceMap===_&&y.errors===b&&y.isFieldsValidating===c&&y.isFieldsValid===l&&y.isGroupValid===x&&y.isValid===S&&y.canSubmit===w&&y.isTouched===u&&y.isBlurred===d&&y.isPristine===m&&y.isDefaultValue===f&&y.isDirty===p&&y.isValidating===h&&y.isSubmitting===o.isSubmitting&&y.isSubmitted===o.isSubmitted&&y.submissionAttempts===o.submissionAttempts&&y.isSubmitSuccessful===o.isSubmitSuccessful){r[a]=y;continue}let T={...o,errorMap:g,errorSourceMap:_,_arrayVersion:s?._arrayVersion??0,isTouched:u,isBlurred:d,isDirty:p,isPristine:m,isDefaultValue:f,isValid:S,errors:b,isValidating:h,isFieldsValidating:c,isFieldsValid:l,isGroupValid:x,canSubmit:w};Object.defineProperty(T,"__srcErrorMap",{value:g,enumerable:!1,configurable:!0}),r[a]=T}return r});let r;this.store=BE(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),i=Object.values(n).filter(Boolean),a=i.some(e=>e.isValidating),o=i.every(e=>e.isValid),s=i.some(e=>e.isTouched),c=i.some(e=>e.isBlurred),l=i.every(e=>e.isDefaultValue),u=s&&t.errorMap?.onMount,d=i.some(e=>e.isDirty),f=!d,p=!!(t.errorMap?.onMount||i.some(e=>e?.errorMap?.onMount)),m=!!a,h=e?.errors??[];(!r||t.errorMap!==r.errorMap)&&(h=Object.values(t.errorMap).reduce((e,t)=>t===void 0?e:t&&iD(t)?(e.push(t.form),e):(e.push(t),e),[]));let g=h.length===0,_=o&&g,v=this.options.canSubmitWhenInvalid??!1,y=t.submissionAttempts===0&&!s&&!p||!m&&!t.isSubmitting&&_||v,b=t.errorMap;if(u&&(h=h.filter(e=>e!==t.errorMap.onMount),b=Object.assign(b,{onMount:void 0})),e&&r&&e.errorMap===b&&e.fieldMeta===this.fieldMetaDerived.state&&e.errors===h&&e.isFieldsValidating===a&&e.isFieldsValid===o&&e.isFormValid===g&&e.isValid===_&&e.canSubmit===y&&e.isTouched===s&&e.isBlurred===c&&e.isPristine===f&&e.isDefaultValue===l&&e.isDirty===d&&aD(r,t))return e;let x={...t,errorMap:b,fieldMeta:this.fieldMetaDerived.state,errors:h,isFieldsValidating:a,isFieldsValid:o,isFormValid:g,isValid:_,canSubmit:y,isTouched:s,isBlurred:c,isPristine:f,isDefaultValue:l,isDirty:d};return r=this.baseStore.get(),x}),this.handleSubmit=this.handleSubmit.bind(this),this.update(e||{})}get state(){return this.store.state}get formId(){return this._formId}runValidator(e){return bD(e.validate)?yD[e.type](e.value,e.validate):e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function TD(e){return e?iD(e)?{formError:TD(e.form).formError,fieldErrors:e.fields}:{formError:e}:{formError:void 0}}function ED(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}var DD=class e{constructor(t){this.options={},this.mount=()=>{this.options.defaultValue!==void 0&&!this.getMeta().isTouched&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:!0});let e=this.getInfo();e.instance=this,this.update(this.options);let{onMount:t}=this.options.validators||{};if(t){let e=this.runValidator({validate:t,value:{value:this.state.value,fieldApi:this,validationSource:`field`},type:`validate`});e&&this.setMeta(t=>({...t,errorMap:{...t?.errorMap,onMount:e},errorSourceMap:{...t?.errorSourceMap,onMount:`field`}}))}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);let e=this.form.fieldInfo[this.name];if(e&&e.instance===this){for(let[t,n]of Object.entries(e.validationMetaMap))n?.lastAbortController.abort(),e.validationMetaMap[t]=void 0;this.form.baseStore.setState(e=>({...e,fieldMetaBase:{...e.fieldMetaBase,[this.name]:{...xD,isTouched:e.fieldMetaBase[this.name]?.isTouched??xD.isTouched,isBlurred:e.fieldMetaBase[this.name]?.isBlurred??xD.isBlurred,isDirty:e.fieldMetaBase[this.name]?.isDirty??xD.isDirty}}})),e.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,fieldApi:this}),this.form.options.listeners?.onFieldUnmount?.({formApi:this.form,fieldApi:this})}}},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(aD(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,this.state.meta)},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,cD(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(e,t)=>{this.form.pushFieldValue(this.name,e,cD(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(e,t,n)=>{this.form.insertFieldValue(this.name,e,t,cD(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(e,t,n)=>{this.form.replaceFieldValue(this.name,e,t,cD(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(e,t)=>{this.form.removeFieldValue(this.name,e,cD(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(e,t,n)=>{this.form.swapFieldValues(this.name,e,t,cD(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(e,t,n)=>{this.form.moveFieldValues(this.name,e,t,cD(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=e=>{this.form.clearFieldValues(this.name,cD(e,{dontRunListeners:!0})),e?.dontRunListeners||this.triggerOnChangeListener()},this.getLinkedFields=t=>{let n=Object.values(this.form.fieldInfo),r=[];for(let i of n){if(!i.instance||!(i.instance instanceof e))continue;let{onChangeListenTo:n,onBlurListenTo:a}=i.instance.options.validators||{};t===`change`&&n?.includes(this.name)&&r.push(i.instance),t===`blur`&&a?.includes(this.name)&&r.push(i.instance)}return r},this.validateSync=(e,t)=>{let n=nD(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||gD}),r=this.getLinkedFields(e).reduce((t,n)=>{let r=nD(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||gD});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),i=!1;NE(()=>{let e=(e,n)=>{let r=kD(n.cause),a=n.validate?OD(e.runValidator({validate:n.validate,value:{value:e.store.state.value,validationSource:`field`,fieldApi:e},type:`validate`})):void 0,o=t[r],{newErrorValue:s,newSource:c}=sD({formLevelError:o,fieldLevelError:a});e.state.meta.errorMap?.[r]!==s&&e.setMeta(e=>({...e,errorMap:{...e.errorMap,[r]:s},errorSourceMap:{...e.errorSourceMap,[r]:c}})),s&&(i=!0)};for(let t of n)e(this,t);for(let t of r)t.validate&&e(t.field,t)});let a=kD(`submit`);return this.state.meta.errorMap?.[a]&&e!==`submit`&&!i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[a]:void 0},errorSourceMap:{...e.errorSourceMap,[a]:void 0}})),{hasErrored:i}},this.validateAsync=async(e,t)=>{let n=rD(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||gD}),r=await t,i=this.getLinkedFields(e).reduce((t,n)=>{let r=rD(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||gD});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),a=[],o=[],s=n.some(e=>e.validate),c=Array.from(new Set(i.filter(e=>e.validate).map(e=>e.field)));NE(()=>{s&&this.startValidation();for(let e of c)e.startValidation()});let l=(e,t,n)=>{let i=kD(t.cause),a=e.getInfo();a.validationMetaMap[i]?.lastAbortController.abort();let o=new AbortController;a.validationMetaMap[i]={lastAbortController:o},n.push(new Promise(async n=>{let a;try{a=await new Promise((n,r)=>{e.timeoutIds.validations[t.cause]&&(clearTimeout(e.timeoutIds.validations[t.cause]),e.endValidation()),e.timeoutIds.validations[t.cause]=setTimeout(async()=>{if(o.signal.aborted)return n(void 0);try{n(await this.runValidator({validate:t.validate,value:{value:e.store.state.value,fieldApi:e,signal:o.signal,validationSource:`field`},type:`validateAsync`}))}catch(e){r(e)}},t.debounceMs)})}catch(e){a=e}if(o.signal.aborted)return n(void 0);let s=OD(a),c=r[e.name]?.[i],{newErrorValue:l,newSource:u}=sD({formLevelError:c,fieldLevelError:s});if(e.getInfo().instance!==e)return n(void 0);e.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:l},errorSourceMap:{...e.errorSourceMap,[i]:u}})),n(l)}))};for(let e of n)e.validate&&l(this,e,a);for(let e of i)e.validate&&l(e.field,e,o);let u=[];return(a.length||o.length)&&(u=await Promise.all(a),await Promise.all(o)),NE(()=>{s&&this.endValidation();for(let e of c)e.endValidation()}),u.filter(Boolean)},this.validate=(e,t)=>{if(!this.state.meta.isTouched)return[];let n=t?.skipGroupValidation?[]:Array.from(this.form.formGroupApis).filter(e=>this.name.startsWith(e.name)),r=(t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e)).fieldsErrorMap[this.name]??{};if(!t?.skipFormValidation)for(let t of n){if(t.state.meta.submissionAttempts===0)continue;let{fieldsErrorMap:n}=this.form.validateSync(e,{group:t,dontUpdateFormErrorMap:!0,filterFieldNames:e=>hD(t.name,e)});r={...r,...n[this.name]??{}}}let{hasErrored:i}=this.validateSync(e,r),a=new WeakMap;for(let t of n){let{hasErrored:n}=t.validateSync(e,{},{skipRelatedFieldValidation:!0});a.set(t,n)}if(i&&!this.options.asyncAlways){this.getInfo().validationMetaMap[kD(e)]?.lastAbortController.abort();let t=[];for(let r of n)r.getInfo().validationMetaMap[kD(e)]?.lastAbortController.abort(),t.push(r.state.meta.errors);return[...this.state.meta.errors,...t.flat()]}let o=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e),s=this.validateAsync(e,o),c=[];for(let t of n)a.get(t)&&!t.options.asyncAlways||c.push(t.validateAsync(e,o,{skipRelatedFieldValidation:!0}));return c.length===0?s:Promise.all([s,...c]).then(e=>e.flat())},this.handleChange=e=>{this.setValue(e)},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(e=>({...e,isTouched:!0})),this.state.meta.isBlurred||this.setMeta(e=>({...e,isBlurred:!0})),this.validate(`blur`),this.triggerOnBlurListener()},this.setErrorMap=e=>{this.setMeta(t=>({...t,errorMap:{...t.errorMap,...e}}))},this.parseValueWithSchema=e=>yD.validate({value:this.state.value,validationSource:`field`},e),this.parseValueWithSchemaAsync=e=>yD.validateAsync({value:this.state.value,validationSource:`field`},e),this.triggerOnBlurListener=()=>{let e=this.form.options.listeners?.onBlurDebounceMs;e&&e>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});for(let e of this.form.formGroupApis)hD(e.name,this.name)&&e.triggerOnChangeListener()},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,fieldApi:this})},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=BE(e=>{this.form.store.get();let n=this.form.getFieldMeta(this.name)??{...xD,...t.defaultMeta},r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!aD(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}})}get state(){return this.store.state}runValidator(e){return bD(e.validate)?yD[e.type](e.value,e.validate):e.validate(e.value)}startValidation(){this.setMeta(e=>{let t=e._pendingValidationsCount+1;return{...e,_pendingValidationsCount:t,isValidating:t>0&&!e.isValidating||e.isValidating}})}endValidation(){this.setMeta(e=>{let t=Math.max(0,e._pendingValidationsCount-1);return{...e,_pendingValidationsCount:t,isValidating:t===0&&e.isValidating?!1:e.isValidating}})}};function OD(e){if(e)return e}function kD(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function AD(e){return{isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1}}function jD(e){return{...xD,...e,errors:[],isPristine:!0,isValid:!0,isDefaultValue:!0,isFieldsValidating:!1,isFieldsValid:!0,isGroupValid:!0,canSubmit:!0,isSubmitting:!1,isSubmitted:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1}}var MD=class e{constructor(t){this.options={},this.setFormGroupState=e=>{this.form.baseStore.setState(t=>{let n=t.formGroupStateBase[this.name]??AD({});return{...t,formGroupStateBase:{...t.formGroupStateBase,[this.name]:e(n)}}})},this._lastDistributedFieldNames={},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(aD(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,{...xD,...this.options.defaultMeta})},this.mount=()=>{this.update(this.options),this.form.formGroupApis.add(this),this.fieldInfo.instance=this,this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:e.formGroupStateBase[this.name]??AD({...this.options.defaultState})}}));let{onMount:e}=this.options.validators||{};if(e){let t=this.runValidator({validate:e,value:{value:this.state.value,groupApi:this,validationSource:`form`},type:`validate`}),n=t,r;PD(t)&&(n=t.group,r=t.fields);let i=ND(n);i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,onMount:i},errorSourceMap:{...e.errorSourceMap,onMount:`field`}})),this.distributeFieldErrors(`onMount`,r)}return this.options.listeners?.onMount?.({value:this.state.value,groupApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);if(this.fieldInfo.instance===this){for(let[e,t]of Object.entries(this.fieldInfo.validationMetaMap))t?.lastAbortController.abort(),this.fieldInfo.validationMetaMap[e]=void 0;this.form.formGroupApis.delete(this),this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:AD({})}})),this.fieldInfo.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,groupApi:this})}}},this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,cD(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.fieldInfo,this.getRelatedFields=()=>{let e=Object.values(this.form.fieldInfo),t=[];for(let n of e)n.instance&&n.instance instanceof DD&&n.instance.name.startsWith(this.name)&&t.push(n.instance);return t},this.getRelatedFieldMetasDerived=()=>{let e=Object.entries(this.form.fieldMetaDerived.state),t=[];for(let[n,r]of e)n!==this.name&&hD(this.name,n)&&t.push({...r,name:n});return t},this.buildChildFieldName=e=>e===``?this.name:e.startsWith(`[`)?`${this.name}${e}`:`${this.name}.${e}`,this.distributeFieldErrors=(e,t)=>{let n=this._lastDistributedFieldNames[e]??new Set,r=new Set;if(t)for(let[e,n]of Object.entries(t))n!=null&&n!==!1&&r.add(this.buildChildFieldName(e));let i=new Set([...n,...r]),a=!1;for(let n of i){let r=n.startsWith(this.name+`[`)?n.slice(this.name.length):n.slice(this.name.length+1),i=t?.[r],o=this.form.getFieldMeta(n);if(!o&&!i)continue;let s=o?.errorMap[e],{newErrorValue:c,newSource:l}=oD({newFormValidatorError:i,isPreviousErrorFromFormValidator:o?.errorSourceMap[e]===`form`,previousErrorValue:s});c&&(a=!0),(s!==c||o?.errorSourceMap[e]!==l)&&this.form.setFieldMeta(n,(t=xD)=>({...t,errorMap:{...t.errorMap,[e]:c},errorSourceMap:{...t.errorSourceMap,[e]:l}}))}return this._lastDistributedFieldNames[e]=r,a},this.validateSync=(t,n,r={})=>{let i=nD(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||gD}),a=(r.skipRelatedFieldValidation?[]:this.getRelatedFields()).reduce((e,n)=>{let r=nD(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||gD});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),o=!1;NE(()=>{let t=(t,r)=>{let i=ID(r.cause),a=t===this,s;r.validate&&(s=t.runValidator({validate:r.validate,value:{value:t.store.state.value,validationSource:a?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validate`}));let c=s,l;a&&PD(s)&&(c=s.group,l=s.fields);let u=ND(c),d=n[i],{newErrorValue:f,newSource:p}=sD({formLevelError:d,fieldLevelError:u});t.state.meta.errorMap?.[i]!==f&&t.setMeta(e=>({...e,errorMap:{...e.errorMap,[i]:f},errorSourceMap:{...e.errorSourceMap,[i]:p}})),f&&(o=!0),a&&this.distributeFieldErrors(i,l)&&(o=!0)};for(let e of i)t(this,e);for(let e of a)e.validate&&t(e.field,e)});let s=ID(`submit`);return this.state.meta.errorMap?.[s]&&t!==`submit`&&!o&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[s]:void 0},errorSourceMap:{...e.errorSourceMap,[s]:void 0}})),{hasErrored:o}},this.validateAsync=async(t,n,r={})=>{let i=rD(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||gD}),a=await n,o=r.skipRelatedFieldValidation?[]:this.getRelatedFields(),s=o.reduce((e,n)=>{let r=rD(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||gD});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),c=[],l=[],u=i.some(e=>e.validate)||s.some(e=>e.validate);if(u){this.state.meta.isValidating||this.setMeta(e=>({...e,isValidating:!0}));for(let e of o)e.setMeta(e=>({...e,isValidating:!0}))}let d=(t,n,r)=>{let i=ID(n.cause),o=t.getInfo();o.validationMetaMap[i]?.lastAbortController.abort();let s=new AbortController;o.validationMetaMap[i]={lastAbortController:s};let c=t===this;r.push(new Promise(async r=>{let o;try{o=await new Promise((r,i)=>{t.timeoutIds.validations[n.cause]&&clearTimeout(t.timeoutIds.validations[n.cause]),t.timeoutIds.validations[n.cause]=setTimeout(async()=>{if(s.signal.aborted)return r(void 0);try{r(await this.runValidator({validate:n.validate,value:{value:t.store.state.value,signal:s.signal,validationSource:c?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validateAsync`}))}catch(e){i(e)}},n.debounceMs)})}catch(e){o=e}if(s.signal.aborted)return r(void 0);let l=o,u;c&&PD(o)&&(l=o.group,u=o.fields);let d=ND(l),f=a[t.name]?.[i],{newErrorValue:p,newSource:m}=sD({formLevelError:f,fieldLevelError:d});if(t.getInfo().instance!==t)return r(void 0);t.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:p},errorSourceMap:{...e.errorSourceMap,[i]:m}})),c&&this.distributeFieldErrors(i,u),r(p)}))};for(let e of i)e.validate&&d(this,e,c);for(let e of s)e.validate&&d(e.field,e,l);let f=[];if((c.length||l.length)&&(f=await Promise.all(c),await Promise.all(l)),u){this.setMeta(e=>({...e,isValidating:!1}));for(let e of o)e.setMeta(e=>({...e,isValidating:!1}))}return f.filter(Boolean)},this.validateAllFields=async e=>{let t=[];return NE(()=>{Object.values(this.getRelatedFields()).forEach(n=>{t.push(Promise.resolve().then(()=>n.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=(e,t,n)=>this.form.validateArrayFieldsStartingFrom(e,t,n),this.validateField=(e,t)=>this.form.validateField(e,t),this.getFieldValue=e=>this.form.getFieldValue(e),this.getFieldMeta=e=>this.form.getFieldMeta(e),this.setFieldMeta=(e,t)=>this.form.setFieldMeta(e,t),this.setFieldValue=(e,t)=>this.form.setFieldValue(e,t),this.deleteField=e=>this.form.deleteField(e),this.pushFieldValue=(e,t)=>this.form.pushFieldValue(e,t),this.insertFieldValue=(e,t,n)=>this.form.insertFieldValue(e,t,n),this.replaceFieldValue=(e,t,n)=>this.form.replaceFieldValue(e,t,n),this.swapFieldValues=(e,t,n)=>this.form.swapFieldValues(e,t,n),this.moveFieldValues=(e,t,n)=>this.form.moveFieldValues(e,t,n),this.clearFieldValues=e=>this.form.clearFieldValues(e),this.resetField=e=>this.form.resetField(e),this.removeFieldValue=(e,t)=>this.form.removeFieldValue(e,t),this.areRelatedFieldsValid=()=>Object.values(this.getRelatedFields()).every(e=>e.state.meta.isValid),this.validate=(e,t)=>{let{fieldsErrorMap:n}=t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>hD(this.name,e)}),{hasErrored:r}=this.validateSync(e,n[this.name]??{},{skipRelatedFieldValidation:t?.skipRelatedFieldValidation});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[ID(e)]?.lastAbortController.abort(),this.state.meta.errors;let i=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>hD(this.name,e)});return this.validateAsync(e,i,{skipRelatedFieldValidation:t?.skipRelatedFieldValidation})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeGroupDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this})},e)):this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,groupApi:this})},this._handleSubmit=async e=>{this.setFormGroupState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),NE(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.state.meta.isTouched||e.setMeta(e=>({...e,isTouched:!0}))})});let t=e??this.options.onSubmitMeta;this.setFormGroupState(e=>({...e,isSubmitting:!0}));let n=()=>{this.setFormGroupState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.areRelatedFieldsValid()){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}if(await this.validate(`submit`,{skipRelatedFieldValidation:!0}),!this.areRelatedFieldsValid()||!this.state.meta.isValid){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}NE(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.options.listeners?.onGroupSubmit?.({value:e.state.value,fieldApi:e})})}),this.options.listeners?.onSubmit?.({groupApi:this,value:this.state.value});try{await this.options.onGroupSubmit?.({value:this.state.value,groupApi:this,meta:t}),NE(()=>{this.setFormGroupState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),n()})}catch(e){throw this.setFormGroupState(e=>({...e,isSubmitSuccessful:!1})),n(),e}},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.fieldInfo={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.store=BE(e=>{this.form.formGroupMetaDerived.get(),this.form.baseStore.get();let n=this.form.getFormGroupMeta(this.name)??jD(t.defaultMeta),r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!aD(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}}),this.handleSubmit=this.handleSubmit.bind(this)}get state(){return this.store.state}runValidator(e){if(bD(e.validate)){let t=yD[e.type](e.value,e.validate);return e.type===`validate`?FD(t):t.then(FD)}return e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function ND(e){if(e)return e}function PD(e){return!!e&&typeof e==`object`&&`fields`in e}function FD(e){if(!e||typeof e!=`object`||!(`form`in e)&&!(`fields`in e))return e;let{form:t,fields:n,...r}=e;return{...r,group:t,fields:n}}function ID(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function LD(e,t){if(!t)return;let n=Object.assign({},e,{state:mD(e.state)});t(n),n.fieldInfo!==e.fieldInfo&&(e.fieldInfo=n.fieldInfo),n.options!==e.options&&(e.options=n.options);let r=Object.keys({values:null,validationMetaMap:null,fieldMetaBase:null,formGroupStateBase:null,isSubmitting:null,isSubmitted:null,isValidating:null,submissionAttempts:null,isSubmitSuccessful:null,_force_re_eval:null}).reduce((t,r)=>(e.state[r]!==n.state[r]&&(t[r]=n.state[r]),t),{});return NE(()=>{Object.keys(r).length&&e.baseStore.setState(e=>({...e,...r})),n.state.errorMap!==e.state.errorMap&&e.setErrorMap(n.state.errorMap)}),n}var RD=Kn();function zD(e,t){return e===t}function BD(e,t=e=>e,n){let r=n?.compare??zD,i=(0,Q.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,Q.useCallback)(()=>e.get(),[e]);return(0,RD.useSyncExternalStoreWithSelector)(i,a,a,t,r)}var VD=typeof window<`u`?Q.useLayoutEffect:Q.useEffect;function HD(e){let[t,n]=(0,Q.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,Q.useState)(()=>new DD({...e})),a=r;(t.form!==e.form||t.name!==e.name)&&(a=new DD({...e}),i(a),n({form:e.form,name:e.name}));let o=BD(a.store,e.mode===`array`?e=>e.meta._arrayVersion||0:e=>e.value),s=BD(a.store,e=>e.meta.isTouched),c=BD(a.store,e=>e.meta.isBlurred),l=BD(a.store,e=>e.meta.isDirty),u=BD(a.store,e=>e.meta.errorMap),d=BD(a.store,e=>e.meta.errorSourceMap),f=BD(a.store,e=>e.meta.isValidating),p=(0,Q.useMemo)(()=>({...a,get state(){return{value:e.mode===`array`?a.state.value:o,get meta(){return{...a.state.meta,isTouched:s,isBlurred:c,isDirty:l,errorMap:u,errorSourceMap:d,isValidating:f}}}}}),[a,e.mode,o,s,c,l,u,d,f]);return VD(a.mount,[a]),VD(()=>{a.update(e)}),p}var UD=(({children:e,...t})=>{let n=HD(t),r=(0,Q.useMemo)(()=>GE(e,n),[e,n]);return(0,$.jsx)($.Fragment,{children:r})});function WD(){return(0,Q.useState)(()=>fD())[0]}var GD=Q,KD=`18.3.1`.split(`.`)[0]===`17`?WD:GD.useId;function qD(e){let[t,n]=(0,Q.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,Q.useState)(()=>new MD({...e}));(t.form!==e.form||t.name!==e.name)&&(i(new MD({...e})),n({form:e.form,name:e.name}));let a=BD(r.store,e=>e.value),o=BD(r.store,e=>e.meta.isTouched),s=BD(r.store,e=>e.meta.isBlurred),c=BD(r.store,e=>e.meta.isDirty),l=BD(r.store,e=>e.meta.errorMap),u=BD(r.store,e=>e.meta.errorSourceMap),d=BD(r.store,e=>e.meta.isValidating),f=BD(r.store,e=>e.meta.isSubmitting),p=BD(r.store,e=>e.meta.isSubmitted),m=BD(r.store,e=>e.meta.submissionAttempts),h=BD(r.store,e=>e.meta.isSubmitSuccessful),g=BD(r.store,e=>e.meta.canSubmit),_=BD(r.store,e=>e.meta.isValid),v=BD(r.store,e=>e.meta.isFieldsValid),y=BD(r.store,e=>e.meta.isFieldsValidating),b=BD(r.store,e=>e.meta.isGroupValid),x=(0,Q.useMemo)(()=>({...r,handleSubmit:((...e)=>r._handleSubmit(...e)),get state(){return{...r.state,value:a,get meta(){return{...r.state.meta,isTouched:o,isBlurred:s,isDirty:c,errorMap:l,errorSourceMap:u,isValidating:d,isSubmitting:f,isSubmitted:p,submissionAttempts:m,isSubmitSuccessful:h,canSubmit:g,isValid:_,isFieldsValid:v,isFieldsValidating:y,isGroupValid:b}}}}}),[r,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b]);return VD(r.mount,[r]),VD(()=>{r.update(e)}),x}var JD=(({children:e,...t})=>{let n=qD(t),r=(0,Q.useMemo)(()=>GE(e,n),[e,n]);return(0,$.jsx)($.Fragment,{children:r})});function YD({form:e,selector:t=e=>e,children:n}){let r=BD(e.store,t);return(0,$.jsx)($.Fragment,{children:GE(n,r)})}function XD(e){let t=KD(),[n,r]=(0,Q.useState)(e?.formId),[i,a]=(0,Q.useState)(()=>new wD({...e,formId:e?.formId??t}));if(n!==e?.formId){let n=e?.formId??t;a(new wD({...e,formId:n})),r(n)}let o=(0,Q.useMemo)(()=>{let e={...i,handleSubmit:((...e)=>i._handleSubmit(...e)),get formId(){return i._formId},get state(){return i.store.state}};return e.Field=function(e){return(0,$.jsx)(UD,{...e,form:i})},e.FormGroup=function(e){return(0,$.jsx)(JD,{...e,form:i})},e.Subscribe=function(e){return(0,$.jsx)(YD,{form:i,selector:e.selector,children:e.children})},e},[i]);VD(i.mount,[]),VD(()=>{i.update(e)});let s=(0,Q.useRef)(!1);return VD(()=>{s.current&&e?.transform&&LD(i,e.transform)},[i,e?.transform]),VD(()=>{s.current=!0}),o}var ZD=Na(Y),QD=Na(G({message:Y}));function $D(e){for(let t of e.errors){let e=Ii(Oi(Vi(QD(t),e=>e.message),()=>ZD(t)));if(e!==void 0&&e.length>0)return e}}var eO={neutral:`progress-neutral`,primary:`progress-primary`,secondary:`progress-secondary`,accent:`progress-accent`,success:`progress-success`,info:`progress-info`,warning:`progress-warning`,error:`progress-error`},tO=(0,Q.forwardRef)(function({className:e,tone:t=`primary`,...n},r){return(0,$.jsx)(`progress`,{...n,"data-complete":n.value!==void 0&&Number(n.value)>=Number(n.max??1)?`true`:void 0,className:N(`progress caps-gooey-motion caps-gooey-progress w-full`,eO[t],e),ref:r})});(0,Q.forwardRef)(function({label:e,value:t,max:n,tone:r=`info`,className:i,...a},o){return(0,$.jsxs)(`div`,{...a,ref:o,className:N(`caps-game-meter`,i),children:[(0,$.jsxs)(`div`,{className:`caps-game-meter-readout`,children:[(0,$.jsx)(`span`,{children:e}),(0,$.jsxs)(`span`,{className:`caps-game-meter-value`,children:[t,` / `,n]})]}),(0,$.jsx)(tO,{"aria-label":e,value:t,max:n,tone:r})]})});function nO({className:e,items:t,onCancel:n,onRemove:r,onRetry:i,rowClassName:a}){return t.length?(0,$.jsx)(`div`,{"aria-live":`polite`,className:`caps-upload-queue flex w-full min-w-0 flex-col gap-sm ${e??``}`,"data-upload-rows":!0,children:t.map(e=>(0,$.jsx)(aO,{item:e,onCancel:n,onRemove:r,onRetry:i,...a===void 0?{}:{rowClassName:a}},e.id))}):null}function rO({action:e,id:t,onAction:n,retry:r=!1}){return e?(0,$.jsx)(ct,{"aria-label":e.accessibleLabel,title:e.label,variant:`ghost`,size:`xs`,className:`motion-reduce:transition-none`,icon:r?(0,$.jsx)(VC,{}):(0,$.jsx)(O,{}),onClick:()=>void n(t),type:`button`}):null}function iO({item:e}){return(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block min-w-0 truncate`,title:e.name,children:e.name}),(0,$.jsx)(`div`,{className:`caps-upload-details`,children:(0,$.jsxs)(`span`,{"aria-live":e.alert?`assertive`:void 0,className:`caps-upload-status min-w-0 break-words`,"data-upload-status":!0,role:e.alert?`alert`:void 0,children:[e.alert??e.statusLabel,` `,e.progressLabel]})})]})}function aO({item:e,onCancel:t,onRemove:n,onRetry:r,rowClassName:i}){return(0,$.jsxs)(`div`,{className:`caps-upload-row grid w-full min-w-0 max-w-full grid-cols-[2rem_minmax(0,1fr)_auto] items-center gap-sm p-sm text-xs ${i??``}`,children:[e.preview.kind===`image`?(0,$.jsx)(`img`,{alt:``,className:`caps-upload-preview mask mask-squircle size-8 shrink-0 object-cover`,src:e.preview.url}):(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`caps-upload-preview mask mask-squircle flex size-8 shrink-0 items-center justify-center bg-base-300`,children:(0,$.jsx)(LC,{className:`size-4`})}),(0,$.jsx)(iO,{item:e}),(0,$.jsx)(oO,{actions:e.actions,id:e.id,onCancel:t,onRemove:n,onRetry:r}),(0,$.jsx)(tO,{"aria-label":`${e.name} progress`,className:`caps-upload-progress`,tone:e.alert?`error`:e.progress===100?`success`:`accent`,max:100,value:e.progress??(e.alert?0:void 0)})]})}function oO({actions:e,id:t,onCancel:n,onRemove:r,onRetry:i}){return(0,$.jsxs)(`div`,{className:`caps-upload-actions flex min-w-0 flex-wrap justify-end gap-xs`,children:[(0,$.jsx)(rO,{action:e.retry,id:t,onAction:i,retry:!0}),(0,$.jsx)(rO,{action:e.cancel,id:t,onAction:n}),(0,$.jsx)(rO,{action:e.remove,id:t,onAction:r})]})}var sO=Q.createContext(void 0);function cO(e){let t=Q.useContext(sO);if(t===void 0&&!e)throw Error(U(47));return t}var lO={...Bn,disabled:e=>e.disabled,instantType:e=>e.instantType===`trigger-change`&&!Bn.open(e)?void 0:e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,isPressOpenedByTrigger:(e,t)=>e.openChangeReason===`trigger-press`&&Bn.isOpenedByTrigger(e,t),isTouchPressOpen:(e,t)=>t&&e.openMethod===`touch`&&e.openChangeReason===`trigger-press`,hasTriggerFocusGuards:(e,t)=>Bn.isOpenedByTrigger(e,t)&&!e.focusManagerModal,modal:e=>e.modal,titleElementId:e=>e.titleElementId,descriptionElementId:e=>e.descriptionElementId,openOnHover:e=>e.openOnHover,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin},uO=class extends or{constructor(e,t,n){let r=new dr;super(dO(e,r,t,n),fO(r),lO)}setOpen=(e,t)=>{let n=t.reason===Pn,r=t.reason===`trigger-press`&&t.event.detail===0,i=!e&&(t.reason===`escape-key`||t.reason==null),a=qt(t),o=this.select(`activeTriggerId`);if(!e&&t.reason===`close-press`&&t.trigger==null&&o!=null&&(t.trigger=this.context.triggerElements.getById(o)??this.select(`activeTriggerElement`)??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);let s=()=>{let n=Qn(this.state,e,t.trigger,a());n.openChangeReason=t.reason,this.update(n)};n?(this.context.stickIfOpen=!0,this.context.stickIfOpenTimeout.start(500,()=>{this.context.stickIfOpen=!1}),vv.flushSync(s)):s();let c;r?c=`click`:i?c=`dismiss`:t.reason===`focus-out`&&(c=`focus`),this.set(`instantType`,c)}};function dO(e,t,n,r=!1){let i={...hr(t,n,r),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,openOnHover:!1,closeDelay:0,adaptiveOrigin:void 0,...e};return i.open&&e?.mounted===void 0&&(i.mounted=!0),i}function fO(e){return{popupRef:Q.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:Q.createRef(),beforeTriggerFocusGuardRef:Q.createRef(),beforeContentFocusGuardRef:Q.createRef(),stickIfOpenTimeout:new mn,stickIfOpen:!0,triggerElements:e}}var pO=vn(function({props:e}){let{children:t,open:n,defaultOpen:r=!1,onOpenChange:i,onOpenChangeComplete:a,modal:o=!1,handle:s,triggerId:c,defaultTriggerId:l=null}=e,u=hO(s,{modal:o,open:r,openProp:n,activeTriggerId:l,triggerIdProp:c});u.useControlledProp(`openProp`,n),u.useControlledProp(`triggerIdProp`,c);let d=u.useState(`open`),f=u.useState(`mounted`),p=u.useState(`payload`);u.useContextCallback(`onOpenChange`,i),u.useContextCallback(`onOpenChangeComplete`,a),wr(u,d),Fn(u);let{forceUnmount:m}=pn(d,u,()=>{u.context.stickIfOpen=!0,u.set(`openChangeReason`,null)});u.useSyncedValues({modal:o}),Q.useEffect(()=>{d||u.context.stickIfOpenTimeout.clear()},[u,d]),Q.useImperativeHandle(e.actionsRef,()=>({unmount:m,close:()=>u.setOpen(!1,Ar(Mt))}),[m,u]);let h=d||f||s!=null;return(0,$.jsxs)(sO.Provider,{value:u,children:[s&&(0,$.jsx)(An,{handle:s,store:u}),h&&(0,$.jsx)(gO,{store:u,modal:o}),typeof t==`function`?t({payload:p}):t]})});function mO(e){return cO(!0)?(0,$.jsx)(pO,{props:e}):(0,$.jsx)(Je,{children:(0,$.jsx)(pO,{props:e})})}function hO(e,t){let n=Dt((e,n)=>new uO(t,e,n));return Q.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function gO({store:e,modal:t}){let n=e.useState(`floatingRootContext`),r=Nr(n,{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}}),i=r.reference,a=r.floating;return cn(e,{activeTriggerProps:i,inactiveTriggerProps:i,popupProps:a}),null}var _O=Nt(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,handle:s,payload:c,openOnHover:l=!1,delay:d=300,closeDelay:f=0,id:p,...m}=e,h=cO(!0),g=Zt(s)??h;if(!g)throw Error(U(74));let _=D(p),v=g.useState(`isTriggerActive`,_),y=g.useState(`floatingRootContext`),b=g.useState(`isOpenedByTrigger`,_),x=g.useState(`triggerPopupId`,_),S=Q.useRef(null),{registerTrigger:C,isMountedByThisTrigger:w}=Lr(_,S,g,{payload:c,disabled:a,openOnHover:l,closeDelay:f}),T=g.useState(`isPressOpenedByTrigger`,_),E=g.useState(`isTouchPressOpen`,l),O=g.useState(`hasTriggerFocusGuards`,_),k=bv(y,{enabled:!a&&l&&!E,mouseOnly:!0,move:!1,handleClose:Iv(),restMs:d,delay:{close:f},triggerElementRef:S,isActiveTrigger:v,isClosing:()=>g.select(`transitionStatus`)===`ending`}),j=A(()=>g.context.stickIfOpen),M=Ue(y,{stickIfOpen:j}),N=vt(()=>g.select(`open`),e=>{g.set(`openMethod`,e)}),ee=g.useState(`triggerProps`,w),{getButtonProps:te,buttonRef:ne}=u({disabled:a,native:o}),P={open(e){return T?Cr.open(e):Ir.open(e)}},{handlePreFocusGuardFocus:F,handleFocusTargetFocus:re}=Xb(g,S),I=Or(`button`,e,{state:{disabled:a,open:b},ref:[ne,t,C,S],props:[M.reference,k,ee,N,{[ve]:``,id:_,"aria-haspopup":`dialog`,"aria-expanded":b,"aria-controls":x},m,te],stateAttributesMapping:P}),L=(0,$.jsx)(Q.Fragment,{children:I},_);return O?(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsx)(tr,{ref:g.context.beforeTriggerFocusGuardRef,onFocus:F}),L,(0,$.jsx)(tr,{ref:g.context.triggerFocusTargetRef,onFocus:re})]}):L}),vO=Q.createContext(void 0);function yO(){let e=Q.useContext(vO);if(e===void 0)throw Error(U(45));return e}var bO=Q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return cO().useState(`mounted`)||n?(0,$.jsx)(vO.Provider,{value:n,children:(0,$.jsx)(l,{ref:t,...r})}):null}),xO=Q.createContext(void 0);function SO(){let e=Q.useContext(xO);if(!e)throw Error(U(46));return e}var CO=Q.forwardRef(function(e,t){let{render:n,className:r,style:i,anchor:a,positionMethod:o,side:s,align:c,sideOffset:l,alignOffset:u,collisionBoundary:d=`clipping-ancestors`,collisionPadding:f,arrowPadding:p,sticky:m,disableAnchorTracking:h=!1,collisionAvoidance:g=k,..._}=e,v=cO(),y=yO(),b=E(),x=v.useState(`floatingRootContext`),S=v.useState(`mounted`),C=v.useState(`open`),w=v.useState(`openChangeReason`),T=v.useState(`activeTriggerElement`),D=v.useState(`modal`),O=v.useState(`openMethod`),A=v.useState(`positionerElement`),j=v.useState(`instantType`),M=v.useState(`transitionStatus`),N=_b({anchor:a,floatingRootContext:x,positionMethod:o,mounted:S,side:s,sideOffset:l,align:c,alignOffset:u,arrowPadding:p,collisionBoundary:d,collisionPadding:f,sticky:m,disableAnchorTracking:h,keepMounted:y,nodeId:b,collisionAvoidance:g,adaptiveOrigin:v.useState(`adaptiveOrigin`)});Db({store:v,domReference:x.useState(`domReferenceElement`),positionerElement:A,open:C});let ee=D===!0&&w!==`trigger-hover`;Ab(C&&ee,O===`touch`,A,T);let te=v.useStateSetter(`positionerElement`),ne=Ob(e,{open:C,side:N.side,align:N.align,anchorHidden:N.anchorHidden,instant:j},{styles:N.positionerStyles,transitionStatus:M,props:_,refs:[t,te],hidden:!S,inert:!C});return(0,$.jsxs)(xO.Provider,{value:N,children:[S&&ee&&(0,$.jsx)(Ct,{inert:Ie(!C),cutout:T}),(0,$.jsx)(kr,{id:b,children:ne})]})}),wO=Q.createContext(void 0);function TO(){let[e,t]=Q.useState(0),n=A(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:Q.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}var EO=Q.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:s,...c}=e,l=cO(),u=SO(),d=Vy(!0)!=null,{context:f,hasClosePart:p}=TO(),m=l.useState(`open`),h=l.useState(`openMethod`),g=l.useState(`instantType`),_=l.useState(`transitionStatus`),y=l.useState(`popupProps`),b=l.useState(`titleElementId`),x=l.useState(`descriptionElementId`),S=l.useState(`modal`),C=l.useState(`mounted`),w=l.useState(`openChangeReason`),T=l.useState(`activeTriggerElement`),E=l.useState(`floatingRootContext`),D=E.useState(`floatingId`),O=l.useState(`disabled`),k=l.useState(`openOnHover`),A=l.useState(`closeDelay`);Ot({open:m,ref:l.context.popupRef,onComplete(){m&&l.context.onOpenChangeComplete?.(!0)}}),_v(E,{enabled:k&&!O,closeDelay:A});let j=a===void 0?nn(l.context.popupRef):a,M=S!==!1&&p;l.useSyncedValue(`focusManagerModal`,M);let N=l.useStateSetter(`popupElement`),ee={open:m,side:u.side,align:u.align,instant:g,transitionStatus:_},te=Or(`div`,e,{state:ee,ref:[t,l.context.popupRef,N],props:[y,{id:D,role:`dialog`,...Ht,"aria-labelledby":b,"aria-describedby":x,onKeyDown(e){d&&o.has(e.key)&&e.stopPropagation()}},Hy(_),c],stateAttributesMapping:Et});return(0,$.jsx)(v,{context:E,openInteractionType:h,modal:M,disabled:!C||w===`trigger-hover`,initialFocus:j,returnFocus:s,restoreFocus:`popup`,getInsideElements:()=>[l.context.beforeTriggerFocusGuardRef.current],previousFocusableElement:nr(T)?T:void 0,nextFocusableElement:l.context.triggerFocusTargetRef,beforeContentFocusGuardRef:l.context.beforeContentFocusGuardRef,children:(0,$.jsx)(wO.Provider,{value:f,children:te})})}),DO=(0,Q.forwardRef)(function({children:e,className:t,type:n=`button`,...r},i){return(0,$.jsxs)(`button`,{...r,ref:i,type:n,className:N(`select caps-select caps-combobox-trigger w-full`,t),children:[(0,$.jsx)(`span`,{children:e}),(0,$.jsx)(pe,{className:`caps-select-chevron`,"aria-hidden":`true`})]})});function OO({defaultInputValue:e,defaultOpen:t,defaultValue:n,getKey:r,getSearchText:i,groupBy:a,id:o,isDisabled:s,items:c,onOpenChange:l,onCommit:u,multiple:d,controlledOpen:f,controlledKeys:p,trigger:m}){let h=`${o}-listbox`,[g,_]=(0,Q.useState)(e),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(n),[S,C]=(0,Q.useState)(t),w=p??(b===null?[]:[b]),T=m?f??S:!0,E=(0,Q.useMemo)(()=>{let e=g.trim().toLowerCase();return e?c.filter(t=>i(t).toLowerCase().includes(e)):c},[i,c,g]),D=Ce({getKey:r,isDisabled:s,items:E});(0,Q.useEffect)(()=>{if(D.activeKey!==null)return;let e=D.enabledItems.find(e=>w.includes(r(e)))??D.enabledItems[0];e&&D.setActiveKey(r(e))},[D.activeKey,D.enabledItems,D.setActiveKey,r,w]);let O=e=>{y(!1),e||_(``),f===void 0&&C(e),l?.(e)},k=e=>`${h}-option-${encodeURIComponent(e)}`,A=e=>{let t=r(e);p===void 0&&x(t),u(e),m&&!d&&O(!1)},j=e=>{y(!0),_(e.target.value),D.setActiveKey(null)},M=e=>{if(_e(e))return;let t;switch(e.key){case`ArrowDown`:t=[1,void 0];break;case`ArrowUp`:t=[-1,void 0];break;case`End`:t=[1,`end`];break;case`Home`:t=[-1,`start`]}t?(y(!0),e.preventDefault(),D.move(t[0],t[1])):e.key===`Enter`&&D.activeItem&&(e.preventDefault(),A(D.activeItem))},N=(0,Q.useMemo)(()=>{if(!a)return[{label:``,items:E}];let e=new Map;for(let t of E){let n=a(t),r=e.get(n);r?r.push(t):e.set(n,[t])}return[...e].map(([e,t])=>({label:e,items:t}))},[E,a]);return{keyboardNavigation:v,onPointerMove:()=>{y(!1)},activeKey:D.activeKey,activeItem:D.activeItem,groups:N,inputValue:g,listboxId:h,onInputChange:j,onInputKeyDown:M,optionId:k,open:T,commit:A,selectedKeys:w,setOpen:O}}function kO(e){let{"aria-describedby":t,"aria-invalid":n,"aria-label":r,"aria-labelledby":i,"aria-required":a,activeTone:o=`neutral`,container:s,contentClassName:c,defaultInputValue:l=``,defaultOpen:u=!1,defaultValue:d=null,emptyMessage:f=`No matches`,getKey:p,getLabel:m,getSearchText:h=m,groupBy:g,id:_,inputProps:v,inputRef:y,isDisabled:b=()=>!1,items:x,onOpenChange:S,onValueChange:C,multiple:w,open:T,placeholder:E=`Search…`,renderItem:D,rootRef:O,trigger:k,triggerRef:A,value:j,...M}=e,ee=e=>{let t=p(e);if(w){let e=j.includes(t)?j.filter(e=>e!==t):[...j,t];C?.(e,x.filter(t=>e.includes(p(t))))}else C?.(t,e)},te;w?te=j:j!==void 0&&(te=j===null?[]:[j]);let P=(0,Q.useId)(),F=k?.props??v,re=_??F?.id??P,I={id:re,"aria-describedby":[t,F?.[`aria-describedby`]].filter(Boolean).join(` `)||void 0,"aria-invalid":n??F?.[`aria-invalid`],"aria-label":F?.[`aria-label`]??r,"aria-labelledby":F?.[`aria-labelledby`]??i,"aria-required":a??F?.[`aria-required`]},{keyboardNavigation:L,onPointerMove:R,activeItem:z,activeKey:ie,commit:ae,groups:oe,inputValue:se,listboxId:B,onInputChange:ce,onInputKeyDown:le,open:ue,optionId:V,selectedKeys:de,setOpen:H}=OO({defaultInputValue:l,defaultOpen:u,defaultValue:d,getKey:p,getSearchText:h,groupBy:g,id:re,isDisabled:b,items:x,onOpenChange:S,onCommit:ee,multiple:w??!1,controlledOpen:T,controlledKeys:te,trigger:k});ne(()=>{k&&H(!1)});let pe=fe(`popover`),me=s===void 0?pe:s,he=rr(`.caps-combobox-option[data-active="true"]:not(:disabled), [data-navigation="pointer"] .caps-combobox-option:hover:not(:disabled)`),ge=(0,$.jsx)(wn,{...v,...k?{}:I,"aria-activedescendant":z?V(p(z)):void 0,"aria-autocomplete":`list`,"aria-controls":B,"aria-expanded":!0,className:N(`input-sm`,v?.className),id:k?v?.id??`${re}-input`:re,onChange:e=>{v?.onChange?.(e),ce(e)},onKeyDown:e=>{v?.onKeyDown?.(e),e.defaultPrevented||le(e)},placeholder:v?.placeholder??E,ref:y,role:`combobox`,value:se}),_e=(0,$.jsx)(`div`,{id:B,ref:he,className:`caps-combobox-list`,"data-navigation":L?`keyboard`:`pointer`,onPointerMove:R,role:`listbox`,"aria-multiselectable":w??void 0,children:oe.every(e=>e.items.length===0)?(0,$.jsx)(`div`,{className:`px-md py-md text-sm text-base-content`,children:f}):oe.map(e=>(0,$.jsxs)(`div`,{"aria-label":e.label||void 0,role:e.label?`group`:void 0,children:[e.label?(0,$.jsx)(`div`,{className:`px-md pb-xs pt-sm text-xs text-base-content uppercase tracking-wider`,children:e.label}):null,e.items.map(e=>{let t=p(e),n=b(e),r=ie===t,i={active:r,disabled:n,selected:de.includes(t)};return(0,$.jsxs)(`button`,{"aria-disabled":n||void 0,"aria-selected":i.selected,className:`caps-combobox-option`,"data-active":r&&L,disabled:n,id:V(t),onClick:()=>{ae(e)},onMouseDown:e=>{e.preventDefault()},role:`option`,tabIndex:-1,type:`button`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`caps-combobox-check`,children:i.selected?(0,$.jsx)(Le,{}):null}),D?.(e,r,i)??m(e)]},t)})]},e.label))});return k?(0,$.jsx)(`div`,{...M,className:N(M.className),ref:O,children:(0,$.jsxs)(mO,{modal:!0,onOpenChange:H,open:ue,children:[(0,$.jsx)(_O,{...I,"aria-haspopup":`dialog`,className:`btn`,ref:A,render:k}),me===null?null:(0,$.jsx)(bO,{container:me,children:(0,$.jsx)(CO,{align:`start`,side:`bottom`,sideOffset:4,children:(0,$.jsxs)(EO,{"data-active-tone":o,className:N(`min-w-40 rounded-box border border-base-300 bg-base-100 p-xs shadow-lg outline-none caps-combobox-panel caps-combobox-popup`,c),children:[(0,$.jsx)(`div`,{className:`caps-combobox-search`,children:ge}),_e]})})})]})}):(0,$.jsx)(`div`,{...M,className:N(M.className),ref:O,children:(0,$.jsxs)(`div`,{className:N(`caps-combobox-panel`,c),"data-active-tone":o,children:[(0,$.jsx)(`div`,{className:`caps-combobox-search`,children:ge}),_e]})})}function AO({icon:e,caption:t}){return(0,$.jsxs)(`span`,{className:`caps-icon-choice-mark`,"aria-hidden":`true`,children:[(0,$.jsx)(`span`,{className:`caps-icon-choice-art`,children:e}),t?(0,$.jsx)(`span`,{className:`caps-icon-choice-caption`,children:t}):null,(0,$.jsx)(`span`,{className:`caps-icon-choice-lamp`})]})}var jO=(0,Q.forwardRef)(function({label:e,icon:t,caption:n,appearance:r,className:i,...a},o){return(0,$.jsx)(`label`,{className:`caps-icon-choice`,"data-appearance":r===`compact`?r:void 0,children:(0,$.jsx)(s,{...a,appearance:r??`default`,"aria-label":e,className:N(`caps-icon-choice-input`,i),indicator:(0,$.jsx)(AO,{icon:t,caption:n}),ref:o})})}),MO=(0,Q.forwardRef)(function({label:e,icon:t,hint:n,className:r,...i},a){let o=(0,Q.useId)(),c=[i[`aria-describedby`],n?o:null].filter(Boolean).join(` `)||void 0;return(0,$.jsx)(`label`,{className:`caps-check-key`,children:(0,$.jsx)(s,{...i,"aria-label":e,"aria-describedby":c,className:N(`caps-check-key-input`,r),indicator:(0,$.jsxs)(`span`,{className:`caps-check-key-face`,"aria-hidden":`true`,children:[t?(0,$.jsx)(`span`,{className:`caps-check-key-icon`,children:t}):null,(0,$.jsxs)(`span`,{className:`caps-check-key-copy`,children:[(0,$.jsx)(`span`,{className:`caps-check-key-label`,children:e}),n?(0,$.jsx)(`span`,{className:`caps-check-key-hint`,id:o,children:n}):null]}),(0,$.jsx)(`span`,{className:`caps-check-key-lamp`})]}),ref:a})})});function NO({className:e,...t}){return(0,$.jsx)(`div`,{...t,className:N(`caps-check-keys`,e)})}function PO({checked:e}){let t=`caps-radio-${(0,Q.useId)().replaceAll(`:`,``)}`,n=(0,Q.useRef)(null),r=(0,Q.useRef)(e).current,i=(0,Q.useRef)(e),a=(0,Q.useRef)(null),o=Ze(a),{reduced:s}=o;return(0,Q.useLayoutEffect)(()=>{if(!n.current)return;let t=s||i.current===e;i.current=e;let r=e?4:0,a=Hn(o,{ease:`outCubic`,duration:75}),c=e?cr(o,{bounce:.65,duration:300}):Hn(o,{ease:`inCubic`,duration:100}),l=pc(n.current,t?{rx:r,ry:r,cy:6,duration:0}:{rx:[{to:e?3.5:4.15,...a},{to:r,...c}],ry:[{to:e?4.5:3.85,...a},{to:r,...c}],cy:[{to:e?5.85:6.1,...a},{to:6,...c}]});return()=>{l.cancel()}},[e,s,o]),(0,$.jsxs)(`svg`,{ref:a,className:`caps-radio-visual`,width:`24`,height:`24`,viewBox:`0 0 12 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,$.jsxs)(`defs`,{children:[(0,$.jsx)(Re,{id:`${t}-surface`,transform:`matrix(1 0 0 1 6 6)`}),(0,$.jsx)(me,{id:`${t}-shadow`}),(0,$.jsx)(R,{id:`${t}-inset`}),(0,$.jsx)(`clipPath`,{id:`${t}-well`,children:(0,$.jsx)(`circle`,{cx:`6`,cy:`6`,r:`5`})})]}),(0,$.jsx)(`circle`,{className:`caps-radio-track`,cx:`6`,cy:`6`,r:`5.5`,filter:`url(#${t}-inset)`}),(0,$.jsx)(`g`,{clipPath:`url(#${t}-well)`,children:(0,$.jsx)(`ellipse`,{ref:n,cx:`6`,cy:`6`,rx:r?4:0,ry:r?4:0,fill:`url(#${t}-surface)`,filter:`url(#${t}-shadow)`})})]})}var FO=(0,Q.createContext)(null),IO=(0,Q.forwardRef)(function({children:e,className:t,defaultValue:n,disabled:r=!1,name:i,onValueChange:a,orientation:o=`vertical`,value:s,...c},l){let u=(0,Q.useId)(),d=(0,Q.useRef)(null);(0,Q.useImperativeHandle)(l,()=>{if(!d.current)throw Error(`RadioGroup is not mounted`);return d.current},[]);let f=i??`radio-group-${u}`,[p,m]=(0,Q.useState)(n),h=s??p;return(0,Q.useEffect)(()=>{let e=d.current?.form;if(!e||s!==void 0)return;let t=e=>{queueMicrotask(()=>{e.defaultPrevented||m(n)})};return e.addEventListener(`reset`,t),()=>{e.removeEventListener(`reset`,t)}},[s,n,c.form]),(0,$.jsx)(FO.Provider,{value:{disabled:r,name:f,onValueChange:e=>{s===void 0&&m(e),a?.(e)},value:h},children:(0,$.jsx)(`fieldset`,{...c,className:N(`flex gap-md`,o===`horizontal`?`flex-row flex-wrap`:`flex-col`,t),disabled:r,role:c.role??`radiogroup`,ref:d,children:e})})}),LO=(0,Q.forwardRef)(function({className:e,indicator:t,onChange:n,onClick:r,value:i,...a},o){let s=(0,Q.useContext)(FO);if(!s)throw Error(`RadioGroupItem must be used inside <RadioGroup>`);let c=s.value===i,l=e=>{n?.(e),e.target.checked&&s.onValueChange?.(i)};return(0,$.jsxs)(`span`,{className:`caps-radio`,"data-checked":c,"data-custom-indicator":t!==void 0||void 0,children:[(0,$.jsx)(`input`,{...a,"aria-checked":c,checked:c,className:N(`caps-radio-input`,e),disabled:s.disabled||a.disabled,name:s.name,onChange:l,onClick:r,ref:o,type:`radio`,value:i}),t===void 0?(0,$.jsx)(PO,{checked:c}):t]})}),RO=(0,Q.forwardRef)(function({description:e,id:t,meta:n,title:r,...i},a){let o=(0,Q.useContext)(FO),s=(0,Q.useId)(),c=t??s,l=o?.value===i.value,u=o?.disabled===!0||i.disabled===!0;return(0,$.jsxs)(`label`,{className:`caps-choice-card`,"data-checked":l,"data-disabled":u||void 0,htmlFor:c,children:[(0,$.jsx)(LO,{...i,"aria-describedby":e?`${c}-description`:void 0,"aria-labelledby":`${c}-title`,id:c,ref:a}),(0,$.jsxs)(`span`,{className:`caps-choice-card-copy`,children:[(0,$.jsx)(`span`,{className:`caps-choice-card-title`,id:`${c}-title`,children:r}),e?(0,$.jsx)(`span`,{className:`caps-choice-card-description`,id:`${c}-description`,children:e}):null]}),n?(0,$.jsx)(`span`,{className:`caps-choice-card-meta`,children:n}):null]})}),zO=(0,Q.forwardRef)(function({label:e,icon:t,caption:n,art:r=`dim`,className:i,...a},o){return(0,$.jsx)(`label`,{className:`caps-icon-choice`,"data-art":r===`color`?r:void 0,children:(0,$.jsx)(LO,{...a,"aria-label":e,className:N(`caps-icon-choice-input`,i),indicator:(0,$.jsx)(AO,{icon:t,caption:n}),ref:o})})}),BO=(0,Q.forwardRef)(function({label:e,color:t,className:n,...r},i){return(0,$.jsx)(`label`,{className:`caps-icon-choice`,"data-art":`color`,"data-swatch":``,title:e,children:(0,$.jsx)(LO,{...r,"aria-label":e,className:N(`caps-icon-choice-input`,n),indicator:(0,$.jsx)(AO,{icon:(0,$.jsx)(`span`,{className:`caps-swatch-dot`,style:{backgroundColor:t}})}),ref:i})})}),VO=(0,Q.forwardRef)(function({className:e,invalid:t,...n},r){return(0,$.jsxs)(`span`,{className:`caps-select-shell`,children:[(0,$.jsx)(`select`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:N(`select select-bordered caps-select w-full`,t&&`select-error`,e),ref:r}),!n.multiple&&(!n.size||n.size<=1)?(0,$.jsx)(pe,{className:`caps-select-chevron`,"aria-hidden":`true`}):null]})});function HO({checked:e}){let t=`caps-switch-${(0,Q.useId)().replaceAll(`:`,``)}`,n=(0,Q.useRef)(null),r=(0,Q.useRef)(null),i=(0,Q.useRef)(e).current,a=(0,Q.useRef)(e),o=at();return(0,Q.useLayoutEffect)(()=>{if(!n.current||!r.current)return;let t=o||a.current===e;a.current=e;let i=e?16:8,s=F(n.current),c=cr(s,{bounce:.25,duration:440}),l=Hn(s,{ease:`inOutSine`,duration:100}),u=pc(n.current,t?{x:2,y:2,width:i,height:8,duration:0}:{x:[{to:e?2.5:1.5,...l},{to:2,...c}],y:[{to:1.5,...l},{to:2,...c}],height:[{to:9,...l},{to:8,...c}],width:[{to:e?7:16.5,...l},{to:i,...c}]}),d=pc(r.current,{gradientTransform:e?`matrix(2 0 0 1 10 6)`:`matrix(1 0 0 1 6 6)`,...t?{duration:0}:{delay:l.duration,...c}});return()=>{u.cancel(),d.cancel()}},[e,o]),(0,$.jsxs)(`svg`,{className:`caps-switch-visual`,width:`40`,height:`24`,viewBox:`0 0 20 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,$.jsxs)(`defs`,{children:[(0,$.jsx)(Re,{ref:r,id:`${t}-surface`,transform:i?`matrix(2 0 0 1 10 6)`:`matrix(1 0 0 1 6 6)`}),(0,$.jsx)(me,{id:`${t}-shadow`}),(0,$.jsx)(R,{id:`${t}-inset`}),(0,$.jsx)(`clipPath`,{id:`${t}-track`,children:(0,$.jsx)(`rect`,{x:`1`,y:`1`,width:`18`,height:`10`,rx:`5`})})]}),(0,$.jsx)(`rect`,{className:`caps-switch-track`,filter:`url(#${t}-inset)`,x:`0.5`,y:`0.5`,width:`19`,height:`11`,rx:`5.5`}),(0,$.jsx)(`g`,{clipPath:`url(#${t}-track)`,children:(0,$.jsx)(`rect`,{ref:n,x:`2`,y:`2`,width:i?16:8,height:`8`,rx:`4`,fill:`url(#${t}-surface)`,filter:`url(#${t}-shadow)`})})]})}var UO=(0,Q.forwardRef)(function({className:e,checked:t,defaultChecked:n=!1,onChange:r,onCheckedChange:i,...a},o){let s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(n),u=t??c;return(0,Q.useImperativeHandle)(o,()=>{if(!s.current)throw Error(`Switch input is not mounted`);return s.current},[]),(0,Q.useEffect)(()=>{let e=s.current?.form;if(!e||t!==void 0)return;let r=e=>{queueMicrotask(()=>{!e.defaultPrevented&&s.current&&l(n)})};return e.addEventListener(`reset`,r),()=>{e.removeEventListener(`reset`,r)}},[t,n,a.form]),(0,$.jsxs)(`span`,{className:`caps-switch`,"data-checked":u,children:[(0,$.jsx)(`input`,{...a,checked:u,className:N(`caps-switch-input`,e),onChange:e=>{t===void 0&&l(e.target.checked),r?.(e),i?.(e.target.checked)},ref:s,role:`switch`,type:`checkbox`}),(0,$.jsx)(HO,{checked:u})]})}),WO=Na(Y),GO=Na(Ko),KO=Na(vo($a)),qO=Na(uo(Y)),JO=uo(zo(File)),YO=Na(JO),XO=q([Y,$a,Ko,pa,ha,uo(Y),JO]),ZO=Na(XO),QO=e=>Xi(WO(e.state.value),()=>``),$O=e=>Xi(GO(e.state.value),()=>!1),ek=e=>Xi(KO(e.state.value),()=>null),tk=e=>Xi(qO(e.state.value),()=>[]),nk=e=>Xi(YO(e.state.value),()=>[]),rk=e=>Xi(ZO(e.state.value),()=>null);function ik({field:e,spec:t,locked:n,...r}){let[i,a]=(0,Q.useState)(!1);return(0,$.jsxs)(Ve,{children:[(0,$.jsx)(wn,{...r,name:t.name,disabled:n,type:i?`text`:`password`,autoComplete:`off`,spellCheck:!1,className:`caps-field-secret`,placeholder:t.placeholder,readOnly:t.readOnly,value:QO(e),onBlur:e.handleBlur,onChange:t=>{e.handleChange(t.currentTarget.value)}}),(0,$.jsx)(W,{type:`button`,variant:`outline`,size:`icon`,"aria-label":i?`Hide`:`Show`,"aria-pressed":i,disabled:n,onClick:()=>{a(e=>!e)},children:i?(0,$.jsx)(FC,{"aria-hidden":`true`}):(0,$.jsx)(IC,{"aria-hidden":`true`})})]})}var ak={text:`text`,email:`email`,url:`url`,tel:`tel`};function ok({spec:e,field:t,locked:n,...r}){let i=nk(t),a=n||e.readOnly===!0,o=(0,Q.useRef)(null);return(0,$.jsxs)(`div`,{className:`flex flex-col gap-sm`,children:[(0,$.jsx)(Vr,{asChild:!0,children:(0,$.jsx)(`input`,{...r,ref:o,type:`file`,tabIndex:-1,required:r.required===!0&&i.length===0,name:e.name,accept:e.accept,multiple:e.multiple,disabled:a,onBlur:t.handleBlur,onChange:e=>{t.handleChange(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}})}),(0,$.jsx)(W,{type:`button`,variant:`outline`,"aria-label":`Choose files for ${e.label}`,"aria-describedby":r[`aria-describedby`],"aria-invalid":r[`aria-invalid`],disabled:a,onBlur:t.handleBlur,onClick:()=>{o.current?.click()},children:`Choose files`}),(0,$.jsx)(nO,{items:i.map((e,t)=>({id:String(t),name:e.name,preview:{kind:`file`},progress:0,progressLabel:`${String(e.size)} bytes`,statusLabel:`Selected`,actions:a?{}:{remove:{label:`Remove`,accessibleLabel:`Remove ${e.name}`}}})),onRemove:e=>{t.handleChange(i.filter((t,n)=>String(n)!==e))},onCancel:()=>void 0,onRetry:()=>void 0})]})}function sk({spec:e,field:t,locked:n,...r}){let i=e=>{t.handleChange(e)},a={...r,name:e.name,disabled:n,onBlur:t.handleBlur};switch(e.kind){case`text`:case`email`:case`url`:case`tel`:return(0,$.jsx)(wn,{...a,type:ak[e.kind],inputMode:e.kind===`text`?void 0:e.kind,autoComplete:e.autoComplete,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:QO(t),onChange:e=>{i(e.currentTarget.value)}});case`textarea`:return(0,$.jsx)(bn,{...a,rows:e.rows??3,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:QO(t),onChange:e=>{i(e.currentTarget.value)}});case`secret`:return(0,$.jsx)(ik,{...r,field:t,spec:e,locked:n});case`money`:return(0,$.jsxs)(Ve,{children:[(0,$.jsx)(h,{className:`caps-field-currency`,children:e.currency??`USD`}),(0,$.jsx)(wn,{...a,inputMode:`decimal`,autoComplete:`off`,className:`caps-field-amount`,placeholder:e.placeholder??`0.00`,readOnly:e.readOnly,value:QO(t),onChange:e=>{i(e.currentTarget.value)}})]});case`date`:return(0,$.jsx)(wn,{...a,type:`date`,readOnly:e.readOnly,value:QO(t),onChange:e=>{i(e.currentTarget.value)}});case`number`:return(0,$.jsx)(jr,{...a,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},...e.step===void 0?{}:{step:e.step},...e.unit===void 0?{}:{unit:e.unit},...e.wrap===void 0?{}:{wrap:e.wrap},disabled:n||e.readOnly===!0,decrementLabel:`Decrease ${e.label}`,incrementLabel:`Increase ${e.label}`,value:ek(t),onValueChange:e=>{t.handleChange(e)}});case`select`:return(0,$.jsxs)(VO,{...a,value:QO(t),onChange:e=>{i(e.currentTarget.value)},children:[e.placeholder===void 0?null:(0,$.jsx)(`option`,{value:``,disabled:!0,children:e.placeholder}),e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,disabled:e.disabled,children:e.label},e.value))]});case`combobox`:return(0,$.jsx)(kO,{id:r.id??e.name,"aria-describedby":r[`aria-describedby`],"aria-invalid":r[`aria-invalid`],"aria-required":r[`aria-required`],items:e.options,getKey:e=>e.value,getLabel:e=>e.label,isDisabled:t=>t.disabled||n||e.readOnly===!0,value:QO(t),...e.placeholder===void 0?{}:{placeholder:e.placeholder},trigger:(0,$.jsx)(DO,{name:e.name,disabled:n||e.readOnly===!0,onBlur:t.handleBlur,children:e.options.find(e=>e.value===QO(t))?.label??e.placeholder??`Choose…`}),inputProps:{"aria-label":`Search ${e.label}`,disabled:n||e.readOnly===!0},onValueChange:e=>{i(e??``),t.handleBlur()}});case`file`:return(0,$.jsx)(ok,{...r,spec:e,field:t,locked:n});case`checkbox`:return(0,$.jsx)(s,{...a,disabled:n||e.readOnly===!0,checked:$O(t),onChange:e=>{t.handleChange(e.currentTarget.checked)}});case`switch`:return(0,$.jsx)(UO,{...a,disabled:n||e.readOnly===!0,checked:$O(t),onCheckedChange:e=>{t.handleChange(e)}});case`radio`:case`icon-radio`:case`checkboxes`:case`icon-checkboxes`:return null}}var ck=new Set([`radio`,`icon-radio`,`checkboxes`,`icon-checkboxes`]);function lk({spec:e,field:t,locked:n,error:r,layout:i}){let a=n||e.readOnly===!0,o=e.label;if(e.kind===`checkboxes`||e.kind===`icon-checkboxes`){let n=tk(t),s=(e,r)=>{t.handleChange(r?[...n,e]:n.filter(t=>t!==e))};return(0,$.jsx)(wt,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:e.kind===`icon-checkboxes`?(0,$.jsx)(`div`,{className:`caps-field-icon-choices`,children:e.options.map(r=>(0,$.jsx)(jO,{name:e.name,value:r.value,label:r.label,...r.caption===void 0?{}:{caption:r.caption},icon:r.icon,disabled:r.disabled,checked:n.includes(r.value),onBlur:t.handleBlur,onChange:e=>{s(r.value,e.currentTarget.checked)}},r.value))}):(0,$.jsx)(NO,{children:e.options.map(r=>(0,$.jsx)(MO,{name:e.name,value:r.value,label:r.label,icon:r.icon,hint:r.description,disabled:r.disabled,checked:n.includes(r.value),onBlur:t.handleBlur,onChange:e=>{s(r.value,e.currentTarget.checked)}},r.value))})})}let s=e.options.some(e=>e.description!==void 0||e.meta!==void 0);return(0,$.jsx)(wt,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:(0,$.jsx)(IO,{name:e.name,"aria-label":o,value:QO(t),onValueChange:e=>{t.handleChange(e),t.handleBlur()},orientation:e.kind===`icon-radio`||s?`horizontal`:`vertical`,children:e.options.map(t=>e.kind===`icon-radio`?(0,$.jsx)(zO,{value:t.value,label:t.label,...t.caption===void 0?{}:{caption:t.caption},icon:t.icon,disabled:t.disabled},t.value):s?(0,$.jsx)(RO,{value:t.value,title:t.label,description:t.description,meta:t.meta,disabled:t.disabled},t.value):(0,$.jsx)(un,{label:t.label,orientation:`inline`,children:(0,$.jsx)(LO,{value:t.value,disabled:t.disabled})},t.value))})})}function uk({spec:e,field:t,locked:n,error:r,render:i,...a}){return i({name:e.name,label:e.label,help:e.help,value:rk(t),onChange:e=>{t.handleChange(e)},onBlur:t.handleBlur,error:r,disabled:n,id:a.id??e.name,"aria-describedby":a[`aria-describedby`],"aria-invalid":r!==void 0})}function dk({form:e,spec:t,locked:n,layout:r}){let i=HD({form:e,name:t.name}),a=BD(e.store,e=>e.submissionAttempts>0),o=i.state.meta.isBlurred||a?$D(i.state.meta):void 0;if(t.render===void 0&&ck.has(t.kind))return(0,$.jsx)(lk,{spec:t,field:i,locked:n,error:o,layout:r});let s=r===`columns`?t.kind===`switch`||t.kind===`checkbox`?`horizontal`:`vertical`:t.kind===`checkbox`?`inline`:(t.layout??(t.kind===`switch`?`row`:`stacked`))===`row`?`horizontal`:`vertical`;return(0,$.jsx)(un,{label:t.label,...r===`columns`?{labelTitle:t.label}:{},description:t.help,icon:t.icon,orientation:s,error:o,...t.required===void 0?{}:{required:t.required},...t.optional===void 0?{}:{optional:t.optional},children:t.render===void 0?(0,$.jsx)(sk,{spec:t,field:i,locked:n}):(0,$.jsx)(uk,{spec:t,field:i,locked:n,error:o,render:t.render})})}var fk=Na(Aa(Y,XO));function pk({form:e,spec:t,locked:n,layout:r}){let i=t.when;return BD(e.store,e=>i===void 0||i(Xi(fk(e.values),()=>({}))))?(0,$.jsx)(dk,{form:e,spec:t,locked:n,layout:r}):null}function mk({form:e,section:t,locked:n,layout:r}){let i=t.fields.map(t=>(0,$.jsx)(pk,{form:e,spec:t,locked:n,layout:r},t.name));return t.title===void 0?i:(0,$.jsx)(Ft,{title:t.title,description:t.description,layout:r,children:i})}function hk({model:e,names:t,disabled:n=!1,layout:r}){let i=e.form;return t===void 0?e.description.sections.map(e=>(0,$.jsx)(mk,{form:i,section:e,locked:n,layout:r},e.id??``)):t.map(t=>{let a=e.description.fields.find(e=>e.name===t);return a===void 0?null:(0,$.jsx)(pk,{form:i,spec:a,locked:n,layout:r},t)})}var gk=class{annotation;constructor(e){this.annotation=e}},_k=class{sections;constructor(e){this.sections=e}},vk=`caps/form`,yk=0;function bk(e){yk+=1;let t={[`${vk}:${String(yk)}`]:new gk(e)};return e.label!==void 0&&(t.title=e.label),e.help!==void 0&&(t.description=e.help),t}Y.annotate(bk({kind:`secret`})).pipe(Ua(`Secret`));var xk=e=>{let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[-_]+/g,` `).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)};function Sk(e){return Object.values(e??{}).reduce((e,t)=>t instanceof gk?{...e,...t.annotation}:e,{})}function Ck(e){return e.reduce((e,t)=>({...e,...Sk(t)}),{})}function wk(e){let t=e?.[vk];return t instanceof _k?t.sections:{}}var Tk=Na(Y);function Ek(e){if(no(e))return ta(Tk(e.literal),{onNone:()=>null,onSome:e=>[e]});if(!Do(e))return null;let t=[];for(let n of e.types){if(Po(n))continue;let e=Ek(n);if(e===null)return null;t.push(...e)}return t}function Dk(e){if(lo(e))return{type:`string`,literals:[]};if(Uo(e))return{type:`number`,nullable:!1};if(jo(e))return{type:`boolean`};let t=Ek(e);if(t!==null)return{type:`string`,literals:t};if(Qa(e)){let[t]=e.rest;if(t===void 0)return null;if(lo(t))return{type:`strings`,literals:[]};let n=Ek(t);return n===null?null:{type:`strings`,literals:n}}if(Do(e)){let t=e.types.filter(e=>!Po(e)&&!Co(e)),n=e.types.some(e=>Co(e)),[r]=t;if(t.length!==1||r===void 0)return null;let i=Dk(r);return i?.type===`number`?{type:`number`,nullable:n}:n?null:i}return null}function Ok(e){let t=e.ast;if(!ao(t))throw Error(`A schema form needs a Schema.Struct.`);return{fields:t.propertySignatures.map(e=>{let t=String(e.name),n=qo(e.type),r=Ck([e.type.annotations,...(e.type.checks??[]).map(e=>e.annotations)]),i=r.kind===`file`?{type:`files`}:Dk(n);if(i===null)throw Error(`Schema field "${t}" has no form control. Annotate it with field({ render }) or a kind.`);return{name:t,valueType:i,optional:e.type.context?.isOptional===!0,annotation:r,title:Xa(e.type),description:fo(e.type)}}),sections:wk(mo(t))}}function kk(e){let t=e,n=!1,r=!1;for(;;)if(t instanceof ni)n=!0,t=t.unwrap();else if(t instanceof li)r=!0,t=t.unwrap();else if(t instanceof Gr)t=t.unwrap();else if(t instanceof Ji)t=t.in;else return{node:t,optional:n,nullable:r}}function Ak(e){if(e instanceof pi){let t=e.options.map(e=>Ak(e));return t.some(e=>e===null)?null:t.flatMap(e=>e??[])}let t=e instanceof di?e.options:e instanceof Qr?[...e.values]:null;if(t===null)return null;let n=t.map(e=>Tk(e));return n.every(Qi)?n.map(e=>e.value):null}function jk(e){let{node:t,nullable:n}=kk(e);if(t instanceof ei)return{type:`string`,literals:[]};if(t instanceof fi)return{type:`number`,nullable:n};if(t instanceof la)return{type:`boolean`};let r=Ak(t);if(r!==null)return{type:`string`,literals:r};if(t instanceof oi){let e=kk(t.element).node;if(e instanceof ei)return{type:`strings`,literals:[]};let n=Ak(e);return n===null?null:{type:`strings`,literals:n}}return null}function Mk(e){let t=[e];for(;;){let e=t[t.length-1];if(e===void 0)break;let n=e instanceof ni||e instanceof li||e instanceof Gr?e.unwrap():e instanceof Ji?e.in:e;if(n===e)break;t.push(n)}return t.reverse().map(e=>ca.get(e))}function Nk(e){return Mk(e).reduce((e,t)=>({...e,...t}),{})}function Pk(e){return Object.entries(e.shape)}function Fk(e){let t=kk(e).node;if(!(t instanceof Zr))throw Error(`A schema form needs a z.object.`);return{fields:Pk(t).map(([e,t])=>{let n=Ck(Mk(t)),r=n.kind===`file`?{type:`files`}:jk(t);if(r===null)throw Error(`Schema field "${e}" has no form control. Annotate it with field({ render }) or a kind.`);let i=Nk(t);return{name:e,valueType:r,optional:kk(t).optional,annotation:n,title:i.title,description:i.description}}),sections:wk(Nk(e))}}function Ik(e,t){let n=t.options??{};return(e.length>0?e:Object.keys(n)).map(e=>{let t=n[e],r=t===void 0?{}:t instanceof Object?t:{label:t};return{value:e,label:r.label??xk(e),description:r.description,meta:r.meta,icon:r.icon,caption:r.caption,disabled:r.disabled===!0}})}function Lk(e,t){let n=t.some(e=>e.icon!==void 0);switch(e.type){case`boolean`:return`switch`;case`number`:return`number`;case`strings`:return n?`icon-checkboxes`:`checkboxes`;case`files`:return`file`;case`string`:return t.length===0?`text`:t.length>12?`combobox`:n?`icon-radio`:t.some(e=>e.description!==void 0||e.meta!==void 0)||t.length<=3?`radio`:`select`}}function Rk(e,t){switch(e.type){case`boolean`:return!1;case`number`:return e.nullable?null:0;case`strings`:case`files`:return[];case`string`:return t[0]?.value??``}}function zk(e){let t=e instanceof hi?Fk(e):Ok(e),n=t.fields.map((e,t)=>{let{kind:n,...r}=e.annotation,i=Ik(e.valueType.type===`string`||e.valueType.type===`strings`?e.valueType.literals:[],e.annotation),a=r.help??e.description;return{...r,name:e.name,label:r.label??e.title??xk(e.name),help:a,kind:n??Lk(e.valueType,i),options:i,optionalInSchema:e.optional,index:t}}),r={};t.fields.forEach((e,t)=>{let i=n[t];i&&(r[e.name]=Rk(e.valueType,i.options))});let i=e=>e.order??e.index,a=e=>e.section!==void 0&&Object.hasOwn(t.sections,e.section)?e.section:null,o=e=>n.filter(t=>a(t)===e).sort((e,t)=>i(e)-i(t)),s=Object.entries(t.sections).map(([e,t])=>({id:e,title:t.title,description:t.description,fields:o(e)}));return{fields:n,sections:[{id:null,title:void 0,description:void 0,fields:o(null)},...s].filter(e=>e.fields.length>0),defaults:r}}function Bk(e){let t=e instanceof hi?e:ua(e);return{"~standard":{...t[`~standard`],validate:e=>{let n=t[`~standard`].validate(e);return n instanceof Promise?n.then(e=>Vk(e)):Vk(n)}}}}function Vk(e){return e.issues===void 0?e:{issues:e.issues.map(e=>e.path===void 0?e:{...e,path:e.path.slice(0,1)})}}var Hk=`onServer`;function Uk(e){let t=e.querySelector(`[aria-invalid="true"]`),n=t?.matches(`input, select, textarea, button, [tabindex]`)?t:t?.querySelector(`input, select, textarea, button`);return n?.focus(),n!=null}function Wk(e){if(Uk(e))return()=>void 0;let t=new MutationObserver(()=>{Uk(e)&&t.disconnect()});return t.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[`aria-invalid`]}),()=>{t.disconnect()}}function Gk(e){return e.state.meta.errorMap.onServer!==void 0}function Kk(e){e.setMeta(e=>({...e,errorMap:{...e.errorMap,[Hk]:void 0}}))}function qk(e,t,n){e.setFieldMeta(t,e=>({...e,isBlurred:!0,errorMap:{...e.errorMap,[Hk]:n}}))}function Jk(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(e.defaultValues),[s,c]=(0,Q.useState)(null);aD(a,e.defaultValues)||(o(e.defaultValues),c(null));let{schema:l}=e,u=(0,Q.useMemo)(()=>zk(l),[l]),d=(0,Q.useMemo)(()=>Bk(l),[l]),f=XD({defaultValues:s??a,validators:{onChange:d,onSubmit:d},listeners:{onChange:({fieldApi:e})=>{n(null),i(null),Gk(e)&&Kk(e)}},onSubmit:async({value:t,formApi:r})=>{n(null),i(null);let a=await Bk(l)[`~standard`].validate(t);if(a.issues){n(a.issues[0]?.message??`Check the form and try again.`);return}let o;try{o=await e.onSubmit(a.value,t)??{kind:`saved`}}catch(t){console.error(`SchemaForm submit failed`,t),n(e.failure??`Couldn't save changes. Try again.`);return}if(o.kind===`refused`){n(o.error??null);let e=r;for(let[t,n]of Object.entries(o.fields??{}))n!==void 0&&n.length>0&&qk(e,t,n);return}let s=o.values??t;c(s),r.reset(s),i(o.message??`Saved`),e.onSaved?.(s)}});return{description:u,form:f,error:t,saved:r,discard:()=>{n(null),i(null),f.reset()},submit:()=>f.handleSubmit()}}function Yk(e){return{dirty:BD(e.form.store,e=>!e.isDefaultValue),submitting:BD(e.form.store,e=>e.isSubmitting),canSubmit:BD(e.form.store,e=>e.canSubmit)}}function Xk({model:e,submitLabel:t=`Save changes`,discardLabel:n,onCancel:r,cancelLabel:i,allowClean:a,layout:o,footer:s,children:c,disabled:l=!1,...u}){let{submitting:d}=Yk(e),f=(0,Q.useRef)(null),p=(0,Q.useRef)(()=>void 0);return(0,Q.useEffect)(()=>()=>{p.current()},[]),(0,$.jsxs)(xr,{...u,ref:f,layout:o,busy:d,noValidate:!0,onSubmit:t=>{t.preventDefault(),e.form.state.isSubmitting||e.submit().then(()=>{p.current();let t=f.current;t!==null&&!e.form.state.isValid&&(p.current=Wk(t))})},children:[c??(0,$.jsx)(hk,{model:e,disabled:l,layout:o}),s===void 0?(0,$.jsx)($k,{model:e,label:t,discardLabel:r===void 0?n:void 0,onCancel:r,cancelLabel:i,allowClean:a??r!==void 0,divider:r===void 0}):s]})}function Zk({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i,...a}){let o=Jk({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i});return(0,$.jsx)(Xk,{...a,model:o})}function Qk(e){return`model`in e?(0,$.jsx)(Xk,{...e}):(0,$.jsx)(Zk,{...e})}function $k({model:e,label:t,discardLabel:n,onCancel:r,cancelLabel:i=`Cancel`,allowClean:a=!1,dirtyLabel:o=`Unsaved changes`,buttonProps:s,...c}){let{dirty:l,submitting:u}=Yk(e),d=u?null:e.saved&&!l?(0,$.jsx)(_r,{tone:`success`,size:`compact`,label:e.saved}):l?(0,$.jsx)(_r,{tone:`neutral`,size:`compact`,label:o}):null;return(0,$.jsxs)(Pr,{...c,error:e.error,status:d,children:[r?(0,$.jsx)(W,{type:`button`,variant:`ghost`,disabled:u,onClick:r,children:i}):n&&l?(0,$.jsx)(W,{type:`button`,variant:`ghost`,disabled:u,onClick:e.discard,children:n}):null,(0,$.jsx)(W,{...s,type:`submit`,loading:u,disabled:u||!l&&!a,title:!l&&!a?`No changes to save`:void 0,children:t})]})}var eA=e=>e,tA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing burger path: ${t}`);return n},nA={apiVersion:1,name:`burger`,palette:{bottomBun:`#e9c46a`,bunSpot:`#d4a373`,cheese:`#f4d03f`,dead:`#636e72`,deadTongue:`#b2bec3`,eye:`#2d3436`,lettuce:`#7cb342`,mouth:`#2d3436`,patty:`#5d4037`,tomato:`#e74c3c`,topBun:`#f4a261`,blush:`#feaae4`,tongue:`#f98284`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.cylinder({parent:r,name:`bottom-bun`,backface:t(`bottomBun`),color:t(`bottomBun`),diameter:34,frontFace:t(`bunSpot`),length:6,rotate:{x:Math.PI/2},stroke:!1,translate:{y:8}}),e.cylinder({parent:r,name:`patty`,color:t(`patty`),diameter:36,frontFace:t(`patty`),length:4,rotate:{x:Math.PI/2},stroke:!1,translate:{y:3}}),e.cylinder({parent:r,name:`tomato`,color:t(`tomato`),diameter:34,frontFace:t(`tomato`),length:2,rotate:{x:Math.PI/2},stroke:!1,translate:{y:-2}});let i=e.hemisphere({parent:r,name:`top-bun`,backface:t(`bunSpot`),color:t(`topBun`),diameter:38,rotate:{x:Math.PI/2},stroke:!1,translate:{y:-3}});for(let[n,r]of[{x:-8,y:-6,z:14},{x:6,y:-8,z:13},{x:0,y:-10,z:12},{x:10,y:-4,z:13},{x:-5,y:-2,z:15},{x:4,y:-12,z:11}].entries())e.path({parent:i,name:`seed.${String(n+1)}`,path:[{x:0,y:0}],color:t(`bunSpot`),stroke:1.2,translate:r});let a=e.group({parent:r,name:`face`,translate:{y:-5,z:16}}),o=yc(e,t,a,{blushMode:`medium-alias`,hideMouth:!0}),s=e.group({parent:r,name:`burger.mouth`,translate:{y:1,z:10}}),c=eA({angry:[{x:-13,y:2},{x:13,y:2},{x:13,y:5},{bezier:[{x:7,y:4},{x:0,y:5},{x:-7,y:4}]},{x:-13,y:5}],happy:[{x:-12,y:0},{bezier:[{x:-6,y:3},{x:0,y:5},{x:6,y:3}]},{x:12,y:0},{x:13,y:2},{bezier:[{x:7,y:5},{x:0,y:7},{x:-7,y:5}]},{x:-13,y:2}],open:[{x:-10,y:0},{bezier:[{x:-10,y:5},{x:-5,y:8},{x:0,y:8}]},{bezier:[{x:5,y:8},{x:10,y:5},{x:10,y:0}]},{x:10,y:1},{bezier:[{x:5,y:6},{x:-5,y:6},{x:-10,y:1}]}],pout:[{x:-8,y:2},{bezier:[{x:0,y:5},{x:8,y:2},{x:8,y:4}]},{x:0,y:6},{x:-8,y:4}],sad:[{x:-12,y:3},{bezier:[{x:-6,y:0},{x:0,y:-1},{x:6,y:0}]},{x:12,y:3},{x:13,y:5},{bezier:[{x:7,y:2},{x:0,y:1},{x:-7,y:2}]},{x:-13,y:5}],small:[{x:-6,y:1},{x:6,y:1},{x:7,y:3},{x:0,y:2},{x:-7,y:3}],surprised:[],worried:[{x:-11,y:1},{bezier:[{x:-6,y:3},{x:-3,y:1},{x:0,y:2}]},{bezier:[{x:3,y:1},{x:6,y:3},{x:11,y:1}]},{x:12,y:3},{x:0,y:4},{x:-12,y:3}],dead:[{x:-12,y:1},{x:12,y:1},{x:13,y:4},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:4}],normal:[{x:-12,y:1},{x:12,y:1},{x:13,y:4},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:4}]}),l=eA({angry:[{x:-13,y:0},{x:13,y:0},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:2},{x:-7,y:1}]},{x:-13,y:2}],happy:[{x:-12,y:2},{bezier:[{x:-6,y:0},{x:0,y:-1},{x:6,y:0}]},{x:12,y:2},{x:13,y:3},{bezier:[{x:7,y:1},{x:0,y:0},{x:-7,y:1}]},{x:-13,y:3}],open:[{x:-10,y:2},{bezier:[{x:-10,y:-3},{x:-5,y:-6},{x:0,y:-6}]},{bezier:[{x:5,y:-6},{x:10,y:-3},{x:10,y:2}]},{x:10,y:1},{bezier:[{x:5,y:-4},{x:-5,y:-4},{x:-10,y:1}]}],pout:[{x:-8,y:0},{bezier:[{x:-4,y:-1},{x:0,y:0},{x:4,y:-1}]},{x:8,y:0},{x:9,y:1},{x:0,y:1},{x:-9,y:1}],sad:[{x:-12,y:0},{bezier:[{x:-6,y:2},{x:0,y:3},{x:6,y:2}]},{x:12,y:0},{x:13,y:1},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:1}],small:[{x:-6,y:0},{bezier:[{x:-3,y:1},{x:0,y:0},{x:3,y:1}]},{x:6,y:0},{x:7,y:1},{x:0,y:1},{x:-7,y:1}],surprised:[{x:-13,y:2},{bezier:[{x:-7,y:-2},{x:0,y:-3},{x:7,y:-2}]},{x:13,y:2},{x:14,y:3},{bezier:[{x:8,y:0},{x:0,y:-1},{x:-8,y:0}]},{x:-14,y:3}],worried:[{x:-11,y:1},{bezier:[{x:-6,y:0},{x:-3,y:1},{x:0,y:0}]},{bezier:[{x:3,y:2},{x:6,y:0},{x:11,y:1}]},{x:12,y:2},{bezier:[{x:7,y:1},{x:0,y:1},{x:-7,y:1}]},{x:-12,y:2}],dead:[{x:-12,y:1},{bezier:[{x:-6,y:0},{x:0,y:-.5},{x:6,y:0}]},{x:12,y:1},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:.5},{x:-7,y:1}]},{x:-13,y:2}],normal:[{x:-12,y:1},{bezier:[{x:-6,y:0},{x:0,y:-.5},{x:6,y:0}]},{x:12,y:1},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:.5},{x:-7,y:1}]},{x:-13,y:2}]}),u={};for(let n of[`normal`,`happy`,`sad`,`angry`,`surprised`,`dead`,`small`,`worried`,`pout`,`open`]){let r=e.group({parent:s,name:`burger.mouth.${n}`}),i={y:n===`open`?2:n===`small`?.5:1.5,z:+(n===`pout`)};n===`surprised`?e.ellipse({parent:r,name:`cheese.${n}`,color:t(`cheese`),fill:!0,height:8,stroke:2,translate:{y:2,z:0},width:6}):e.path({parent:r,name:`cheese.${n}`,color:t(`cheese`),fill:!0,path:tA(c,n),stroke:2,translate:i});let a={y:n===`open`?1:n===`surprised`?-1:-.5,z:n===`pout`?2:1};e.path({parent:r,name:`lettuce.${n}`,color:t(`lettuce`),fill:!0,path:tA(l,n),stroke:1.5,translate:a}),u[n]=r}return{root:n,variants:{eyes:o.eyes,mouth:u,blush:o.blush}}},expressions:vc,activities:bc,defaultPresentation:{activity:`idle`,expression:`normal`}},rA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing cat face node: ${t}`);return n},iA=e=>e,aA={apiVersion:1,name:`cat`,palette:{body:`#ffe6c6`,eye:`#28282e`,mouth:`#28282e`,blush:`#feaae4`,dead:`#6c5671`,deadTongue:`#d9c8bf`,tongue:`#f98284`,stripes:`#dea38b`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.path({parent:r,name:`body.sphere`,path:[{x:0,y:0}],color:t(`body`),stroke:32});for(let n of[-1,1])e.path({parent:r,name:`ear.${n<0?`left`:`right`}`,color:t(`body`),fill:!0,path:[{x:-6,y:0},{x:6,y:0},{x:0,y:-10}],rotate:{z:.6*n},stroke:3,translate:{x:9*n,y:-10}});let i=e.group({parent:r,name:`face`,translate:{z:20}}),a=yc(e,t,i,{hideMouth:!0}),o=e.group({parent:i,name:`cat.mouth`,translate:{y:6,z:2}}),s=(n,r,i)=>e.path({parent:o,name:`cat.mouth.${n}`,closed:!1,color:t(`mouth`),path:r,stroke:i}),c=iA({normal:s(`normal`,[{x:-2,y:-1},{x:0,y:0},{x:2,y:-1}],1.5),sad:s(`sad`,[{x:-2.5,y:2},{bezier:[{x:0,y:0},{x:2.5,y:2},{x:2.5,y:2}]}],1.5),angry:s(`angry`,[{x:-3,y:1},{x:3,y:1}],2),small:s(`small`,[{x:-1.5,y:0},{x:1.5,y:0}],1),worried:s(`worried`,[{x:-2,y:1},{bezier:[{x:-.5,y:.5},{x:.5,y:.5},{x:2,y:1}]}],1)}),l=e.group({parent:o,name:`cat.mouth.happy`,translate:{y:1}});e.path({parent:l,closed:!1,color:t(`mouth`),path:[{x:-2.5,y:1},{bezier:[{x:0,y:3},{x:2.5,y:1},{x:2.5,y:1}]}],stroke:1.5}),e.ellipse({parent:l,width:2,height:1.5,stroke:0,fill:!0,color:t(`tongue`),translate:{y:2}}),c.happy=l,c.surprised=e.ellipse({parent:o,name:`cat.mouth.surprised`,width:2.5,height:3,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}});let u=e.group({parent:o,name:`cat.mouth.dead`,translate:{y:3}});e.ellipse({parent:u,width:2.5,height:1.5,stroke:1.5,fill:!0,color:t(`dead`)}),e.ellipse({parent:u,width:1.2,height:.8,stroke:0,fill:!0,color:t(`deadTongue`),translate:{y:.5}}),c.dead=u,c.pout=e.ellipse({parent:o,name:`cat.mouth.pout`,width:2,height:2.5,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}}),c.open=e.ellipse({parent:o,name:`cat.mouth.open`,width:4,height:5,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}});let d=e.group({parent:i,name:`whiskers`,translate:{y:5,z:2}});for(let n of[-1,1]){let r=n*12;for(let[i,a]of[-2,0,2].entries())e.path({parent:d,name:`whisker.${n<0?`left`:`right`}.${String(i)}`,closed:!1,color:t(`eye`),path:[{x:0,y:a},{x:n*8,y:a+(i-1)*1.5}],stroke:.8,translate:{x:r,y:a*.5}})}let f={normal:rA(c,`normal`),happy:c.happy,sad:rA(c,`sad`),angry:rA(c,`angry`),surprised:c.surprised,dead:c.dead,small:rA(c,`small`),worried:rA(c,`worried`),pout:c.pout,open:c.open};return{root:n,variants:{eyes:a.eyes,mouth:f,blush:a.blush}}},expressions:vc,activities:{...bc,listening:{motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3},thinking:{motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}},defaultPresentation:{activity:`idle`,expression:`normal`}},oA={apiVersion:1,name:`mushroom`,palette:{body:`#fff7e4`,cap:`#f98284`,capSpot:`#ffe6c6`,eye:`#28282e`,mouth:`#28282e`,dead:`#6c5671`,deadTongue:`#d9c8bf`,tongue:`#f98284`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.hemisphere({parent:r,name:`body.hemisphere`,backface:t(`cap`),color:t(`body`),diameter:32,rotate:{x:3*Math.PI/2},stroke:!1,translate:{y:2}});let i=e.hemisphere({parent:r,name:`cap.hemisphere`,backface:t(`capSpot`),color:t(`cap`),diameter:42,rotate:{x:Math.PI/2},stroke:!1,translate:{y:2}});e.path({parent:i,name:`cap.spot.front`,path:[{x:0,y:0}],color:t(`capSpot`),stroke:12,translate:{x:-8,y:8,z:12}}),e.path({parent:i,name:`cap.spot.top`,path:[{x:0,y:0}],color:t(`capSpot`),stroke:18,translate:{x:8,y:-4,z:13}});let a=e.group({parent:r,name:`face`,translate:{y:7,z:8}}),o=yc(e,t,a,{blushMode:`none`});return{root:n,variants:{eyes:o.eyes,mouth:o.mouth,blush:o.blush}}},expressions:vc,activities:{...bc,error:{geometry:{eyes:`dead`,mouth:`dead`},motion:{target:`root`,rotate:{x:.9},durationMs:600,repeat:`none`},mouseInfluence:.1}},defaultPresentation:{activity:`idle`,expression:`sleepy`}},sA={mushroom:[`cap`,`capSpot`],cat:[`body`,`stripes`],burger:[`topBun`,`bottomBun`]},cA={mushroom:oA,cat:aA,burger:nA};function lA(e){let t=gc(_c(cA[e])),n=hc.parse(t.data);return{controls:t.controls,expressions:Object.keys(n.expressions),identitySlots:sA[e]}}var uA=new Map;function dA(e){let t=uA.get(e);return t||(t=lA(e),uA.set(e,t)),t}var fA=Object.freeze({get mushroom(){return dA(`mushroom`)},get cat(){return dA(`cat`)},get burger(){return dA(`burger`)}}),pA={mushroom:`Shiitake`,cat:`Cat`,burger:`Burger`},mA=[[`Rose`,`#f98284`,`#ffe6c6`],[`Peach`,`#f6a55c`,`#ffe9c9`],[`Gold`,`#f2d06b`,`#fff6d1`],[`Leaf`,`#9bd47a`,`#e6f8d8`],[`Mint`,`#5fc7b4`,`#d9f6ef`],[`Sky`,`#6aaee8`,`#dcefff`],[`Lilac`,`#9b8cf0`,`#ebe6ff`],[`Plum`,`#e58bd6`,`#fbe2f6`]];function hA(e,t){if(t===e.character)return e;let n=fA[e.character].identitySlots,r=fA[t].identitySlots,i=Object.fromEntries(r.flatMap((t,r)=>{let i=n[r];return Object.hasOwn(e.appearance,i)?[[t,e.appearance[i]]]:[]}));return{...e,character:t,appearance:i,expression:`normal`}}function gA(e,[,t,n]){let r=fA[e.character].identitySlots;return{...e,appearance:{...e.appearance,...Object.fromEntries(r.map((e,r)=>[e,r===0?t:n]))}}}function _A(e,t){let n=0;for(let e of t)n+=e.codePointAt(0)??0;return gA(e,mA[n%mA.length]??mA[0])}function vA({value:e,disabled:t=!1,onChange:n}){let r=fA[e.character].identitySlots,i=mA.find(([,t,n])=>r.every((r,i)=>e.appearance[r]===(i===0?t:n)))?.[0]??``;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(wt,{legend:`Avatar`,icon:(0,$.jsx)(Un,{name:`agent`}),layout:`columns`,disabled:t,children:(0,$.jsx)(IO,{"aria-label":`Character`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:e.character,onValueChange:t=>{n(hA(e,Bo.shape.character.parse(t)))},children:Ao.map(t=>(0,$.jsx)(zO,{value:t,label:pA[t],caption:pA[t],art:`color`,icon:(0,$.jsx)(Ln,{avatar:hA(e,t),name:pA[t],size:32})},t))})}),(0,$.jsx)(wt,{legend:`Colour`,icon:(0,$.jsx)(Un,{name:`prints`}),layout:`columns`,disabled:t,children:(0,$.jsx)(IO,{"aria-label":`Colour`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:i,onValueChange:t=>{let r=mA.find(([e])=>e===t);r&&n(gA(e,r))},children:mA.map(([e,t])=>(0,$.jsx)(BO,{value:e,label:e,color:t},e))})})]})}var yA=Ea.check(Ta(1,{message:`Give your Agent a name.`}),J(256,{message:`Use at most 256 characters.`})),bA=Na(yA),xA=e=>e===`new`||e===`none`?e:e.computerId,SA=e=>e===`new`||e===`none`?e:{computerId:e},CA=e=>e?.[0]?.computerId??`none`;function wA(e,t){let n=Object.fromEntries(e.map(e=>[e.computerId,e.name]));n.new=`New Computer`,n.none=`No Computer`;let r={label:`Computer`,kind:`select`,icon:(0,$.jsx)(Un,{name:`computer`}),options:n};return Y.check(Ha(e=>Object.hasOwn(n,e)||`Choose a Computer.`)).annotate(bk(t===null?r:{...r,help:t}))}var TA=Eo({family:`grove-agent-create-request`,version:1,kinds:{request:{prefix:`request`}}});function EA({create:e,computers:t,computersUnavailable:n,inputRef:r,error:i,addCredit:a,onCancel:o}){let s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(()=>{let e=TA.request.generate();return _A(to(e),e)}),u=(0,Q.useMemo)(()=>G({name:yA.annotate(bk({label:`Name`,icon:(0,$.jsx)(Un,{name:`write`}),render:e=>(0,$.jsx)(wn,{ref:r,id:e.id,name:e.name,"aria-label":`New Agent name`,"aria-required":`true`,"aria-describedby":e[`aria-describedby`],"aria-invalid":e[`aria-invalid`],placeholder:`Name your Agent`,maxLength:256,disabled:e.disabled,value:e.value,onBlur:e.onBlur,onChange:t=>{e.onChange(t.currentTarget.value)}})})),computer:wA(t??[],n)}),[r,t,n]),d=t!==null,[f,p]=(0,Q.useState)(!1),m={name:``,computer:CA(t)},h=Jk({schema:u,defaultValues:m,onSubmit:async({name:t,computer:n})=>{let r=d?SA(n):void 0,i=s.current;if(i?.name!==t||(i.computer===void 0?void 0:xA(i.computer))!==(r===void 0?void 0:xA(r))||i.avatar!==c){let e={name:t,requestId:TA.request.generate(),avatar:c};i=r===void 0?e:{...e,computer:r}}return s.current=i,await e(i)?(s.current=null,{kind:`saved`,values:m}):{kind:`refused`}}}),{submitting:g,canSubmit:_,dirty:v}=Yk(h);return(0,$.jsxs)(Qk,{model:h,layout:`columns`,"aria-label":`Create Agent`,footer:(0,$.jsxs)(Pr,{divider:!1,error:a===null?i:null,children:[(0,$.jsx)(W,{type:`button`,variant:`ghost`,"aria-expanded":f,onClick:()=>{p(e=>!e)},children:f?`Fewer options`:`More options`}),(0,$.jsx)(W,{type:`button`,variant:`ghost`,disabled:g,onClick:o,children:`Cancel`}),(0,$.jsx)(W,{type:`submit`,className:`shrink-0 disabled:-outline-offset-1`,variant:`primary`,loading:g,disabled:g||!_||!v,children:`Create Agent`})]}),onSubmitCapture:e=>{xi(bA(h.form.state.values.name))&&e.currentTarget.querySelector(`input[name="name"]`)?.focus()},onChange:()=>{let e=h.form.state.values;(e.name.trim()!==s.current?.name||d&&s.current.computer!==void 0&&e.computer!==xA(s.current.computer))&&(s.current=null)},children:[a===null?null:(0,$.jsx)(DA,{openBilling:a}),(0,$.jsx)(hk,{model:h,names:d&&f?[`name`,`computer`]:[`name`]}),f?(0,$.jsx)(vA,{value:c,disabled:g,onChange:e=>{l(e),s.current=null}}):null]})}function DA({openBilling:e}){let t=Wc({mutationFn:e});return(0,$.jsx)(yt,{variant:`inline`,need:`Add credit to create your Agent`,cause:t.isError?`Billing could not open. Try again.`:`This Team needs credit to run Agents and Computers.`,fix:{label:t.isError?`Retry Billing`:`Add credit`,onSelect:()=>{t.mutate()},pending:t.isPending},waitingFor:`Billing`})}function OA({open:e,pending:t,error:n,addCredit:r,computers:i,create:a,onClose:o,returnFocus:s}){let c=(0,Q.useRef)(null);return(0,$.jsx)(d,{open:e,onOpenChange:e=>{!e&&!t&&o()},children:(0,$.jsxs)(Xe,{className:`flex flex-col gap-lg`,initialFocus:c,finalFocus:s,keepMounted:!1,children:[(0,$.jsxs)(ue,{children:[(0,$.jsx)(mt,{children:`New Agent`}),(0,$.jsx)(it,{children:`Agents chat, write and work with you.`})]}),i.status===`loading`?(0,$.jsx)(`p`,{role:`status`,children:`Loading your Computers…`}):(0,$.jsx)(EA,{create:a,computers:i.status===`offered`?i.computers:i.status===`unavailable`?[]:null,computersUnavailable:i.status===`unavailable`?i.message:null,inputRef:c,error:n,addCredit:r,onCancel:o})]})})}function kA({open:e,agents:t,defaultAgentId:n,start:r,pending:i,onClose:a,onNewAgent:o,returnFocus:s}){let c=Jk({schema:(0,Q.useMemo)(()=>G({agentId:Y.check(Ha(e=>t.some(t=>t.agentId===e)||`Choose an Agent.`)).annotate(bk({label:`Agent`,kind:`select`,options:Object.fromEntries(t.map(e=>[e.agentId,fE(e)]))}))}),[t]),defaultValues:{agentId:n??``},onSubmit:async({agentId:e})=>{let t=await r(e);if(t)return{kind:`refused`,error:t}}}),{submitting:l,canSubmit:u}=Yk(c);return(0,$.jsx)(d,{open:e,onOpenChange:e=>{!e&&!i&&!c.form.state.isSubmitting&&a()},children:(0,$.jsxs)(Xe,{className:`flex flex-col gap-lg`,keepMounted:!1,finalFocus:s,children:[(0,$.jsxs)(ue,{children:[(0,$.jsx)(mt,{children:`New conversation`}),(0,$.jsx)(it,{children:`Choose who to talk with.`})]}),t.length===0?(0,$.jsxs)(`div`,{className:`grid gap-sm`,children:[(0,$.jsx)(`p`,{children:`No Agent has conversation access yet.`}),o?(0,$.jsx)(W,{onClick:o,children:`New Agent`}):null,(0,$.jsx)(W,{variant:`ghost`,onClick:a,children:`Cancel`})]}):(0,$.jsx)(Qk,{model:c,"aria-label":`New conversation`,footer:(0,$.jsxs)(Pr,{divider:!1,error:c.error,children:[(0,$.jsx)(W,{type:`button`,variant:`ghost`,disabled:l||i,onClick:a,children:`Cancel`}),(0,$.jsx)(W,{type:`submit`,loading:l||i,disabled:!u||l||i,children:`Start`})]})})]})})}var AA=Q.useLayoutEffect;function jA(e,t,n){Q.useEffect(()=>{if(!e.current||n||typeof IntersectionObserver!=`function`)return()=>t();let r=new IntersectionObserver(e=>{t(e.pop())},{rootMargin:`100px`});return r.observe(e.current),()=>{r.disconnect(),t()}},[t,n,e])}function MA(e){let t=Q.useRef(null);return Q.useImperativeHandle(e,()=>t.current,[]),t}function NA(e){return e[e.length-1]}function PA(e){return typeof e==`function`}function FA(e,t){return PA(e)?e(t):e}var IA=Object.prototype.hasOwnProperty,LA=Object.prototype.propertyIsEnumerable;function RA(e){for(let t in e)if(IA.call(e,t))return!0;return!1}var zA=()=>Object.create(null),BA=(e,t)=>VA(e,t,zA);function VA(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=GA(e)&&GA(i);if(!a&&!(UA(e)&&UA(i)))return i;let o=a?e:HA(e);if(!o)return i;let s=a?i:HA(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:IA.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=VA(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function HA(e){let t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(let r of n){if(!LA.call(e,r))return!1;t.push(r)}return t}function UA(e){if(!WA(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!WA(n)||!n.hasOwnProperty(`isPrototypeOf`))}function WA(e){return Object.prototype.toString.call(e)===`[object Object]`}function GA(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function KA(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!KA(e[r],t[r],n))return!1;return!0}if(UA(e)&&UA(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!KA(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!KA(e[o],t[o],n)))return!1;return i===a}return!1}var qA=/[\x00-\x1f\x7f"<>`{}]/g;function JA(e){return e.replace(qA,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function YA(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return JA(t)}var XA=[`http:`,`https:`,`mailto:`,`tel:`];function ZA(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function QA(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=YA(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=YA(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function $A(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function ej(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function tj(){throw Error(`Invariant failed`)}function nj(e){let t=new Map,n,r,i=e=>{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var rj=4,ij=5;function aj(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function oj(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=aj(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2<a.length&&a.charCodeAt(r+2)===36){let e=r+3,a=s;if(e<a)return n[0]=3,n[1]=t+r,n[2]=t+e,n[3]=t+a,n[4]=t+s+1,n[5]=i,n}}else if(c===36){let a=r+1,o=r+2;return o===s?(n[0]=2,n[1]=t+r,n[2]=t+a,n[3]=t+o,n[4]=t+s+1,n[5]=e.length,n):(n[0]=1,n[1]=t+r,n[2]=t+o,n[3]=t+s,n[4]=t+s+1,n[5]=i,n)}}return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n}function sj(e,t,n,r,i,a,o,s){s?.(n);let c=r;{let r=n.fullPath??n.from,s=n.options,l=r.length,u=s?.caseSensitive??e,d=s?.params?.parse??s?.parseParams;for(;c<l;){let e=oj(r,c,t),n,s=c,l=e[5];c=l+1,a++;let f=e[0];switch(f){case 0:{let t=r.substring(e[2],e[3]),o=t,s;u?s=i.static??=new Map:(o=t.toLowerCase(),s=i.staticInsensitive??=new Map);let c=s.get(o);if(c)n=c;else{let e=lj(r);e.parent=i,e.depth=a,n=e,s.set(o,e)}break}case 1:case 3:case 2:{let t=r.substring(s,e[1]),c=r.substring(e[4],l),p=u&&!!(t||c),m=t?p?t:t.toLowerCase():void 0,h=c?p?c:c.toLowerCase():void 0,g=f===1?i.dynamic:f===3?i.optional:i.wildcard,_=f!==2&&!d&&g?.find(e=>!e.parse&&e.caseSensitive===p&&e.prefix===m&&e.suffix===h);if(_)n=_;else{let e=uj(f,r,p,m,h);n=e,e.parent=i,e.depth=a;let t;t=f===1?i.dynamic??=[]:f===3?i.optional??=[]:i.wildcard??=[],t.push(e),t.length===2&&o?.push(t)}break}}i=n}if(d&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=lj(r);e.kind=ij,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let f=(n.path||!n.children)&&!n.isRoot;if(f&&r.endsWith(`/`)){let e=lj(r);e.kind=rj,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=d??null,i.priority=s?.params?.priority??0,f&&!i.route&&(i.route=n,i.fullPath=r)}if(n.children)for(let r of n.children)sj(e,t,r,c,i,a,o,s)}function cj(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function lj(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function uj(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function dj(e,t){let n=lj(`/`),r=new Uint16Array(6),i=[];for(let t of e)sj(!1,r,t,1,n,0,i);for(let e of i)e.sort(cj);t.masksTree=n,t.flatCache=nj(1e3)}function fj(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=_j(e,t.masksTree);return t.flatCache.set(e,r),r}function pj(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=lj(`/`),sj(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),_j(r,o,n)}function mj(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=_j(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=yj(a.route)),t.matchCache.set(r,a),a}function hj(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function gj(e,t=!1,n){let r=lj(e.fullPath),i=new Uint16Array(6),a=[],o={},s={},c=0;sj(t,i,e,1,r,0,a,e=>{if(n?.(e,c),e.id in o&&tj(),o[e.id]=e,c!==0&&e.path){let t=hj(e.fullPath);(!s[t]||e.fullPath.endsWith(`/`))&&(s[t]=e)}c++});for(let e of a)e.sort(cj);return{processedTree:{segmentTree:r,singleCache:nj(1e3),matchCache:nj(1e3),flatCache:null,masksTree:null},routesById:o,routesByPath:s}}function _j(e,t,n=!1){let r=e.split(`/`),i=xj(e,r,t,n);if(!i)return null;let[a]=vj(e,r,i);return{route:i.node.route,rawParams:a}}function vj(e,t,n){let r=bj(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s<r.length;o++,s++,c++,l++){let u=r[s];if(u.kind===rj)break;if(u.kind===ij){l--,o--,c--;continue}let d=t[o],f=c;if(d&&(c+=d.length),u.kind===1){i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0;if(e.charCodeAt(t)===123){let n=u.suffix?.length??0,r=e.substring(t+2,e.length-n-1),i=d.substring(t,d.length-n);a[r]=decodeURIComponent(i)}else{let t=e.substring(1);a[t]=decodeURIComponent(d)}}else if(u.kind===3){if(n.skipped&1<<s){o--,c=f-1;continue}i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0,r=u.suffix?.length??0,p=e.substring(t+3,e.length-r-1),m=u.suffix||u.prefix?d.substring(t,d.length-r):d;m&&(a[p]=decodeURIComponent(m))}else if(u.kind===2){let t=u,n=e.substring(f+(t.prefix?.length??0),e.length-(t.suffix?.length??0)),r=decodeURIComponent(n);a[`*`]=r,a._splat=r;break}}return n.rawParams&&Object.assign(a,n.rawParams),[a,{part:o,node:s,path:c,segment:l}]}function yj(e){let t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function bj(e){let t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function xj(e,t,n,r){if(e===`/`&&n.index)return{node:n.index,skipped:0};let i=!NA(t),a=i&&e!==`/`,o=t.length-+!!i,s=[{node:n,index:1,skipped:0,statics:0,dynamics:0,optionals:0}],c=null,l=null;for(;s.length;){let n=s.pop(),{node:i,index:u,skipped:d,statics:f,dynamics:p,optionals:m}=n,{extract:h,rawParams:g}=n;if(i.kind===2&&i.route&&!Tj(l,n))continue;if(i.parse){if(!wj(e,t,n))continue;g=n.rawParams,h=n.extract}r&&i.route&&i.kind!==rj&&Tj(c,n)&&(c=n);let _=u===o;if(_&&(i.route&&(!a||i.kind===rj||i.kind===2)&&Tj(l,n)&&(l=n),!i.optional&&!i.wildcard&&!i.index&&!i.pathless))continue;let v=_?void 0:t[u],y;if(_&&i.index){let n={node:i.index,index:u,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g},r=!0;if(i.index.parse&&(wj(e,t,n)||(r=!1)),r){if(!p&&!m&&!d&&Cj(f,o))return n;Tj(l,n)&&(l=n)}}if(i.wildcard)for(let e=i.wildcard.length-1;e>=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(_||!(n.caseSensitive?v:y??=v.toLowerCase()).startsWith(r)))){if(a){if(_)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}}if(i.optional){let e=d|1<<i.depth+1;for(let t=i.optional.length-1;t>=0;t--){let n=i.optional[t];s.push({node:n,index:u,skipped:e,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}if(!_)for(let e=i.optional.length-1;e>=0;e--){let t=i.optional[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?v:y??=v.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,statics:f,dynamics:p,optionals:m+Sj(o,u),extract:h,rawParams:g})}}if(!_&&i.dynamic&&v)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?v:y??=v.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,statics:f,dynamics:p+Sj(o,u),optionals:m,extract:h,rawParams:g})}if(!_&&i.staticInsensitive){let e=i.staticInsensitive.get(y??=v.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,statics:f+Sj(o,u),dynamics:p,optionals:m,extract:h,rawParams:g})}if(!_&&i.static){let e=i.static.get(v);e&&s.push({node:e,index:u+1,skipped:d,statics:f+Sj(o,u),dynamics:p,optionals:m,extract:h,rawParams:g})}if(i.pathless)for(let e=i.pathless.length-1;e>=0;e--){let t=i.pathless[e];s.push({node:t,index:u,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;e<c.index;e++)n+=t[e].length;let r=n===e.length?`/`:e.slice(n);return c.rawParams??=Object.create(null),c.rawParams[`**`]=decodeURIComponent(r),c}return null}function Sj(e,t){return 2**(e-t-1)}function Cj(e,t){return e===2**(t-1)-1}function wj(e,t,n){let r,i;try{[r,i]=vj(e,t,n)}catch{return null}if(n.rawParams=r,n.extract=i,!n.node.parse)return!0;try{if(n.node.parse(r)===!1)return null}catch{}return!0}function Tj(e,t){return!e||t.statics>e.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===rj)>(e.node.kind===rj)||t.node.kind===rj==(e.node.kind===rj)&&t.node.depth>e.node.depth)))}function Ej(e){return Dj(e.filter(e=>e!==void 0).join(`/`))}function Dj(e){return e.replace(/\/{2,}/g,`/`)}function Oj(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function kj(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function Aj(e){return kj(Oj(e))}function jj(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function Mj(e,t,n){return jj(e,n)===jj(t,n)}function Nj({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t===`.`,a=t.startsWith(`/`),o;if(r){o=a?t:i?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(i)s=e.split(`/`);else if(a)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&NA(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e<t;e++){let r=n[e];r===``?e?e===t-1&&s.push(r):s=[r]:r===`..`?s.length>1?s.pop():s=[``]:r===`.`||s.push(r)}}s.length>1&&(NA(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c=Dj(s.join(`/`))||`/`;return o&&r&&r.set(o,c),c}function Pj(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function Fj(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Lj(e,n)).join(`/`):Lj(r,n):r}function Ij({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s<o;){let r=s;c=oj(e,r,c);let o=c[5];if(s=o+1,r===o)continue;let u=c[0];if(u===0){l+=`/`+e.substring(r,o);continue}if(u===2){let s=t._splat;a._splat=s,a[`*`]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o);if(!s){i=!0,(u||d)&&(l+=`/`+u+d);continue}let f=Fj(`_splat`,t,n);l+=`/`+u+f+d;continue}if(u===1){let s=e.substring(c[2],c[3]);!i&&!(s in t)&&(i=!0),a[s]=t[s];let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Fj(s,t,n)??`undefined`;l+=`/`+u+f+d;continue}if(u===3){let i=e.substring(c[2],c[3]),s=t[i];if(s==null)continue;a[i]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Fj(i,t,n)??``;l+=`/`+u+f+d;continue}}return e.endsWith(`/`)&&(l+=`/`),{usedParams:a,interpolatedPath:l||`/`,isMissingParams:i}}function Lj(e,t){let n=encodeURIComponent(e);return t?.(n)??n}function Rj(e){return e?.isNotFound===!0}function zj(){try{return sessionStorage}catch{return}}var Bj=`tsr-scroll-restoration-v1_3`,Vj=zj();function Hj(){try{return JSON.parse(Vj?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function Uj(){try{Vj?.setItem(Bj,JSON.stringify(Wj))}catch{}}var Wj=Hj(),Gj=`data-scroll-restoration-id`,Kj=e=>e.state.__TSR_key||e.href;function qj(e){let t=e.getAttribute(Gj);if(t)return`[${Gj}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var Jj=!1,Yj=`window`;function Xj(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function Zj(e){let t=new Set;for(let n of e){if(n===Yj)continue;let e=Xj(n);e&&t.add(e)}return t}function Qj(e,t){let n=t??e.options.scrollRestoration,r=e._scroll;n&&(r.restoring=!0);let i=e.options.getScrollRestorationKey||Kj,a=new Set,o=e=>{let t=Wj[e]||={};for(let e of a)e===document?t[Yj]={scrollX,scrollY}:e.isConnected&&(t[qj(e)]={scrollX:e.scrollLeft,scrollY:e.scrollTop})};n&&!r.restoration&&(r.restoration=!0,Jj=!1,history.scrollRestoration=`manual`,document.addEventListener(`scroll`,e=>{Jj||a.add(e.target)},!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(i(e.fromLocation)),a.clear()}),addEventListener(`pagehide`,()=>{o(i(e.stores.resolvedLocation.get()??e.stores.location.get())),Uj()})),!r.reset&&(r.reset=!0,e.subscribe(`onRendered`,t=>{let n=e.options.scrollRestorationBehavior,o=e.options.scrollToTopSelectors,s=r.next,c=r.hash,l;if(a.clear(),r.next=!0,r.hash=!1,typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let u=i(t.toLocation),d=t.fromLocation&&i(t.fromLocation);if(r.restoring&&d&&d!==u){let e=Wj[d];if(e){let t=Wj[u];for(let n in e){if(n===Yj){if(s)continue}else{let e=Xj(n);if(!e||s&&o&&(l??=Zj(o),l.has(e)))continue}t||=Wj[u]={},t[n]??=e[n]}}}Jj=!0;try{let e=t.toLocation.hash,i=t.toLocation.state.__hashScrollIntoViewOptions??!0,a=!1;if(s){!e&&o&&(l??=Zj(o));let t=e&&i&&c,s=r.restoring?Wj[u]:void 0;if(s)for(let e in s){let{scrollX:r,scrollY:i}=s[e];if(e===Yj){if(t)continue;scrollTo({top:i,left:r,behavior:n}),a=!0}else{let t=Xj(e);t&&(t.scrollLeft=r,t.scrollTop=i,l?.delete(t))}}if(!e){let e={top:0,left:0,behavior:n};if(a||scrollTo(e),l)for(let t of l)t.scrollTo(e)}}!a&&e&&i&&document.getElementById(e)?.scrollIntoView(i)}finally{Jj=!1}}))}function $j(e,t=String){let n=new URLSearchParams;for(let r in e){let i=e[r];i!==void 0&&n.set(r,t(i))}return n.toString()}function eM(e){return e?e===`false`?!1:e===`true`?!0:e*0==0&&+e+``===e?+e:e:``}function tM(e){let t=new URLSearchParams(e),n=Object.create(null);for(let[e,r]of t.entries()){let t=n[e];t==null?n[e]=eM(r):Array.isArray(t)?t.push(eM(r)):n[e]=[t,eM(r)]}return n}var nM=/^(?:\s|["[{\d-]|fa|nu|tr)/,rM=aM(JSON.parse),iM=oM(JSON.stringify,JSON.parse);function aM(e){return t=>{t[0]===`?`&&(t=t.substring(1));let n=tM(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function oM(e,t){let n=t===JSON.parse;function r(r){if(r&&typeof r==`object`)try{return e(r)}catch{}else if(t&&typeof r==`string`){if(n&&!nM.test(r))return r;try{return t(r),e(r)}catch{}}return r}return e=>{let t=$j(e,r);return t?`?${t}`:``}}var sM=`__root__`;function cM(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function lM(e){return e instanceof Response&&!!e.options}function uM(e){return{input:({url:t})=>{for(let n of e)t=fM(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=pM(e[n],t);return t}}}function dM(e){let t=Aj(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=Ej([`/`,t,e.pathname]),e)}}function fM(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function pM(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function mM(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i}=t,a=new Map,o=n(`idle`),s=n(e),c=n(void 0),l=n([]),u=r(()=>l.get().map(e=>a.get(e).get())),d=r(()=>({status:o.get(),isLoading:o.get()===`pending`,matches:u.get(),location:s.get(),resolvedLocation:c.get()}));function f(e){let t=a.get(e);return t||(t=n(void 0),a.set(e,t)),t}let p={status:o,location:s,resolvedLocation:c,ids:l,matches:u,byRoute:a,__store:d,getMatchStore:f,setMatches:m};function m(e){let t=l.get(),n=e.map(e=>e.routeId);i(()=>{ej(t,n)||l.set(n);for(let e of t)n.includes(e)||a.get(e).set(()=>void 0);for(let t of e){let e=f(t.routeId);e.get()!==t&&e.set(t)}})}return p}var hM=`__TSR_index`,gM=`popstate`,_M=`beforeunload`;function vM(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=CM(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[hM];i=yM(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[hM];i=yM(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[hM]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function yM(e,t){t||={};let n=wM();return{...t,key:n,__TSR_key:n,[hM]:e}}function bM(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>CM(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=wM();t.history.replaceState({[hM]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_=()=>{g&&(S._ignoreSubscribers=!0,(g[2]?t.history.pushState:t.history.replaceState)(g[1],``,g[0]),S._ignoreSubscribers=!1,g=void 0,u=void 0)},v=(e,t,n)=>{let r=s(t),i=!!g;i||(u=l),l=CM(t,n),g=[r,n,g?.[2]||e],i||queueMicrotask(()=>_())},y=e=>{l=c(),S.notify({type:e})},b=async()=>{if(f){f=!1;return}let e=c(),n=e.state[hM]-l.state[hM],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),S.notify(u);return}}}l=c(),S.notify(u)},x=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},S=vM({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>v(!0,e,t),replaceState:(e,t)=>v(!1,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:_,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(_M,x,{capture:!0}),t.removeEventListener(gM,b)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(_M,x,{capture:!0}),t.addEventListener(gM,b),t.history.pushState=function(...e){let r=n.apply(t.history,e);return S._ignoreSubscribers||y(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return S._ignoreSubscribers||y(`REPLACE`),n},S}function xM(e={initialEntries:[`/`]}){let t=e.initialEntries,n=e.initialIndex?Math.min(Math.max(e.initialIndex,0),t.length-1):t.length-1,r=t.map((e,t)=>yM(t,void 0)),i=()=>CM(t[n],r[n]),a=[];return vM({getLocation:i,getLength:()=>t.length,pushState:(e,i)=>{n<t.length-1&&(t.splice(n+1),r.splice(n+1)),r.push(i),t.push(e),n=Math.max(t.length-1,0)},replaceState:(e,i)=>{r[n]=i,t[n]=e},back:()=>{n=Math.max(n-1,0)},forward:()=>{n=Math.min(n+1,t.length-1)},go:e=>{n=Math.min(Math.max(n+e,0),t.length-1)},createHref:e=>e,getBlockers:()=>a,setBlockers:e=>a=e})}function SM(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function CM(e,t){let n=SM(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=wM();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[hM]:0,key:a,__TSR_key:a}}}function wM(){return(Math.random()+1).toString(36).substring(7)}function TM(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function EM(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function DM({key:e,__TSR_key:t,__TSR_index:n,__hashScrollIntoViewOptions:r,...i}){return i}function OM(e,t,n,r){for(let i of t){if(r?.()===!1)return;n.some(e=>e.routeId===i.routeId)||e.routesById[i.routeId].options.onLeave?.(i)}for(let i of n){if(r?.()===!1)return;e.routesById[i.routeId].options[t.some(e=>e.routeId===i.routeId)?`onStay`:`onEnter`]?.(i)}}var kM=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.subscribers=new Set,this._cache=new Map,this._committed=[],this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=async e=>(e(),!1),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??!1??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=Pj(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.history=this.options.history?this.options.history:bM()),this.origin=this.options.origin,this.origin||=window?.origin&&window.origin!==`null`?window.origin:`http://localhost`,this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=nj(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=mM(this.latestLocation,e),Qj(this)}let a=this.options.basepath??`/`,o=this.options.rewrite;if(r||n!==a||i!==o){this.basepath=a;let e=[],t=Aj(a);t&&t!==`/`&&e.push(dM({basepath:a})),o&&e.push(o),this.rewrite=e.length===0?void 0:e.length===1?e[0]:uM(e),this.history&&this.updateLatestLocation(),this.stores&&this.stores.location.set(this.latestLocation)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=gj(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&dj(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{for(let t of this.subscribers)if(t.eventType===e.type)try{t.fn(e)}catch(e){console.error(e)}},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:QA(e).path,external:!1,searchStr:o,search:BA(t?.search,i),hash:QA(r.slice(1)).path,state:VA(t?.state,a)}}let o=new URL(i,this.origin),s=fM(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:QA(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:BA(t?.search,c),hash:QA(s.hash.slice(1)).path,state:VA(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>Nj({base:e,to:t.includes(`//`)?Dj(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>{let t=Object.create(null),n=mj(kj(e),this.processedTree,!0);return n&&Object.assign(t,n.rawParams),[n?.branch||[this.routesById.__root__],t,n?.route]},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this._pendingLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r[1],a=t.to?`${t.to}`:void 0,o=r[2],s=Object.assign(Object.create(null),r[3]),c=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),l=a?this.resolvePathWithBase(c,a):c,u=FM(t.params,s),d=this.routesByPath[kj(l)],f;if(d)f=this.getRouteBranch(d);else if(l.includes(`$`))f=[];else{let[e,t,n]=this.getMatchedRoutes(l);f=e,this.options.notFoundRoute&&(!n||n.path!==`/`&&t[`**`])&&(f=[...f,this.options.notFoundRoute])}if(f.length&&RA(u))for(let e of f){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(u,t(u))}catch{}}let p=e.leaveParams?l:QA(Ij({path:l,params:u,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,m=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};f.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,MM(t.options.validateSearch,{...e,...m}))}catch{}}),m=e}m=NM(m,t,f,e._includeValidateSearch),m=BA(o,m);let h=this.options.stringifySearch(m),g=t.hash===!0?n.hash:t.hash?FA(t.hash,n.hash):void 0,_=g?`#${g}`:``,v=t.state===!0?n.state:t.state?FA(t.state,n.state):{};v=VA(n.state,v);let y=`${p}${h}${_}`,b,x,S=!1;if(this.rewrite){let e=new URL(y,this.origin),t=pM(this.rewrite,e);b=e.href.replace(e.origin,``),t.origin===this.origin?x=t.pathname+t.search+t.hash:(x=t.href,S=!0)}else b=$A(y),x=b;return{publicHref:x,href:b,pathname:p,search:m,searchStr:h,state:v,hash:g??``,external:S,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),a=r?t(r):void 0;if(!a){let n=Object.create(null);if(this.options.routeMasks){let o=fj(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=FM(s,n);r={from:e.from,...c,params:l},a=t(r)}}}return a&&(i.maskedLocation=a),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=kj(this.latestLocation.href)===kj(n.href)&&KA(DM(n.state),DM(this.latestLocation.state)),a=this._commitPromise,o,s=new Promise(e=>{o=e});if(s.resolve=()=>{o(),a?.resolve()},this._commitPromise=s,i)this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t}),this.history.subscribers.size||this.load({action:{type:r}})}return this._scroll.next=n.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,_redirects:a,href:o,...s}={})=>{if(o){let t=this.history.location.state.__TSR_index,n=CM(o,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);s.to=fM(this.rewrite,r).pathname,s.search=this.options.parseSearch(n.search),s.hash=n.hash.slice(1)}let c=this.buildLocation({...s,_includeValidateSearch:!0});a&&(c._redirects=a),this._pendingLocation=c;let l=this.commitLocation({...c,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return queueMicrotask(()=>{this._pendingLocation===c&&(this._pendingLocation=void 0)}),l},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(ZA(t,this.protocolAllowlist))return;if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return}i.replace?window.location.replace(t):window.location.href=t;return}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.load=async e=>{this.updateLatestLocation(),e?.action&&(this._scroll.hash=e.action.type===`PUSH`||e.action.type===`REPLACE`),await DN(this,e)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&window.CSS?.supports?.(`selector(:active-view-transition-type(a))`)){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(EM(r,i)):t.types;if(a===!1)return e();n={update:e,types:a}}else n=e;return document.startViewTransition(n).updateCallbackDone}return e()},this.invalidate=e=>{let t=this._committed,n=e?.filter,r=this._preloads,i=new Set([...t,...this._cache.values(),...[...r?.values()??[]].flat(),...this._tx?.[3]??[]].filter(e=>!n||n(e)).map(e=>e.id)),a=[];for(let[e,t]of r??[])t.some(e=>i.has(e.id))&&(r.delete(e),a.push(e));let o=t=>{if(i.has(t.id)){let n=this.routesById[t.routeId],r={...t,invalid:!0,...(e?.forcePending||t.status===`error`||t.status===`notFound`)&&TM(n)?{status:`pending`,error:void 0}:void 0};return t._flight=void 0,r}return t};this._committed=t.map(o);for(let[t,n]of this._cache)i.has(t)&&(n.invalid=!0,e?.forcePending&&(n.status=`pending`));for(let e of i)this._flights?.delete(e);for(let e of a)e.abort();return this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=(e.options._builtLocation??this.buildLocation(e.options)).publicHref||`/`;e.options.href=t,e.headers.set(`Location`,t)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&ZA(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=this._cache,n=this._preloads,r=e?.filter,i=[],a=[];for(let[e,n]of t)(!r||r(n))&&(a.push(e),i.push(n));let o=[];for(let[e,t]of n??[])(!r||t.some(r))&&(o.push(e),i.push(...t));for(let e of a)t.delete(e);for(let e of o)n.delete(e);for(let e of i){let t=e._flight;e._flight=void 0,t&&!--t[2]&&(this._flights?.get(e.id)===t&&this._flights.delete(e.id),o.push(t[1]))}for(let e of o)e.abort()},this.loadRouteChunk=zM,this.preloadRoute=e=>ON(this,e),this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n),i=this.stores.status.get()===`pending`;if(t?.pending&&!i)return!1;let a=t?.pending??!i?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),o=pj(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,a.pathname,this.processedTree);return!o||e.params&&!KA(o.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?KA(a.search,r.search,{partial:!0})?o.rawParams:!1:o.rawParams},this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??iM,parseSearch:e.parseSearch??rM,protocolAllowlist:e.protocolAllowlist??XA}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=yj(e),this.routeBranchCache.set(e,t)),t}matchRoutesInternal(e,t){let[n,r,i]=this.getMatchedRoutes(e.pathname),a=n,o=!1;(i?i.path!==`/`&&r[`**`]:kj(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?PM(this.options.notFoundMode,a):void 0,c=Array(a.length),l=this._committed,u=(e,t)=>{let n=l[t];return n?.routeId===e.id?n:e===this.options.notFoundRoute?l.find(t=>t.routeId===e.id):void 0},d;for(let n=0;n<a.length;n++){let i=a[n],o=c[n-1],l,f,p;{let n=o?.search??e.search,r=o?._strictSearch??void 0;try{let e=MM(i.options.validateSearch,{...n})??void 0;l={...n,...e},f={...r,...e}}catch(e){let r=e;if(e instanceof AM||(r=new AM(e.message,{cause:e})),t?.throwOnError)throw r;l=n,f={},p=r}}let m=``,h=``;try{m=i.options.loaderDeps?.({search:l})??``,h=m&&JSON.stringify(m)||``}catch(e){if(t?.throwOnError)throw e;p??=e}let{interpolatedPath:g,usedParams:_}=Ij({path:i.fullPath,params:r,decoder:this.pathParamsDecoder,server:this.isServer}),v=i.id+g+h,y=u(i,n),b=this._cache.get(v)??(y?.id===v?y:void 0);d=b?._strictParams??Object.assign(_,d);let x;if(!b)try{IM(i,d)}catch(e){if(x=Rj(e)||lM(e)?e:new jM(e.message,{cause:e}),t?.throwOnError)throw x}let S=y?`stay`:`enter`,C;if(b)C={...b,cause:S,search:BA(y?y.search:b.search,l),_strictSearch:f,searchError:p};else{let e=TM(i)?`pending`:`success`;C={id:v,ssr:i.options.ssr,index:n,routeId:i.id,params:y?.params??d,_strictParams:d,pathname:g,updatedAt:Date.now(),search:y?BA(y.search,l):l,_strictSearch:f,searchError:p,status:e,isFetching:!1,error:void 0,paramsError:x,context:{},abortController:t?._controller??new AbortController,cause:S,loaderDeps:y?VA(y.loaderDeps,m):m,invalid:!1,preload:!1,staticData:i.options.staticData||{},fullPath:i.fullPath}}let w=s===i.id;C._notFound&&!w&&(C.error=void 0),C._notFound=w,c[n]=C}for(let e=0;e<c.length;e++){let n=c[e];n.params=n.cause===`stay`?BA(n.params,d):d,t?._controller&&(n.context={})}return c}matchRoutesLightweight(e){let t=NA(this.stores.ids.get()),n=t?this.stores.byRoute.get(t).get():void 0,r=n?.id,i=this.lightweightCache.get(e);if(i&&i[0]===r)return i[1];let[a,o]=this.getMatchedRoutes(e.pathname),s=NA(a),c={...e.search};for(let e of a)try{Object.assign(c,MM(e.options.validateSearch,c))}catch{}let l=n&&n.routeId===s.id&&n.pathname===e.pathname,u;if(l)u=n.params;else{let e=Object.assign(Object.create(null),o);for(let t of a)try{IM(t,e)}catch{}u=e}let d=[a,s.fullPath,c,u];return this.lightweightCache.set(e,[r,d]),d}},AM=class extends Error{},jM=class extends Error{};function MM(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new AM(`Async validation not supported`);if(n.issues)throw new AM(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function NM(e,t,n,r){let i=[];for(let e of n){let t=e.options;`search`in t?t.search?.middlewares&&i.push(...t.search.middlewares):(t.preSearchFilters||t.postSearchFilters)&&i.push(({search:e,next:n})=>{let r=n(t.preSearchFilters?t.preSearchFilters.reduce((e,t)=>t(e),e):e);return t.postSearchFilters?t.postSearchFilters.reduce((e,t)=>t(e),r):r});let n=t.validateSearch;n&&i.push(({search:e,next:t,meta:i})=>{let a=t(e);if(r)try{let e=MM(n,a);if(i&&e)for(let t in e)t in a||(i.defaulted||=new Map).set(t,e[t]);return{...a,...e}}catch{}return a})}let a=(e,n,r)=>{if(e>=i.length){if(!t.search)return{};if(t.search===!0)return n;let e=FA(t.search,n);return r&&(r.explicit=e),e}return i[e]({search:n,next:(t,n)=>{if(n){let n=r||{};return{search:a(e+1,t,n),meta:n}}return a(e+1,t,r)},meta:r})};return a(0,e)}function PM(e,t){if(e!==`root`){let e;for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.options.notFoundComponent)return r.id;e||=r.children&&r.id}if(e)return e}return sM}function FM(e,t){return e===!1||e===null?Object.create(null):(e??!0)===!0?t:Object.assign(t,FA(e,t))}function IM(e,t){let n=e.options.params?.parse??e.options.parseParams;n&&Object.assign(t,n(t))}function LM(e,t){return e.options[t]?.preload?.()}function RM(e,t){let n=LM(e,`component`),r=LM(e,`pendingComponent`),i=t&&r?r.then(t):r;return t&&!r&&t(),n&&i?Promise.all([n,i]).then(()=>{}):n??i}function zM(e,t,n){let r=()=>t===!1?void 0:t?LM(e,t):RM(e,n),i=e._lazy;if(i)return i===!0?r():i.then(r);if(!e.lazyFn)return r();let a=e.lazyFn().then(t=>{{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazy=!0}},t=>{throw e._lazy=void 0,t});return e._lazy=a,a.then(r)}function BM(e){let t=e.findIndex(e=>e.status!==`success`||e._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var VM=0,HM=1,UM=2,WM=3,GM=4;function KM(e){return typeof e[0]==`number`}function qM(e,t){return t.aborted?Promise.race([Promise.reject(t),e]):new Promise((n,r)=>{let i=()=>r(t);t.addEventListener(`abort`,i,{once:!0}),Promise.resolve(e).then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function JM(e,t){return e.routesById[t.routeId]}function YM(e,t,n){return lM(e)?[WM,e]:Rj(e)?(e.routeId||=n,[UM,e]):(t&&typeof e?.then==`function`&&(e=Error(`A Promise was thrown`,{cause:e})),t?[HM,e]:[VM,e])}function XM(e,t){let n=YM(t,!0,e.id);if(n[0]!==HM)return n;try{e.options.onError?.(n[1])}catch(t){n=YM(t,!0,e.id)}return n}function ZM(e,t,n){return n[0].signal.aborted||!n[2]()?(n[0].abort(),[GM]):XM(e,t)}function QM(e,t){return n=>e.navigate({...n,_fromLocation:t})}async function $M(e,t,n,r,i,a){let[o,s]=t,c=n[0].signal,l=!!n[4];for(let t=n[7]??0;t<r;t++){let r=s[t],i=JM(e,r);r.abortController=n[0];let u=s[t-1]?.context??e.options.context??{},d={params:r.params,location:o,navigate:QM(e,o),buildLocation:e.buildLocation,cause:l?`preload`:r.cause,abortController:n[0],preload:l,matches:s,routeId:i.id},f=u;try{let e=r._ctx;!e&&i.options.context&&(e=r._ctx=i.options.context({...d,deps:r.loaderDeps,context:u})||{}),f={...u,...e},r.context=f}catch(a){return tN(e,r),[t,ZM(i,a,n)]}if(c.aborted||!n[2]())return n[0].abort(),[t,[GM]];let p=r.paramsError??r.searchError;if(p!==void 0)return tN(e,r),[t,ZM(i,p,n)];let m=i.options.beforeLoad;if(!m)continue;let h={...d,search:r.search,context:f,...e.options.additionalContext},g=r.status;g===`success`&&t>=a&&(r.status=`pending`),n[8]?.();try{iN(e,r,`beforeLoad`,n[0]);let a=await qM(m(h),c);if(!n[2]())return n[0].abort(),[t,[GM]];let o=YM(a,!1,i.id);if(o[0]!==VM)return tN(e,r),[t,o];r.context={...f,...a}}catch(a){return tN(e,r),[t,ZM(i,a,n)]}finally{g===`success`&&r.status===`pending`&&(r.status=`success`),iN(e,r,!1,n[0])}}i()}function eN(e,t,n){if(!(!n||--n[2])){if(e._flights?.get(t.id)===n){let n=e._tx;if(n&&!n[0].signal.aborted&&!n[3].includes(t)&&n[3].some(e=>e.id===t.id)&&n[3].some(e=>e.isFetching===`beforeLoad`))return;e._flights.delete(t.id)}return n[1]}}function tN(e,t){let n=t._flight;t._flight=void 0,eN(e,t,n)?.abort()}function nN(e,t,n,r){let i=[];for(let a of t)if(!n?.includes(a)){let t=a._flight;if(a._flight=void 0,r&&t?.[2]===1&&e._flights?.get(a.id)===t&&n?.some(e=>e.id===a.id))t[2]=0;else{let n=eN(e,a,t);n&&i.push(n)}}for(let e of i)e.abort()}function rN(e){for(let t of e){let e=t._flight;e&&e[2]++}}function iN(e,t,n,r){if(t.isFetching=n,r&&e._tx?.[0]!==r)return;let i=e.stores.byRoute.get(t.routeId),a=i?.get();a?.id===t.id&&i.set({...a,isFetching:n})}function aN(e,t,n,r,i,a,o){let s=t[0];return{params:n.params,location:s,navigate:QM(e,s),cause:o?`preload`:n.cause,abortController:i,preload:o,deps:n.loaderDeps,parentMatchPromise:a,context:n.context,route:r,...e.options.additionalContext}}async function oN(e,t,n,r,i,a,o,s){let c=s.signal;if(c.aborted)return[GM];if(!i)return[VM,void 0];let l=n._flight;iN(e,n,`loader`,s);try{if(!l){let s=new AbortController;l=[Promise.resolve().then(()=>i(aN(e,t,n,r,s,a,o))).then(e=>YM(e,!1,r.id),e=>YM(e,!0,r.id)).then(t=>(t[0]!==VM&&e._flights?.get(n.id)===l&&(e._flights.delete(n.id),l[2]||s.abort()),t[0]===HM&&l[2]?XM(r,t[1]):t)),s,1],(e._flights??=new Map).set(n.id,l)}return n._flight=l,n.abortController=l[1],await qM(l[0],c)}catch(t){if(t!==c)throw t;return tN(e,n),[GM]}finally{iN(e,n,!1,s)}}function sN(e,t,n){t[0]===VM?(e.loaderData=t[1],e.error=void 0,e.status=`success`,e.invalid=!1,e.updatedAt=Date.now(),e.preload=n):t[0]!==WM&&(e.status=`success`,e.error=void 0,e.invalid=!0)}function cN(e,t,n){let r=e._cache.get(t.id);if(r!==n||e._committed.some(e=>e.id===t.id&&e._flight===t._flight))return;let i={...t,_notFound:void 0,context:{}};i._flight&&i._flight[2]++,e._cache.set(t.id,i),r&&tN(e,r)}function lN(e,t){return t[0]===HM||t[0]===UM?{...e,status:t[0]===HM?`error`:`notFound`,error:t[1],_flight:void 0}:e}function uN(e,t,n,r,i,a,o){let s=t[1][n],c=JM(e,s),l=!!a[4],u=e._cache.get(s.id),d,f=!1,p;try{if(s.status===`success`&&(d=c.options.shouldReload,typeof d==`function`&&(d=d(aN(e,t,s,c,a[0],i,l))),a[2]()||(a[0].abort(),p=[GM])),!p){if(s.status!==`success`)f=!0;else{let t=a[4]||s.preload?c.options.preloadStaleTime??e.options.defaultPreloadStaleTime??3e4:c.options.staleTime??e.options.defaultStaleTime??0;f=!!(s.invalid||d||d===void 0&&Date.now()-s.updatedAt>=t&&(a[6]||s.cause===`enter`||a[3].some(e=>e.routeId===s.routeId&&e.id!==s.id)))}}}catch(t){s.invalid=!0,tN(e,s),p=ZM(c,t,a)}let m=c.options.loader,h=typeof m==`function`?m:m?.handler,g=(!l||c.options.preload!==!1)&&m?e._flights?.get(s.id):void 0;g===s._flight||p?g=void 0:g&&!f&&!l&&d===void 0?f=!0:f||(g=void 0);let _=!!(m&&f&&s.status===`success`&&!l&&!a[5]&&((typeof m==`function`?void 0:m?.staleReloadMode)??e.options.defaultStaleReloadMode)!==`blocking`),v=f&&(!l||c.options.preload!==!1),y=v&&!_&&(s.status!==`success`||!!m),b=c.lazyFn&&c._lazy!==!0?a[8]:void 0;if(v&&!m&&(s.invalid=!1,s.updatedAt=Date.now()),g&&g[2]++,y){let t=s._flight;s._flight=g,eN(e,s,t)?.abort(),s.status===`success`&&n>=o&&(s.status=`pending`),a[8]?.()}v||(s.isFetching=!1);let x=(p?Promise.resolve(p):y?oN(e,t,s,c,h,i,l,a[0]):Promise.resolve([VM,s.loaderData])).then(t=>(y&&(sN(s,t,l),t[0]===VM&&(m&&!a[0].signal.aborted&&cN(e,s,u),s.status=`pending`)),t)),S=qM(Promise.resolve().then(()=>zM(c,void 0,b)),a[0].signal).then(()=>void 0,e=>[n,ZM(c,e,a)]).then(e=>x.then(t=>(y&&!e&&t[0]===VM&&s.status===`pending`&&a[2]()&&(s.status=`success`,a[8]?.()),e)));if(r.push([n,x,S]),!_)return x.then(e=>lN(s,e));let C={...s,status:`pending`,preload:!1,_flight:g};s.invalid=!1,s.isFetching=`loader`;let w=oN(e,t,C,c,h,i,!1,a[0]).then(e=>(s.isFetching=!1,sN(C,e,!1),e));return(t[2]??=[]).push([n,w,S,C]),w.then(e=>lN(C,e))}async function dN(e,t,n,r,i=0){let a=n?.[1][1],o=a?.routeId?t.findIndex(e=>e.routeId===a.routeId):n?.[0]??t.length-1;o<0&&(o=0);for(let n=o;n>=0;n--){let i=JM(e,t[n]),a=zM(i,!1);if(a)try{await qM(a,r)}catch(e){if(e===r)throw e}if(i.options.notFoundComponent)return n}return a?.routeId?o:i}function fN(e,t){t[2]&&=(nN(e,t[2].map(e=>e[3])),void 0)}async function pN(e,t,n,r){let i;try{await Promise.all(e.map(e=>e[1].then(async t=>{let a=e[0];if(!(r&&a>=await r)){if(t[0]>=WM)throw[a,t];!i&&t[0]!==VM&&(i=[a,t],await Promise.all((n??[]).map(e=>{if(!(e[0]<=a))return e[1].then(t=>{if(t[0]===WM)throw[e[0],t]})})))}})))}catch(e){return e}return t??i}async function mN(e,t,n,r,i,a,o){let s=t[1],c=await a,l=!1,u=s.findIndex(e=>e._notFound),d=t=>t[1][0]===UM?dN(e,s,t,r.signal):t[0],f=u<0?s.length:u;if((c?.[1][0]??0)>=WM)f=0;else if(c){f=c[2]??=await d(c);for(let e of n){if(e[0]>=f)break;let t=await e[1];if(t[0]!==VM&&t[0]<WM&&!(`loaderData`in s[e[0]])){c=[e[0],t],f=c[2]=await d(c);break}}}for(let e of n){if(e[0]>=f)break;let t=await e[2];if(t){c=t;break}}if((c?.[1][0]??0)>=WM){let n=c[1];if(n[0]!==WM||n[1].options.reloadDocument||i<20)return fN(e,t),n;l=!0,c=[0,[HM,Error(`Too many redirects`)]]}let p=c?c[2]??await d(c):u;if(p>=0){let i=c?.[1],a=i?.[0],u=s[p],d=i?.[1],f=()=>{i&&(u._notFound=void 0,a===HM?u.status=`error`:(d.routeId=u.routeId,u.routeId===e.routeTree.id?(u.status=`success`,u._notFound=!0):u.status=`notFound`),u.error=d,u.isFetching=!1)};f();let m=JM(e,u);try{await qM(i?Promise.resolve().then(()=>zM(m,a===HM?`errorComponent`:`notFoundComponent`)):Promise.all([zM(m),zM(m,`notFoundComponent`)]),r.signal)}catch(n){if(n===r.signal)return fN(e,t),[GM]}i?l&&(r.abort(),await Promise.all([...n.map(e=>e[1]),...n.map(e=>e[2]),...(t[2]??[]).map(e=>e[1])]),fN(e,t),nN(e,s),f()):(u.status=`success`,o?.())}return t}async function hN(e,t,n,r=0,i=t[1].length){let a=t[1];for(let t=r;t<i;t++){let r=a[t],i=JM(e,r).options;if(i.head||i.scripts)try{let t={ssr:e.options.ssr,matches:a,match:r,params:r.params,loaderData:r.loaderData},[o,s]=await qM(Promise.all([i.head?.(t),i.scripts?.(t)]),n);r.meta=o?.meta,r.links=o?.links,r.headScripts=o?.scripts,r.styles=o?.styles,r.scripts=s}catch(e){if(e===n)break;console.error(e)}if(r.status!==`success`||r._notFound)break}return t}async function gN(e,t,n,r){let i=[t,n],a=e.stores.matches.get(),o=n.findIndex(e=>e._notFound);if(e.options.notFoundMode!==`root`&&o>=0){let t=await dN(e,i[1],void 0,r[0].signal,o);t!==o&&(n[o]._notFound=void 0,n[t]._notFound=!0),o=t}let s=o<0?n.length:o+1,c=0;for(;c<s&&c!==o;){let e=n[c],t=r[3][c],i=a[c];if(t?.id!==e.id||t.status!==`success`||t._notFound||e.preload||i?.id!==e.id||i.status!==`success`||i._notFound)break;c++}let l=[],u=r[7]??0,d=u?Promise.resolve(i[1][u-1]):void 0,f=()=>{for(let t=u;t<s&&!r[0].signal.aborted;t++)d=uN(e,i,t,l,d,r,c)},p=await $M(e,i,r,s,f,c);if(p&&(r[5]=!0,s=p[0],p[1][0]===UM?(p[2]=await dN(e,i[1],p,r[0].signal),s=Math.min(s,p[2]+1)):p[1][0]>=WM&&(s=0),f()),r[2]()&&!r[4]){let t=[];for(let[n,r]of e._flights??[])r[2]||(e._flights.delete(n),t.push(r[1]));for(let e of t)e.abort()}let m;try{let t=mN(e,i,l,r[0],r[1],pN(l,p,i[2]),r[8]);i[2]?.length&&(i[3]=pN(i[2],void 0,void 0,t.then(e=>KM(e)?0:BM(e[1]).length,()=>0))),m=await t}catch(t){throw fN(e,i),t}return KM(m)?m:hN(e,m,r[0].signal,r[7]===m[1].length?r[7]:0)}function _N(e,t){if(e._tx!==t)return;let n=e._pending,r=!1,i=n?.[0][3][n[1]]?.id;n?.[0]!==t&&(n&&t[3][n[1]]?.id===i?(n[0]=t,r=!0):(clearTimeout(n?.[3]),e._pending=n=void 0));let a=t[3],o=e.stores.matches.get(),s=-1,c,l,u,d=!1;for(let t=0;t<a.length;t++){let n=a[t],r=n.status===`success`;if(d=o[t]?.id===n.id&&o[t]?.status===`pending`,r&&!d)continue;let i=JM(e,n);if(c=r&&d||n.invalid?0:i.options.pendingMs??e.options.defaultPendingMs,u=i.options.pendingComponent??e.options.defaultPendingComponent,!u||typeof c!=`number`||c===1/0)return;s=t,l=i.options.pendingMinMs??e.options.defaultPendingMinMs??0;break}if(s<0)return;let f=a[s].id;if((!n||n[1]!==s||i!==f)&&(clearTimeout(n?.[3]),e._pending=n=[t,s,d?Date.now()+l:t[4]+c,void 0,d?Promise.resolve(!0):void 0,u]),n[4]&&!r&&n[5]===u)return;if(n[5]=u,!n[4]){clearTimeout(n[3]);let r=n[2]-Date.now();if(r>0){n[3]=setTimeout(()=>_N(e,t),r);return}n[2]=0}let p=a.map(e=>({...e,_flight:void 0}));p[s].status=`pending`;let m=e.startTransition(()=>e.stores.setMatches(p),p).then(t=>(t&&e._pending===n&&n[4]===m&&!n[2]&&(n[2]=Date.now()+l),t));n[4]=m}function vN(e,t){let n=e._pending;n?.[0]===t&&(clearTimeout(n[3]),e._pending=void 0)}function yN(e,t){e._committed=t,e.stores.setMatches(t)}function bN(e,t){nN(e,t[1]),fN(e,t)}function xN(e,t,n,r){let i=e._committed,a=e._cache;for(let e of n)e.preload=!1,r&&(e._assetEnd=void 0);let o=BM(n).length,s=new Map,c=Date.now();for(let t of[...i,...a.values()]){if(t.status!==`success`||n.some((e,n)=>e.id===t.id&&(n<o||e.status===`success`)))continue;let r=JM(e,t);!r.options.loader||c-t.updatedAt>=(t.preload?r.options.preloadGcTime??e.options.defaultPreloadGcTime??3e5:r.options.gcTime??e.options.defaultGcTime??3e5)||s.set(t.id,a.get(t.id)===t?t:{...t,_flight:void 0,isFetching:!1,context:{}})}t[3]=[],e._cache=s,yN(e,n),nN(e,[...a.values(),...i],[...n,...s.values()]),OM(e,i,n,()=>e._tx===t)}async function SN(e,t){let n=e._tx;for(;n&&n!==t;){if(await n[5],e._tx===n)return;n=e._tx}}async function CN(e,t,n){await e.navigate({...n.options,replace:!0,ignoreBlocker:!0,_redirects:t[1]+1})}function wN(e,t){vN(e,t),t[0].abort(),nN(e,t[3]),t[3]=[],e._tx===t&&(e.batch(()=>{e.stores.status.set(`idle`),e.stores.setMatches(e._committed)}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0))}async function TN(e,t,n,r,i){let a=n.map(e=>({...e}));rN(a);for(let t of r)tN(e,a[t[0]]),a[t[0]]=t[3];let o=[t[2],a],s;try{s=await mN(e,o,r,t[0],t[1],i)}catch(t){throw nN(e,a),t}if(KM(s)){nN(e,a),s[0]===WM&&e._tx===t&&e._committed===n&&await CN(e,t,s[1]);return}let c=await hN(e,s,t[0].signal);if(e._tx!==t||e._committed!==n){nN(e,c[1]);return}for(let t of c[1]){let n=e._cache.get(t.id);n?._flight&&n._flight===t._flight&&(e._cache.delete(t.id),tN(e,n))}yN(e,c[1]),nN(e,n,c[1])}async function EN(e,t,n,r,i,a){let o=[t[0],t[1],()=>e._tx===t&&!!t[3].length,e._committed,void 0,i,n,a,r],s=await gN(e,t[2],t[3],o);if(KM(s)){s[0]===WM&&e._tx===t?(vN(e,t),nN(e,t[3]),t[3]=[],e._tx===t&&await CN(e,t,s[1])):wN(e,t);return}let c=e._pending;if(c?.[0]===t&&(clearTimeout(c[3]),c[4])){let n=t[0].signal,r=!1;try{r=await qM(c[4],n)}catch(e){if(e!==n)throw e}if(r&&e._pending===c&&c[0]===t){let e=c[2]-Date.now();if(e>0){try{await qM(new Promise(t=>{c[3]=setTimeout(t,e)}),n)}catch{}clearTimeout(c[3])}}}if(e._tx!==t){vN(e,t),bN(e,s);return}let l=t[2],u=EM(l,e.stores.resolvedLocation.get()),d=s[2];await e.startViewTransition(async()=>{if(e._tx!==t){bN(e,s);return}let n=await e.startTransition(()=>{vN(e,t),xN(e,t,s[1],a),e._tx===t&&(e.emit({type:`onLoad`,...u}),e._tx===t&&e.emit({type:`onBeforeRouteMount`,...u}))},s[1]);if(e._tx!==t){fN(e,s);return}d?.length&&TN(e,t,s[1],d,s[3]).catch(console.error),e.batch(()=>{e.stores.resolvedLocation.set(l),e.stores.status.set(`idle`),e._tx===t&&e.emit({type:`onResolved`,...u}),n&&e._tx===t&&e.emit({type:`onRendered`,...u})}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0)})}async function DN(e,t){let n=e._tx,r=e.stores.resolvedLocation.get(),i=r??e.stores.location.get(),a=e.latestLocation,o=e._pendingLocation,s=o?.href===a.href?o._redirects??0:0,c=e._handoff,l=c?.[0](),u=new AbortController,d=e._preflight;if(e._preflight=u,l||c?.[1](),d?.abort(),u.signal.aborted){await SN(e,n);return}let f=EM(a,r);if(e.emit({type:`onBeforeNavigate`,...f}),u.signal.aborted||e.emit({type:`onBeforeLoad`,...f}),u.signal.aborted){await SN(e,n);return}let p=i.href===a.href,m,h=u;try{m=e.matchRoutes(a,{_controller:u}),rN(m)}catch(t){if(u.abort(),!lM(t)){await SN(e),e._commitPromise?.resolve(),e._commitPromise=void 0;return}await e.navigate({...t.options,replace:!0,ignoreBlocker:!0}),await SN(e,n);return}let g=l?c[1](m):void 0;if(g?h=l:l?.abort(),u.signal.aborted){nN(e,m),await SN(e,n);return}e._preflight=void 0;let _=[h,s,a,m,Date.now(),Promise.resolve().then(()=>EN(e,_,p,()=>_N(e,_),t?.sync,g)).catch(()=>{e._tx===_&&wN(e,_)})];if(e._tx=_,n){for(let t of e.stores.matches.get()){if(e._tx!==_)break;t.isFetching&&iN(e,t,!1)}n[0].abort(),nN(e,n[3],_[3],!0)}if(e._tx!==_){nN(e,_[3]),_[3]=[],await SN(e,_);return}e.batch(()=>{e.stores.status.set(`pending`),e.stores.location.set(a)}),!r&&!m.some(e=>e._notFound)&&_N(e,_);try{await _[5]}finally{await SN(e,_)}}async function ON(e,t,n=0){if(n>20)return;let r=t._builtLocation??e.buildLocation(t),i=e._committed,a=new AbortController,o;try{o=e.matchRoutes(r,{_controller:a}),rN(o)}catch(e){a.abort(),Rj(e)||console.error(e);return}(e._preloads??=new Map).set(a,o);let s;try{let t;try{t=await gN(e,r,o,[a,n,()=>!0,i,!0])}finally{s=e._preloads.delete(a),nN(e,o),a.abort()}if(!KM(t))return t[1];if(s&&t[0]===WM&&!t[1].options.reloadDocument)return ON(e,{...t[1].options,_fromLocation:r},n+1)}catch(e){Rj(e)||console.error(e)}}var kN=`Error preloading route! ☝️`,AN=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=sM:this.parentRoute||tj();let r=n?sM:t?.path;r&&r!==`/`&&(r=Oj(r));let i=t?.id||r,a=n?sM:Ej([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=Ej([`/`,a]));let o=a===`__root__`?`/`:Ej([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=kj(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>cM({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},jN=class extends AN{constructor(e){super(e)}};function MN(e){return(0,$.jsx)(NN,{...e})}var NN=class extends Q.Component{constructor(...e){super(...e),this.state={error:null},this.reset=()=>{this.setState({error:null})}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){let e=this.state.error;return e?Q.createElement(this.props.errorComponent??PN,{error:e,reset:this.reset}):this.props.children}};function PN({error:e}){let[t,n]=Q.useState(!1);return(0,$.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,$.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,$.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,$.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,$.jsx)(`div`,{children:(0,$.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,$.jsx)(`code`,{children:e.message}):null})}):null]})}function FN({children:e,fallback:t=null}){return(0,$.jsx)(Q.Fragment,{children:IN()?e:t})}function IN(){return Q.useSyncExternalStore(LN,()=>!0,()=>!1)}function LN(){return()=>{}}var RN=Q.createContext(null);function zN(e){return Q.useContext(RN)}var BN=Q.createContext(void 0),VN=Q.createContext(void 0),HN=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(HN||{});function UN({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function WN(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var GN=[],KN=0,{link:qN,unlink:JN,propagate:YN,checkDirty:XN,shallowPropagate:ZN}=UN({update(e){return e._update()},notify(e){GN[$N++]=e,e.flags&=~HN.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=HN.Mutable|HN.Dirty,rP(e))}}),QN=0,$N=0,eP,tP=0;function nP(e){try{++tP,e()}finally{--tP||iP()}}function rP(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=JN(n,e)}function iP(){if(!(tP>0)){for(;QN<$N;){let e=GN[QN];GN[QN++]=void 0,e.notify()}QN=0,$N=0}}function aP(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?HN.None:HN.Mutable,get(){return eP!==void 0&&qN(i,eP,KN),i._snapshot},subscribe(e){let t=WN(e),n={current:!1},r=oP(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=eP,o=t?.compare??Object.is;if(n)eP=i,++KN,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=HN.Mutable|HN.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{eP=a,n&&(i.flags&=~HN.RecursedCheck),rP(i)}}};return n?(i.flags=HN.Mutable|HN.Dirty,i.get=function(){let e=i.flags;if(e&HN.Dirty||e&HN.Pending&&XN(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&ZN(e)}}else e&HN.Pending&&(i.flags=e&~HN.Pending);return eP!==void 0&&qN(i,eP,KN),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(YN(e),ZN(e),iP())}},i}function oP(e){let t=()=>{let t=eP;eP=n,++KN,n.depsTail=void 0,n.flags=HN.Watching|HN.RecursedCheck;try{return e()}finally{eP=t,n.flags&=~HN.RecursedCheck,rP(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:HN.Watching|HN.RecursedCheck,notify(){let e=this.flags;e&HN.Dirty||e&HN.Pending&&XN(this.deps,this)?t():this.flags=HN.Watching},stop(){this.flags=HN.None,this.depsTail=void 0,rP(this)}};return t(),n}var sP=t((e=>{var t=T();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),cP=t(((e,t)=>{t.exports=sP()})),lP=t((e=>{var t=T(),n=cP();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),uP=t(((e,t)=>{t.exports=lP()}))();function dP(e,t){return e===t}function fP(e,t,n=dP){let r=(0,Q.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,Q.useCallback)(()=>e?.get(),[e]);return(0,uP.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var pP={};function mP(e,t){let n=Q.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=VA(n.current,i):i}}function hP(e){let t=zN(),n=Q.useContext(e.from?VN:BN),r=e.from??n,i=t.stores.getMatchStore(r),a=mP(e,t),o=fP(i,e=>e?a(e):pP);if(o!==pP)return o;(e.shouldThrow??!0)&&tj()}function gP(e){return hP({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function _P(e){let{select:t,...n}=e;return hP({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function vP(e){return hP({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function yP(e){return hP({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function bP(e){let t=zN();return Q.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function xP(e){return hP({...e,select:t=>e.select?e.select(t.context):t.context})}function SP(e){let t=Q.useRef(e);return KA(t.current,e,{ignoreUndefined:!1})||(t.current=e),t.current}function CP(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function wP(e,t,n){if(e?.external)return ZA(e.href,n)?void 0:e.href;if(!FP(t)&&typeof t==`string`&&t.indexOf(`:`)!==-1)try{return new URL(t),ZA(t,n)?void 0:t}catch{}}function TP(e,t,n,r,i,a){if(a)return!1;if(n?.exact){if(!Mj(e.pathname,t.pathname,r))return!1}else{let n=jj(e.pathname,r),i=jj(t.pathname,r);if(!(n.startsWith(i)&&(n.length===i.length||n[i.length]===`/`)))return!1}return(n?.includeSearch??!0)&&!KA(e.search,t.search,{partial:!n?.exact,ignoreUndefined:!n?.explicitUndefined})?!1:!n?.includeHash||i&&e.hash===t.hash}function EP(e,t){let n=zN(),r=MA(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:v,style:y,className:b,onClick:x,onBlur:S,onFocus:C,onMouseEnter:w,onMouseLeave:T,onTouchStart:E,ignoreBlocker:D,params:O,search:k,hash:A,state:j,mask:M,reloadDocument:N,unsafeRelative:ee,from:te,_fromLocation:ne,...P}=e,F=IN(),re=SP(e.search),I=SP(e.params),L=SP(o),R=Q.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,re,I,e.state,e.mask,e.unsafeRelative]),z=Q.useCallback(e=>{let t=n.buildLocation({_fromLocation:e,...R}),r=PP(t.maskedLocation?t.maskedLocation.publicHref:t.publicHref,t.maskedLocation?t.maskedLocation.external:t.external,n.history,v),i=wP(r,s,n.protocolAllowlist);return[r?.href,i,TP(e,t,L,n.basepath,F,i!==void 0)]},[L,v,F,R,n,s]),[ie,ae,oe]=fP(n.stores.location,z,CP),se=oe?FA(i,{})??OP:DP,B=oe?DP:FA(a,{})??DP,ce=[b,se.className,B.className].filter(Boolean).join(` `),le=(y||se.style||B.style)&&{...y,...se.style,...B.style},ue=Q.useRef(!1),V=e.reloadDocument||ae||v?!1:c??n.options.defaultPreload,de=l??n.options.defaultPreloadDelay??0,H=Q.useCallback(()=>{n.preloadRoute(R).catch(e=>{console.warn(e),console.warn(kN)})},[n,R]),fe=Q.useCallback(e=>{if(!e){MP(r);return}if(!(e.isIntersecting??V===`intent`)){e.isIntersecting===!1&&MP(r);return}if(!de){H();return}jP.has(r)||jP.set(r,setTimeout(()=>{jP.delete(r),H()},de))},[H,r,V,de]);jA(r,fe,V!==`viewport`),Q.useEffect(()=>{ue.current||V===`render`&&(H(),ue.current=!0)},[H,V]);let pe=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;!v&&!LP(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0&&(e.preventDefault(),n.navigate({...R,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:D}))};if(ae)return{...P,ref:r,href:ae,...g&&{children:g},..._&&{target:_},...v&&{disabled:v},...y&&{style:y},...b&&{className:b},...x&&{onClick:x},...S&&{onBlur:S},...C&&{onFocus:C},...w&&{onMouseEnter:w},...T&&{onMouseLeave:T},...E&&{onTouchStart:E}};let me=()=>{V===`intent`&&H()},he=()=>{V===`intent`&&MP(r)};return{...P,...se,...B,href:ie,ref:r,onClick:NP([x,pe]),onBlur:NP([S,he]),onFocus:NP([C,fe]),onMouseEnter:NP([w,fe]),onMouseLeave:NP([T,he]),onTouchStart:NP([E,me]),disabled:!!v,target:_,...le&&{style:le},...ce&&{className:ce},...v&&kP,...oe&&AP}}var DP={},OP={className:`active`},kP={role:`link`,"aria-disabled":!0},AP={"data-status":`active`,"aria-current":`page`},jP=new WeakMap,MP=e=>{clearTimeout(jP.get(e)),jP.delete(e)},NP=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function PP(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function FP(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var IP=Q.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=EP(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return Q.createElement(`a`,t,o)}return Q.createElement(n,a,o)});function LP(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var RP=class extends AN{constructor(e){super(e),this.useMatch=e=>hP({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>xP({...e,from:this.id}),this.useSearch=e=>yP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>vP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>_P({...e,from:this.id}),this.useLoaderData=e=>gP({...e,from:this.id}),this.useNavigate=()=>bP({from:this.fullPath}),this.Link=Q.forwardRef((e,t)=>(0,$.jsx)(IP,{ref:t,from:this.fullPath,...e}))}};function zP(e){return new RP(e)}var BP=class extends jN{constructor(e){super(e),this.useMatch=e=>hP({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>xP({...e,from:this.id}),this.useSearch=e=>yP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>vP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>_P({...e,from:this.id}),this.useLoaderData=e=>gP({...e,from:this.id}),this.useNavigate=()=>bP({from:this.fullPath}),this.Link=Q.forwardRef((e,t)=>(0,$.jsx)(IP,{ref:t,from:this.fullPath,...e}))}};function VP(e){return new BP(e)}function HP(e){let t=zN(),n=`not-found-${fP(t.stores.location,e=>e.pathname)}-${fP(t.stores.status,e=>e)}`;return(0,$.jsx)(MN,{getResetKey:()=>n,onCatch:(t,n)=>{if(Rj(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(Rj(t))return e.fallback?.(t);throw t},children:e.children})}function UP(){return(0,$.jsx)(`p`,{children:`Not Found`})}function WP(e){return(0,$.jsx)($.Fragment,{children:e.children})}function GP(e,t,n){return t.options.notFoundComponent?(0,$.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,$.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,$.jsx)(UP,{})}function KP(e,t){let n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,$.jsx)(n,{}):null}var qP=(e,t)=>e[0]===t[0]&&e[1]===t[1],JP=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n===`data-only`||!e.ssr,YP=Q.memo(function({routeId:e}){let t=zN();return(0,$.jsx)(XP,{router:t,match:fP(t.stores.getMatchStore(e),e=>e)})});function XP({router:e,match:t}){let n=e.routesById[t.routeId],r=KP(e,n),i=n.options.errorComponent??e.options.defaultErrorComponent,a=n.options.onCatch??e.options.defaultOnCatch,o=n.isRoot?n.options.notFoundComponent??e.options.notFoundRoute?.options.component:n.options.notFoundComponent,s=t.ssr===!1||t.ssr===`data-only`,c=JP(e,n,t.ssr)&&(n.options.wrapInSuspense??r??(n.options.errorComponent?.preload||s))?Q.Suspense:WP,l=i?MN:WP,u=o?HP:WP;return(0,$.jsxs)(n.isRoot?n.options.shellComponent??WP:WP,{children:[(0,$.jsx)(BN.Provider,{value:t.routeId,children:(0,$.jsx)(c,{fallback:r,children:(0,$.jsx)(l,{getResetKey:()=>t,errorComponent:i,onCatch:(e,n)=>{if(Rj(e))throw e.routeId??=t.routeId,e;a?.(e,n)},children:(0,$.jsx)(u,{fallback:e=>{if(e.routeId??=t.routeId,e.routeId!==t.routeId)throw e;return Q.createElement(o,e)},children:s?(0,$.jsx)(FN,{fallback:r,children:(0,$.jsx)(ZP,{match:t})}):(0,$.jsx)(ZP,{match:t})})})})}),null]})}var ZP=Q.memo(function({match:e}){let t=zN(),n=e.routeId,r=t.routesById[n],i=Q.useMemo(()=>{let i=(r.options.remountDeps??t.options.defaultRemountDeps)?.({routeId:n,loaderDeps:e.loaderDeps,params:e._strictParams,search:e._strictSearch});return i?JSON.stringify(i):void 0},[n,e.loaderDeps,e._strictParams,e._strictSearch,r.options.remountDeps,t.options.defaultRemountDeps]),a=Q.useMemo(()=>{let e=r.options.component??t.options.defaultComponent;return e?(0,$.jsx)(e,{},i):(0,$.jsx)(QP,{})},[i,r.options.component,t.options.defaultComponent]);if(e.status===`pending`){if(t.ssr&&!JP(t,r,e.ssr))return a;if(t._tx)throw t._tx[5];return KP(t,r)}if(e.status===`notFound`)return GP(t,r,e.error);if(e.status===`error`)throw e.error;return a}),QP=Q.memo(function(){let e=zN(),t=Q.useContext(BN),n,r,i;{let a=e.stores.getMatchStore(t);[n,r]=fP(a,e=>[!!e._notFound,e.error],qP),i=fP(e.stores.ids,e=>e[e.indexOf(t)+1])}if(n)return GP(e,e.routesById[t],r);if(!i)return null;let a=(0,$.jsx)(YP,{routeId:i});return t===`__root__`?(0,$.jsx)(Q.Suspense,{fallback:KP(e),children:a}):a});function $P(e,t){let n=e[1];e.length=0,n?.(t)}function eF({t:e}){let t=zN(),n=t._rendered??=[];return t.startTransition=(r,i)=>new Promise((a,o)=>{$P(n,!1),n.push(i,a),e(t),Q.startTransition(()=>{try{r()}catch(e){n[1]===a&&(n.length=0),o(e)}})}),AA(()=>{let e=t.history.subscribe(t.load);t.updateLatestLocation();let r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(kj(r.publicHref)!==kj(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),e;let a=t.stores.resolvedLocation.get();return a?.href===r.href&&a.state.__TSR_key===r.state.__TSR_key?n.push(t.stores.matches.get(),e=>{e&&t.emit({type:`onRendered`,...EM(a,a)})}):t._tx||t.load().catch(console.error),e},[t,t.history]),null}function tF(){let e=zN(),t=e.routesById[sM],n=KP(e,t),r=e.ssr?WP:Q.Suspense,i=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(eF,{t:Q.useState()[1]}),(0,$.jsx)(r,{fallback:n,children:(0,$.jsx)(nF,{})})]});return e.options.InnerWrap?(0,$.jsx)(e.options.InnerWrap,{children:i}):i}function nF(){let e=zN(),t=e._rendered,n=fP(e.stores.matches,e=>t[0]??e),r=n[0],i=r?.routeId;AA(()=>{t[0]===n&&$P(t,!0)},[t,n]);let a=i?(0,$.jsx)(YP,{routeId:i}):null;return(0,$.jsx)(BN.Provider,{value:i,children:e.options.disableGlobalCatchBoundary?a:(0,$.jsx)(MN,{getResetKey:()=>r,onCatch:void 0,children:a})})}var rF=e=>({createMutableStore:aP,createReadonlyStore:aP,batch:nP}),iF=e=>new aF(e),aF=class extends kM{constructor(e){super(e,rF)}};function oF({router:e,children:t,...n}){RA(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,$.jsx)(RN.Provider,{value:e,children:t});return e.options.Wrap?(0,$.jsx)(e.options.Wrap,{children:r}):r}function sF({router:e,...t}){return(0,$.jsx)(oF,{router:e,...t,children:(0,$.jsx)(tF,{})})}function cF(e){let t=zN({warn:e?.router===void 0}),n=e?.router||t;return fP(n.stores.__store,mP(e,n))}function lF(){return fP(zN().stores.location,e=>e.state.__TSR_index!==0)}var uF=(0,Q.createContext)(null),dF=uF.Provider,fF=VP({validateSearch:yi({agent:ra().min(1).optional()}),component:()=>null}),pF=zP({getParentRoute:()=>fF,path:`/`}),mF=yi({agentId:ra().min(1),sessionId:ra().min(1)}),hF=zP({getParentRoute:()=>fF,path:`/sessions/$agentId/$sessionId`,params:{parse:e=>mF.parse(e)}});function gF(){return iF({routeTree:fF.addChildren([pF,hF]),history:xM(),InnerWrap:({children:e})=>(0,$.jsxs)($.Fragment,{children:[(0,Q.useContext)(uF),e]}),defaultPendingMs:0,defaultPendingMinMs:0})}function _F(e){let t=e.state.matches.find(e=>e.routeId===hF.id),n=mF.safeParse(t?.params);return n.success?n.data:null}function vF(e,t){let n=cF({router:e,select:e=>e.location.search}),r=hP({from:hF.id,shouldThrow:!1});Ep(t,{canGoBack:lF(),canGoForward:!1,onForward:()=>!1,onBack:()=>e.history.canGoBack()?(e.history.back(),!0):!1});let i=(0,Q.useCallback)(t=>{e.navigate({to:`.`,search:{agent:t??void 0},replace:!0})},[e]),a=(0,Q.useCallback)((t,n)=>e.navigate({to:`/sessions/$agentId/$sessionId`,params:{agentId:t,sessionId:n},search:!0}),[e]);return{agentFilterId:n.agent??null,setFilter:i,selection:r?.params,open:a}}var yF=Ea.check(Ta(1,{message:`Give your Agent a name.`}),J(256,{message:`Use at most 256 characters.`}));function bF({agentId:e,name:t,rename:n}){let[r,i]=(0,Q.useState)(!1),a=Jk({schema:(0,Q.useMemo)(()=>G({name:yF.annotate(bk({label:`Agent name`,render:e=>(0,$.jsx)(wn,{id:e.id,name:e.name,"aria-label":`Agent name`,"aria-invalid":e[`aria-invalid`],"aria-describedby":e[`aria-describedby`],autoFocus:!0,maxLength:256,disabled:e.disabled,value:e.value,onBlur:e.onBlur,onChange:t=>{e.onChange(t.currentTarget.value)}})}))}),[]),defaultValues:{name:t},onSubmit:async({name:r})=>r===t||await n(e,r)?(i(!1),{kind:`saved`,values:{name:r}}):{kind:`refused`}}),{submitting:o,canSubmit:s}=Yk(a);return r?(0,$.jsxs)(Qk,{model:a,"aria-label":`Rename Agent`,footer:null,className:`flex min-w-0 items-center gap-1`,children:[(0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,$.jsx)(hk,{model:a,names:[`name`]})}),(0,$.jsx)(W,{type:`submit`,size:`sm`,loading:o,disabled:o||!s,children:`Save`}),(0,$.jsx)(ct,{"aria-label":`Cancel rename`,type:`button`,icon:(0,$.jsx)(O,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!1)}})]}):(0,$.jsx)(ct,{"aria-label":`Rename Agent`,icon:(0,$.jsx)(BC,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!0)}})}function xF({status:e,approving:t,onApprove:n}){return e?.status===`pending`?(0,$.jsx)(W,{variant:`outline`,size:`sm`,className:`flex-none`,loading:t,disabled:t,onClick:n,children:`Allow App tools`}):null}var SF=G({text:Y}),CF=wo(structuredClone(qa(SF,{onExcessProperty:`error`}).schema));function wF(e){return[{id:`new-conversation`,title:`New conversation`,category:`Conversation`,description:`Start a new conversation with this Agent`,projections:{slash:{aliases:[`new`],order:20},palette:{}},handler:()=>{e().newConversation()}},{id:`permissions`,title:`App permissions`,category:`Conversation`,description:`Review what Grove may access`,projections:{slash:{aliases:[`permissions`],order:21},palette:{}},handler:()=>{e().openPermissions()}},{id:`set-draft`,title:`Set draft`,category:`Conversation`,description:`Replace the open writable Grove conversation's draft without sending it`,projections:{agent:{}},action:{inputSchema:CF,presentation:{type:`action`}},handler:({arguments:t})=>{let{text:n}=oo(SF,{onExcessProperty:`error`})(t);return{accepted:e().setDraft(n)}}}]}function TF(e,t){let n=(0,Q.useRef)(e);n.current=e;let r=(0,Q.useMemo)(()=>wF(()=>n.current),[]),i=(0,Q.useMemo)(()=>Ke(),[]);return(0,Q.useEffect)(()=>{let e=i.contribute({sourceId:`grove`,namespace:`grove`,commands:r});return()=>{e.dispose()}},[r,i]),(0,Q.useEffect)(()=>t?Sc(t,r):void 0,[r,t]),i}var EF=Yi(Si({providerId:ra().min(1).max(256),providerName:ra().min(1).max(256),id:ra().min(1).max(256),name:ra().min(1).max(256),reasoning:Yi(_i(ka)).max(6).readonly()})).max(1024).readonly();async function DF(e,t,n,r=oc){if(!e.has(Zs))throw Error(`Agent read authority is unavailable`);let i=await r(e,{agentId:t});try{let e=await i.fetch(new Request(`${i.baseUrl}/models`,{signal:n}));if(!e.ok)throw Error(`Agent model catalog is unavailable`);return EF.parse(await e.json())}finally{await i.close()}}function OF(e){let t=He(),n=e?.capabilities.has(Zs)===!0||e?.capabilities.has(qs)===!0,r=Gg(n?e:null),i=e&&!n?{...r,status:`live`}:r,a=Vg.of(e,`agents`),o=Uc({...Wg(e,Gs,a,e=>e.list()),enabled:e?.capabilities.has(Gs)===!0}),{refetch:s}=o,c=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(e===null||!o.isSuccess||i.status!==`live`)return;let t=i.items.filter(e=>!(`kind`in e));if(t.length===0)return;let n=JSON.stringify(t.map(e=>[e.agentId,e.sessionId,e.state])),r=c.current?.app===e&&c.current.key!==n;c.current={app:e,key:n};let a=new Set(o.data.map(e=>e.agentId));(r||t.some(e=>!a.has(e.agentId)))&&s()},[e,o.isSuccess,o.data,i.status,i.items,s]);let l=Vg.of(e,`agent-computers`);return{directory:o,inbox:i,computerChoices:Uc({...Wg(e,ic,l,()=>{if(!e)throw Error(`No App connection`);return Ds(e.capabilities)}),enabled:e?.capabilities.has(ic)===!0}),createAgent:Wc({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Ls(e.capabilities,t)},onMutate:()=>({directoryKey:a}),onSettled:(e,n,r)=>{r.computer===`new`&&t.invalidateQueries({queryKey:l})},onSuccess:(e,n,r)=>{t.setQueryData(r.directoryKey,(t=[])=>t.some(t=>t.agentId===e.agentId)?t:[...t,e])}}),renameAgent:Wc({mutationFn:t=>{if(!e)throw Error(`No App connection`);return lc(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}}),setAgentAvatar:Wc({mutationFn:t=>{if(!e)throw Error(`No App connection`);return ys(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}})}}function kF(e,t){let n=He(),r=e?.capabilities.has(zs)===!0,i=Vg.of(e,`agent-tool-policy`,t??`none`);return{canRead:r,status:Uc({...Wg(e,zs,i,e=>t===null?Promise.resolve(null):e.status({agentId:t})),enabled:r&&t!==null}),approve:Wc({mutationFn:t=>{if(!e)throw Error(`No App connection`);return e.capabilities.require(zs).approve({agentId:t.agentId,level:`write`,expectedRevision:t.expectedRevision})},onSuccess:e=>{`error`in e||n.setQueryData(i,e)}})}}function AF(e,t){let n=He(),r=e?.capabilities.has(js)===!0,i=Vg.of(e,`agent-instructions`,t??`none`);return{canUse:r,read:Uc({...Wg(e,js,i,()=>{if(!e||t===null)throw Error(`No Agent is open`);return As(e.capabilities,t)}),enabled:r&&t!==null}),save:Wc({mutationFn:t=>{if(!e)throw Error(`No App connection`);return rs(e.capabilities,t)},onSuccess:t=>{n.setQueryData(Vg.of(e,`agent-instructions`,t.agentId),t)}})}}var jF=new Set([`Enter`,` `]),MF=(0,Q.forwardRef)(function({children:e,onConfirm:t,holdMs:n=900,holdHint:r=`Press and hold to confirm.`,className:i,disabled:a,loading:o=!1,result:s,resultLabel:c,onBlur:l,onKeyDown:u,onKeyUp:d,onPointerDown:p,onPointerUp:m,onPointerLeave:h,onPointerCancel:g,..._},v){let y=(0,Q.useRef)(null),b=(0,Q.useRef)(null),x=(0,Q.useRef)(null),S=(0,Q.useRef)(null),C=(0,Q.useRef)(t),w=(0,Q.useId)();(0,Q.useEffect)(()=>{C.current=t},[t]),(0,Q.useEffect)(()=>()=>{b.current?.cancel(),x.current!==null&&clearTimeout(x.current)},[]);let T=()=>{b.current=null,x.current=null,S.current=null,C.current();let e=y.current;if(!e||!f(e))return;let t=F(e);e.animate([{opacity:1},{opacity:0}],{duration:t.normal,easing:tt(t,t.easeExit)})},E=e=>{let t=y.current;if(a===!0||o||!t||b.current||x.current)return;if(S.current=e,!f(t)){x.current=setTimeout(T,n);return}let r=F(t),i=t.animate([{transform:`scaleY(0)`},{transform:`scaleY(1)`}],{duration:n,easing:r.reduced?`steps(3, end)`:tt(r,`cubic-bezier(0.3, 0, 0.7, 1)`)});i.addEventListener(`finish`,T),b.current=i},D=e=>{if(e!==void 0&&S.current!==e)return;S.current=null,x.current!==null&&(clearTimeout(x.current),x.current=null);let t=b.current,n=y.current;if(!t||!n)return;b.current=null;let r=getComputedStyle(n).transform;t.cancel();let i=F(n);n.animate([{transform:r===`none`?`scaleY(0)`:r},{transform:`scaleY(0)`}],{duration:i.fast,easing:tt(i,i.ease)})};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(W,{..._,ref:v,disabled:a,loading:o,result:s,resultLabel:c??(s===void 0?void 0:e),"aria-describedby":w,className:N(`caps-hold-button`,i),onBlur:e=>{D(),l?.(e)},onPointerDown:e=>{p?.(e),e.button===0&&E(e.pointerId)},onPointerUp:e=>{m?.(e),D(e.pointerId)},onPointerLeave:e=>{h?.(e),D(e.pointerId)},onPointerCancel:e=>{g?.(e),D(e.pointerId)},onKeyDown:e=>{u?.(e),e.key===`Escape`&&D(),jF.has(e.key)&&(e.preventDefault(),e.repeat||E(`key`))},onKeyUp:e=>{d?.(e),jF.has(e.key)&&(e.preventDefault(),D(`key`))},children:[(0,$.jsx)(`span`,{ref:y,"aria-hidden":`true`,className:`caps-hold-fill`}),e]}),(0,$.jsx)(Vr,{id:w,children:r})]})});function NF({label:e,confirmLabel:t,onConfirm:n,error:r,variant:i=`destructive`,size:a,mode:o,phrase:s}){let[c,l]=(0,Q.useState)(!1),[u,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(`idle`),h=(0,Q.useRef)(!1),g=(0,Q.useRef)(null),_=p===`busy`,v=o===`hold`||s.length>0&&u===s,y=_?void 0:r!==void 0&&r!==``?r:p instanceof Error?p.message:void 0,b=y?`failed`:p===`done`?`done`:void 0;async function x(){if(!(h.current||!v)){h.current=!0,m(`busy`);try{await n(),m(`done`),l(!1),f(``)}catch(e){m(Error(`Could not confirm the action. Try again.`,{cause:e}))}finally{h.current=!1}}}return o===`hold`?(0,$.jsxs)(`div`,{className:`grid gap-sm`,children:[(0,$.jsx)(MF,{variant:i,...a===void 0?{}:{size:a},loading:_,result:b,holdHint:t,onConfirm:()=>void x(),children:e}),(0,$.jsx)(an,{children:y})]}):(0,$.jsxs)(d,{open:c,onOpenChange:(e,t)=>{if(h.current){t.cancel();return}l(e),f(``),m(`idle`)},children:[(0,$.jsx)(lt,{render:(0,$.jsx)(W,{variant:i,...a===void 0?{}:{size:a}}),children:e}),(0,$.jsx)(Xe,{initialFocus:g,children:(0,$.jsxs)(xr,{busy:_,onSubmit:e=>{e.preventDefault(),x()},children:[(0,$.jsxs)(ue,{children:[(0,$.jsx)(mt,{children:e}),(0,$.jsx)(it,{children:`Type the phrase exactly to confirm.`})]}),(0,$.jsx)(un,{label:`Type ${s} to confirm`,children:(0,$.jsx)(wn,{ref:g,autoComplete:`off`,autoCapitalize:`none`,spellCheck:!1,value:u,onChange:e=>{f(e.currentTarget.value)}})}),(0,$.jsxs)(Pr,{error:y,children:[(0,$.jsx)(P,{render:(0,$.jsx)(W,{variant:`ghost`}),disabled:_,children:`Cancel`}),(0,$.jsx)(W,{type:`submit`,variant:`destructive`,disabled:!v,loading:_,result:b,children:t})]})]})})]})}function PF(e){return`# ${e}'s instructions\n\nWrite what ${e} should do in every conversation, in plain language.\n\n- Keep replies short.\n`}var FF=new TextEncoder,IF=e=>e.toLocaleString(`en-US`),LF=.8,RF=`No Home Computer. An Agent gets one when it is created with a Computer; with several, choose one in a conversation with /home <name>.`;function zF({agentId:e,name:t,file:n,loading:r,save:i,reload:a,notify:o}){let[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(!1),g=(0,Q.useId)(),_=n?.limit??0,v=FF.encode(s??``).byteLength,y=s!==null&&v>_,b=y||v>=_*LF,x=s===(l??``),S=n?.home===null,C=e=>{h(!1),u(e.content),c(e.content??``)},w=async()=>{try{C(await a())}catch(e){console.error(`Instructions reload failed`,e),o(`Couldn't reload this file. Try again.`,`error`)}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(JT,{children:[(0,$.jsx)(YT,{asChild:!0,children:(0,$.jsx)(ct,{"aria-label":`Instructions`,"aria-haspopup":S?void 0:`dialog`,className:S?`opacity-40`:void 0,icon:(0,$.jsx)(RC,{size:14,"aria-hidden":`true`}),disabled:r||n===void 0,onClick:()=>{n!==void 0&&(S?o(RF,`warning`):C(n))}})}),(0,$.jsx)(XT,{children:S?RF:`Instructions`})]}),(0,$.jsx)(d,{open:s!==null,onOpenChange:e=>{!e&&!f&&c(null)},children:(0,$.jsxs)(Xe,{className:`flex flex-col gap-lg`,keepMounted:!1,forceBackdrop:!0,children:[(0,$.jsxs)(ue,{children:[(0,$.jsxs)(mt,{children:[t,`'s instructions`]}),(0,$.jsxs)(it,{children:[t,` follows these at the start of every conversation, and can update them as it learns.`]}),n?.home?(0,$.jsxs)(`p`,{className:`text-xs text-base-content/70`,children:[`Saved as AGENTS.md on `,n.home.name,`. Other Agents that use`,` `,n.home.name,` read it too.`]}):null]}),(0,$.jsxs)(`div`,{className:`grid gap-xs`,children:[(0,$.jsx)(`label`,{htmlFor:g,className:`text-sm font-medium`,children:`Instructions`}),(0,$.jsx)(bn,{id:g,rows:14,className:`font-mono text-sm`,value:s??``,invalid:y,disabled:f,placeholder:PF(t),onChange:e=>{c(e.currentTarget.value)}}),b?(0,$.jsxs)(`p`,{className:`text-xs ${y?`text-error`:`text-base-content/70`}`,role:y?`alert`:void 0,children:[s!==null&&v!==s.length?`About `:``,IF(v),` of `,IF(_),` characters`,y?`. Shorten it to save.`:``]}):null]}),(0,$.jsxs)(M,{children:[(0,$.jsx)(W,{type:`button`,variant:`ghost`,disabled:f,onClick:()=>{c(null)},children:`Cancel`}),m?s===(l??``)?(0,$.jsx)(W,{type:`button`,variant:`primary`,onClick:()=>{w()},children:`Reload`}):(0,$.jsx)(NF,{mode:`hold`,variant:`primary`,label:`Hold to reload`,confirmLabel:`Hold to reload and lose your edits`,onConfirm:w}):(0,$.jsx)(W,{type:`button`,variant:`primary`,loading:f,disabled:f||s===null||y||x,onClick:()=>{s!==null&&(p(!0),i(e,{expectedContent:l,content:s}).then(e=>{p(!1),e===`saved`?c(null):e===`conflict`?(h(!0),o(`${t} changed this file. Reload to see it.`,`warning`)):o(e===`too_large`?`That file is too large to save.`:`The instructions could not be saved. Try again.`,`error`)}))},children:`Save`})]})]})})]})}function BF({agentId:e,name:t,avatar:n,setAvatar:r}){let[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(!1),c=(0,$.jsx)(Ln,{avatar:n,name:t,size:24});return r===void 0?(0,$.jsx)(`span`,{className:`flex-none`,children:c}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(W,{variant:`ghost`,size:`sm`,"aria-label":`Change avatar`,className:`flex-none p-0`,onClick:()=>{a(n)},children:c}),(0,$.jsx)(d,{open:i!==null,onOpenChange:e=>{!e&&!o&&a(null)},children:(0,$.jsxs)(Xe,{className:`flex flex-col gap-lg`,keepMounted:!1,children:[(0,$.jsxs)(ue,{children:[(0,$.jsxs)(mt,{children:[t,`'s avatar`]}),(0,$.jsxs)(it,{children:[`Every conversation with `,t,` shows this look.`]})]}),i===null?null:(0,$.jsx)(vA,{value:i,disabled:o,onChange:a}),(0,$.jsxs)(M,{children:[(0,$.jsx)(W,{type:`button`,variant:`ghost`,disabled:o,onClick:()=>{a(null)},children:`Cancel`}),(0,$.jsx)(W,{type:`button`,variant:`primary`,loading:o,disabled:o||i===null,onClick:()=>{i!==null&&(s(!0),r(e,i).then(e=>{s(!1),e&&a(null)}))},children:`Save`})]})]})})]})}var VF=(0,Q.forwardRef)(function({className:e,orientation:t,variant:n=`grip`,value:r,min:i,max:a,onValueChange:o,onKeyDown:s,...c},l){return(0,$.jsx)(`div`,{...c,ref:l,className:N(`caps-resize-handle`,e),"data-resize-variant":n,role:`separator`,"aria-orientation":t,"aria-valuemin":Math.round(i),"aria-valuemax":Math.round(a),"aria-valuenow":Math.round(r),tabIndex:c.tabIndex??0,onKeyDown:e=>{if(s?.(e),e.defaultPrevented)return;if(e.key===`Home`||e.key===`End`){e.preventDefault(),o(e.key===`Home`?i:a);return}let n=t===`horizontal`?e.key===`ArrowUp`?-32:e.key===`ArrowDown`?32:null:e.key===`ArrowLeft`?-32:e.key===`ArrowRight`?32:null;n!==null&&(e.preventDefault(),o(Math.min(a,Math.max(i,r+n))))},children:(0,$.jsx)(`span`,{className:`caps-resize-grip`,"aria-hidden":`true`})})});ae({frames:new Map,order:[],tiles:[],minima:new Map,participating:new Set,mainSize:void 0,zoomed:null,gesture:null,restore:new Map});function HF(e,t=!0,n){let r=(0,Q.useRef)(e);r.current=e;let i=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>(t||i.current?.release(!0),()=>i.current?.release(!0)),[t]),(0,Q.useEffect)(()=>{let e=()=>{i.current?.release(!0)};return n?.addEventListener(`abort`,e),()=>{n?.removeEventListener(`abort`,e)}},[n]),{onPointerDown:e=>{if(!t||n?.aborted||i.current||e.pointerType===`mouse`&&e.button!==0)return;let{currentTarget:a,pointerId:o}=e;if(a.setPointerCapture(o),!r.current.begin(e)){a.releasePointerCapture(o);return}let s=r.current.end,c=()=>{l(!0)},l=e=>{a.removeEventListener(`lostpointercapture`,c),i.current=null,s(e),a.hasPointerCapture(o)&&a.releasePointerCapture(o)};i.current={id:o,element:a,x:e.clientX,y:e.clientY,release:l},a.addEventListener(`lostpointercapture`,c)},onPointerMove:e=>{let t=i.current;t?.id===e.pointerId&&(r.current.move(e.clientX-t.x,e.clientY-t.y,e),t.x=e.clientX,t.y=e.clientY)},onPointerUp:e=>{i.current?.id===e.pointerId&&i.current.release(!1)},onPointerCancel:e=>{i.current?.id===e.pointerId&&i.current.release(!0)}}}(0,Q.createContext)(null);var UF=(0,Q.createContext)(null);(0,Q.forwardRef)(function({layer:e,style:t,children:n,...r},i){let a=(0,Q.useContext)(UF),o=a?.update,s=a?.roots.get(`dialog`),[c,l]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(!s)return;let e=()=>{l(Array.from(s.querySelectorAll(`*`)).some(e=>{let t=e.getBoundingClientRect();return t.width>0&&t.height>0}))};e();let t=new MutationObserver(e);return t.observe(s,{childList:!0,subtree:!0,attributes:!0}),()=>{t.disconnect()}},[s]);let u=(0,Q.useRef)(null);(0,Q.useImperativeHandle)(i,()=>u.current);let d=(0,Q.useCallback)(t=>{u.current=t,o?.(e,t)},[o,e]);return(0,Q.createElement)(`div`,{...r,ref:d,onFocusCapture:t=>{e===`windows`&&t.target instanceof Node&&t.currentTarget.contains(t.target)&&a?.dismiss?.(),r.onFocusCapture?.(t)},"data-maosaico-layer":e,inert:e===`windows`&&c?``:void 0,style:{position:`relative`,...t,isolation:`isolate`,zIndex:`var(--stipe-layer-${e})`}},n)});var WF={min:224,max:480,initial:320},GF={agentRailOpen:!0,listRailOpen:!0,listWidth:WF.initial},KF=`layout`,qF=Na(G({agentRailOpen:Ko,listRailOpen:Ko,listWidth:Da.pipe(K(Ya()))}));function JF(e){return Math.round(Math.min(WF.max,Math.max(WF.min,e)))}async function YF(e){let t=await e.read(KF),n=qF(t.member?.value);return{layout:Qi(n)?{...n.value,listWidth:JF(n.value.listWidth)}:GF,revision:t.member?.revision??null}}async function XF(e,t,n){let{revision:r}=await e.write({key:KF,scope:`member`,basedOn:n,value:t});return r}function ZF(e){let[t,n]=(0,Q.useState)(GF),r=(0,Q.useRef)(null),i=(0,Q.useRef)(!1),a=(0,Q.useRef)(!1);return(0,Q.useEffect)(()=>{if(e===void 0)return;let t=!1;return YF(e).then(e=>{t||(r.current=e.revision,i.current=!0,a.current||n(e.layout))},e=>{console.warn(`Grove could not read its saved rail layout`,e),i.current=!0}),()=>{t=!0}},[e]),(0,Q.useEffect)(()=>{e===void 0||!a.current||!i.current||XF(e,t,r.current).then(e=>{r.current=e},e=>{console.warn(`Grove could not save its rail layout`,e)})},[e,t]),[t,(0,Q.useCallback)(e=>{a.current=!0,n(e)},[])]}var QF=[{title:`Add your key`,detail:`Choose your provider in Model keys. Your key stays private.`},{title:`Come back and ask`,detail:`Close Settings to return here. Start with a question or a short writing task.`},{title:`Pick up where you left off`,detail:`Find your conversations in Grove and your desktop Inbox.`}];function $F({connection:e,navigation:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(!1),o=async()=>{r(!1),a(!0);try{r(await e.ui.openSetup(`model`)!==`opened`)}catch(e){console.error(`Grove could not open model setup`,e),r(!0)}finally{a(!1)}};return(0,$.jsxs)(`section`,{className:`inbox-empty @container m-auto flex max-h-full min-h-0 w-full max-w-3xl flex-col gap-xl overflow-y-auto px-lg py-xl`,"aria-label":`Get started with Grove`,children:[(0,$.jsx)(Me,{variant:`panel`,title:`Connect a model to start chatting`,description:`An Agent is an AI helper that writes, thinks through ideas and works with your Apps. A model powers its replies: connect Cloudflare Workers AI, or bring a key from your own model provider.`,visual:(0,$.jsx)(`span`,{className:`block`,style:{width:`3.5rem`,height:`3.5rem`},children:(0,$.jsx)(WC,{className:`h-full w-full`,state:{activity:`idle`,expression:`normal`}})}),primaryAction:{label:i?`Opening Model keys…`:`Add a model key`,onSelect:()=>void o(),pending:i}}),t?(0,$.jsx)(W,{variant:`outline`,className:`self-center`,"aria-haspopup":`dialog`,"aria-controls":`grove-nav`,"aria-expanded":t.open,onClick:t.onOpen,children:`Agents and conversations`}):null,n?(0,$.jsx)($t,{role:`alert`,message:`Model keys could not open. Try opening them again.`,onRetry:()=>void o(),onDismiss:()=>{r(!1)}}):null,(0,$.jsx)(`ol`,{className:`m-0 grid list-none gap-lg p-0 text-sm @xl:grid-cols-3`,children:QF.map((e,t)=>(0,$.jsxs)(`li`,{className:`flex flex-col gap-xs border-t border-base-300 pt-md`,children:[(0,$.jsxs)(`strong`,{className:`font-semibold`,children:[String(t+1),`. `,e.title]}),(0,$.jsx)(`span`,{className:`text-(--stipe-fg-muted)`,children:e.detail})]},e.title))})]})}function eI({description:e,icon:t,label:n,density:r=`regular`,appearance:i=`plain`,iconSize:a=`default`,size:o,trailing:s,...c}){return(0,$.jsxs)(W,{...c,className:N(`caps-action-row`,i===`card`&&`caps-action-row-card`,r===`compact`?`h-auto min-h-10 w-full justify-start gap-xs px-xs py-2xs text-left`:`h-auto min-h-14 w-full justify-start gap-sm px-sm py-xs text-left`,c.className),size:o??(r===`compact`?`default`:`lg`),variant:c.variant??`ghost`,children:[t?(0,$.jsx)(`span`,{className:r===`compact`?`grid ${a===`lg`?`size-8`:`size-7`} shrink-0 place-items-center [&_:is(svg,.caps-monogram)]:size-5`:`grid ${a===`lg`?`size-12`:`size-10`} shrink-0 place-items-center [&_:is(svg,.caps-monogram)]:size-7`,children:t}):null,(0,$.jsxs)(`span`,{className:`caps-action-row-copy`,children:[(0,$.jsx)(`span`,{className:`caps-action-row-label max-w-full truncate`,children:n}),e?(0,$.jsx)(`span`,{className:`caps-action-row-description max-w-full truncate`,children:e}):null]}),s?(0,$.jsx)(`span`,{className:`caps-action-row-trailing`,children:s}):null]})}function tI(e,t,n,r,i,a){let o=[];r&&o.push({kind:`hint`,key:`loading`,loading:!0});let s=0,c=uE(e),l=new Map(c.map(e=>[dE(e.agentId,e.sessionId),e]));for(let e of[`Needs you`,`Working`,`Ready`,`Finished`]){let n=t.flatMap(t=>{let n=l.get(t.key),r=n?.state===`errored`?`Needs you`:t.shelf;return n===void 0||r!==e?[]:[n]});if(n.length!==0){o.push({kind:`heading`,key:e,title:e,gap:s++>0});for(let t of n)o.push({kind:`session`,key:dE(t.agentId,t.sessionId),shelf:e,session:t})}}if(e.unavailable.length>0){o.push({kind:`heading`,key:`Unavailable`,title:`Unavailable`,gap:s>0});for(let t of e.unavailable)o.push({kind:`unavailable`,key:dE(t.agentId,t.sessionId),session:t})}if(n.length>0){o.push({kind:`heading`,key:`Websites`,title:`Websites`,gap:o.length>0});for(let e of n)o.push({kind:`website`,key:`website:${e.bindingId}:${e.conversation.sessionId}`,website:e})}return o.length===0&&!i&&a&&o.push({kind:`hint`,key:`empty`,loading:!1}),o}function nI({viewport:e,view:t,agents:n,loading:r,failed:i,showEmptyState:a,pendingSelection:o,selectedAgentId:s,selectedSessionId:c,onSelect:l,onDelete:u,deleting:d,websites:f,selectedWebsite:p,onSelectWebsite:m}){let h=s!==null&&c!==null?dE(s,c):null,[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(!1),b=g||v,[x,S]=(0,Q.useState)(0),[C,T]=(0,Q.useState)({placements:null,openKey:h,reopened:x}),E=(0,Q.useMemo)(()=>oE(C.placements,[...t.active,...t.settled],{openKey:C.openKey===h?h:null,held:b,reorder:C.openKey!==h||C.reopened!==x}),[C,t,h,b,x]);(0,Q.useEffect)(()=>{!b&&(C.placements!==E||C.openKey!==h||C.reopened!==x)&&T({placements:E,openKey:h,reopened:x})},[b,C,E,h,x]),(0,Q.useEffect)(()=>{let t=e.current;if(t===null)return;let n=t.clientWidth>0&&t.clientHeight>0,r=`ResizeObserver`in globalThis?new ResizeObserver(([e])=>{let t=e.contentRect.width>0&&e.contentRect.height>0;t&&!n&&S(e=>e+1),n=t}):void 0;r?.observe(t);let i=()=>{document.visibilityState===`visible`&&S(e=>e+1)};return document.addEventListener(`visibilitychange`,i),()=>{r?.disconnect(),document.removeEventListener(`visibilitychange`,i)}},[e]);let D=(0,Q.useMemo)(()=>tI(t,E,f,r,i,a),[t,E,f,r,i,a]),O=(0,Q.useCallback)(e=>D[e]?.key??e,[D]),k=be({count:D.length,getScrollElement:()=>e.current,getItemKey:O,estimateSize:e=>D[e]?.kind===`heading`?24:44,measureElement:(e,t,n)=>{let r=De(e,t,n);return r>0?r:De(e,void 0,n)||n.options.estimateSize(n.indexFromElement(e))},initialRect:{width:320,height:800},overscan:5,useFlushSync:!1});return(0,$.jsx)(`div`,{className:`inbox-list px-1 py-1`,onPointerEnter:()=>{_(!0)},onPointerLeave:()=>{_(!1)},onFocusCapture:()=>{y(!0)},onBlurCapture:e=>{e.currentTarget.contains(e.relatedTarget)||y(!1)},children:(0,$.jsx)(`div`,{style:{height:k.getTotalSize(),position:`relative`,width:`100%`},children:k.getVirtualItems().map(e=>{let t=D[e.index],r=t.kind===`session`||t.kind===`unavailable`?t.session:null,i=r?n.get(r.agentId):void 0;return(0,$.jsx)(`div`,{"data-index":e.index,ref:k.measureElement,"data-inbox-shelf":t.kind===`session`?t.shelf:t.kind===`unavailable`?`Unavailable`:void 0,className:t.kind===`heading`?`inbox-shelf`:void 0,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${String(e.start)}px)`,paddingTop:t.kind===`heading`&&t.gap?4:0},children:t.kind===`heading`?(0,$.jsx)(w,{style:{paddingBottom:0},children:t.title}):t.kind===`hint`?t.loading?(0,$.jsx)(Zg,{className:`inbox-empty px-2 py-3 text-sm text-(--stipe-fg-muted)`,message:`Loading conversations…`}):(0,$.jsx)(`p`,{className:`m-0 px-2 py-3 text-xs text-(--stipe-fg-muted)`,children:`Conversations you start with Agents appear here.`}):t.kind===`website`?(0,$.jsx)(eI,{appearance:`plain`,density:`compact`,className:`inbox-row${p?.bindingId===t.website.bindingId&&p.conversation.sessionId===t.website.conversation.sessionId?` is-selected bg-base-300`:``}`,"data-testid":`inbox-website-row`,label:t.website.conversation.label||`Website visitor`,description:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,$.jsx)(Un,{name:`internet`,size:14}),t.website.siteLabel]}),trailing:t.website.conversation.held?(0,$.jsx)(`span`,{className:`text-xs`,children:t.website.conversation.heldByYou?`You're replying`:`With a teammate`}):t.website.conversation.needsYou?(0,$.jsx)(_r,{size:`compact`,tone:`accent`,title:t.website.conversation.needsYou.reason}):null,onClick:()=>{m(t.website)},variant:`ghost`}):t.kind===`unavailable`?i?(0,$.jsx)(iI,{agent:i,row:t.session}):null:i?(0,$.jsx)(rI,{agent:i,session:t.session,attention:t.session.unseen,pending:o?.agentId===t.session.agentId&&o.sessionId===t.session.sessionId,selected:s===t.session.agentId&&c===t.session.sessionId,onDelete:u&&i.sessionOperations.includes(`agent.manage`)?()=>{u(t.session.agentId,t.session.sessionId)}:void 0,deleting:d?.agentId===t.session.agentId&&d.sessionId===t.session.sessionId,onSelect:()=>{l(t.session.agentId,t.session.sessionId)}}):null},e.key)})})})}function rI({agent:e,session:t,attention:n,pending:r,selected:i,onSelect:a,onDelete:o,deleting:s}){let c=$T(t.state),l=t.state===`errored`,u=(0,$.jsxs)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:[(0,$.jsxs)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:[r||c||l?(0,$.jsx)(`span`,{className:`sr-only`,children:r?`Opening`:ZT[t.state]}):null,r||c?(0,$.jsx)(_r,{size:`compact`,title:r?`Opening`:ZT[t.state],motion:t.state===`running`||r?`pulse`:`none`,tone:r?`neutral`:t.state===`needs_you`?`accent`:`info`}):l?(0,$.jsx)(_r,{size:`compact`,title:ZT.errored,tone:`error`}):n?(0,$.jsx)(_r,{size:`compact`,title:`Finished since your last visit`,tone:`neutral`}):null]}),(0,$.jsx)(`time`,{className:`inbox-row-age min-w-0 truncate text-right tabular-nums text-(--stipe-fg-muted)`,dateTime:new Date(t.lastActivityAt).toISOString(),children:aI(t.lastActivityAt)})]});return(0,$.jsxs)(`div`,{className:`relative group`,children:[(0,$.jsx)(eI,{"aria-current":i?`page`:void 0,"aria-label":`${t.title||`New conversation`} — ${fE(e)}${n?` — Finished since your last visit`:``}${t.ready?` — Ready`:c||l?` — ${ZT[t.state]}`:``}`,"aria-busy":r||void 0,appearance:`plain`,className:`inbox-row pr-9${i?` is-selected bg-base-300`:``}`,"data-attention":n?`true`:`false`,"data-pending":r?`true`:`false`,"data-session-id":t.sessionId,"data-status":t.state,"data-testid":`inbox-session-row`,density:`compact`,description:fE(e),label:t.title||`New conversation`,onClick:a,trailing:u,variant:`ghost`}),o?(0,$.jsx)(ct,{"aria-label":`Delete conversation ${t.title||`New conversation`}`,title:`Delete conversation`,icon:(0,$.jsx)(UC,{}),iconSize:`sm`,size:`sm`,className:`absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 @max-[899px]/grove:opacity-100`,disabled:c||s,onClick:o}):null]})}function iI({agent:e,row:t}){return(0,$.jsxs)(`div`,{className:`inbox-row is-unavailable flex min-h-11 w-full items-center gap-2 rounded-field border-(length:--border) border-transparent px-2 py-1 pr-9 text-left text-base-content`,"data-session-id":t.sessionId,"data-testid":`inbox-unavailable-row`,role:`group`,children:[(0,$.jsxs)(`span`,{className:`inbox-row-copy flex min-w-0 flex-1 flex-col`,children:[(0,$.jsx)(`strong`,{className:`truncate text-sm font-medium`,children:`Conversation unavailable`}),(0,$.jsxs)(`small`,{className:`truncate text-xs text-(--stipe-fg-muted)`,children:[fE(e),` `,(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),` This saved conversation could not be read.`]})]}),(0,$.jsx)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:(0,$.jsx)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:(0,$.jsx)(_r,{size:`compact`,tone:`error`,title:`This saved conversation could not be read`})})})]})}function aI(e){let t=Math.max(0,Date.now()-e);return t<6e4?`now`:t<36e5?`${String(Math.floor(t/6e4))}m`:t<864e5?`${String(Math.floor(t/36e5))}h`:new Date(e).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}var oI=ra().min(1).max(256),sI=Ai().int().nonnegative();wi(`state`,[Si({state:Ki(`agent`),version:sI}),Si({state:Ki(`requested`),version:sI,reason:ra().max(4e3),at:Ai().int().nonnegative()}),Si({state:Ki(`person`),version:sI,memberId:oI,memberName:ra().min(1).max(128),since:Ai().int().nonnegative()})]);var cI=Si({bindingId:oI,agentId:oI,origins:Yi(ra().min(1).max(2048)).min(1).max(16),lifecycle:_i([`active`,`suspended`])}),lI=Si({sessionId:oI,label:ra().max(4096),lastEventAt:Ai().int().nonnegative(),needsYou:Si({at:Ai().int().nonnegative(),reason:ra().max(4e3)}).nullable(),held:Gi(),heldByYou:Gi(),heldByName:ra().min(1).max(128).nullable(),holdVersion:Ai().int().nonnegative()}),uI=Si({bindingId:oI}).extend({sessionId:oI});uI.extend({requestId:ra().min(1).max(128),text:ra().trim().min(1).max(4e3)});var dI=Si({expectedVersion:sI,confirm:Gi()});uI.extend(dI.shape),uI.extend({expectedVersion:sI});var fI=Si({websites:Yi(cI).max(1e3)}),pI=Si({conversations:Yi(lI).max(100)});Si({conversation:lI});var mI=Si({status:Ki(`sent`)}),hI=Ws(`channels.read`,1,Di(()=>as({list:is(cc(fI)),conversations:is(cc(pI))}))),gI=Ws(`channels.personal.manage`,1,Di(()=>as({hold:is(cc(lI)),release:is(cc(lI)),dismiss:is(cc(lI)),reply:is(cc(mI))})));function _I(e,t){async function n(e){if(e.type!==`prompt`||(e.images?.length??0)>0)throw new Z(`Website conversations support text replies only`,{code:`COMMAND_NOT_DECLARED`,retryable:!1});if(!t.canReply())throw new Z(`Use Take over to reply to this visitor`,{code:`CAPABILITY_DENIED`,retryable:!1});return await t.reply({bindingId:t.bindingId,sessionId:t.sessionId,requestId:e.requestId,text:e.text}),{status:`recorded`}}return{latestPending:()=>Promise.resolve(null),withdraw:t=>e.withdraw(t),address:e.address,read:t=>e.read(t),watch:t=>e.watch(t),extension:()=>({call:()=>Promise.reject(new Z(`Website Session controls are unavailable`,{code:`COMMAND_NOT_DECLARED`,retryable:!1}))}),command:n}}function vI(e,t){(0,Q.useSyncExternalStore)(t=>e?.capabilities.subscribe(t)??(()=>void 0),()=>e?.capabilities.version??0);let n=He(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),s=e?.capabilities.has(hI)===!0,c=e?.capabilities.has(gI)===!0,l=Uc({...Wg(e,hI,Vg.of(e,`websites`),e=>e.list()),enabled:s}),u=s?l.data?.websites??[]:[],d=Vc({queries:u.map(t=>({...Wg(e,hI,Vg.of(e,`website-conversations`,t.bindingId),e=>e.conversations({bindingId:t.bindingId})),enabled:s}))}),f=u.flatMap((e,t)=>(d[t]?.data?.conversations??[]).map(t=>({bindingId:e.bindingId,agentId:e.agentId,siteLabel:e.origins.map(e=>new URL(e).host).join(`, `),conversation:t}))).sort((e,t)=>t.conversation.lastEventAt-e.conversation.lastEventAt),p=f.find(e=>e.bindingId===r?.bindingId&&e.conversation.sessionId===r.sessionId),m=(0,Q.useMemo)(()=>e===null?null:YC({connection:e,queryClient:n,services:t,onPending:()=>void 0,onConversation:o,onError:t=>{t!==null&&pr(e.ui,{variant:`error`,message:`That conversation could not be opened. Try again.`})}}),[e,n,t]);(0,Q.useEffect)(()=>()=>{m?.close()},[m]),(0,Q.useEffect)(()=>{s||m?.clear()},[s,m]);let h=Wc({mutationFn:t=>{if(e===null)throw Error(`No App connection`);let n=e.capabilities.require(gI);return t.kind===`hold`?n.hold({bindingId:t.bindingId,sessionId:t.sessionId,expectedVersion:t.expectedVersion,confirm:t.confirm}):n.release({bindingId:t.bindingId,sessionId:t.sessionId,expectedVersion:t.expectedVersion,confirm:t.confirm})},onSuccess:(t,r)=>{n.setQueryData(Vg.of(e,`website-conversations`,r.bindingId),e=>e===void 0?void 0:{conversations:e.conversations.map(e=>e.sessionId===t.sessionId?t:e)})}}),g=p?.bindingId,_=p?.conversation.sessionId,v=p?.conversation.heldByYou===!0,y=(0,Q.useMemo)(()=>a===null||g===void 0||_===void 0||e===null?null:_I(a.session,{bindingId:g,sessionId:_,canReply:()=>v&&e.capabilities.has(gI),reply:t=>e.capabilities.require(gI).reply(t)}),[e,a,g,_,v]),b=(0,Q.useCallback)(()=>{m?.clear(),i(null),o(null),h.reset()},[m,h.reset]);return{canRead:s,canManage:c,rows:f,selected:p,session:y,action:h,loading:s&&(l.isPending||d.some(e=>e.isPending)),failed:s&&(l.isError||d.some(e=>e.isError)),clear:b,select:e=>{s&&(p?.bindingId!==e.bindingId||p.conversation.sessionId!==e.conversation.sessionId||a===null)&&(i({bindingId:e.bindingId,sessionId:e.conversation.sessionId}),o(null),h.reset(),m?.select(e.agentId,e.conversation.sessionId))}}}var yI=(0,Q.lazy)(async()=>({default:(await mc(()=>import(`./website-conversation-CpPJ8N_o.js`),__vite__mapDeps([8,1,9,2,3,4,5,10,11,12]))).WebsiteConversation})),bI=(0,Q.lazy)(async()=>({default:(await mc(()=>import(`./parakeet-conversation-D8vRtIjX.js`),__vite__mapDeps([13,1,9,2,3,4,5,10,6,11,12,14]))).ParakeetConversation})),xI={openAgent:oc,createClient:io,autoOpen:!0},SI=[`agent.list`,`agent.manage`,`agent.read`,`agent.send`],CI=[`agent.read`,`agent.send`,`agent.manage`],wI=Eo({family:`grove-session-create-request`,version:1,kinds:{request:{prefix:`request`}}});async function TI(e,t,n,r){let i=await n.openAgent(e.capabilities,{agentId:t}),a=n.createClient({baseUrl:i.baseUrl,eventSource:JC(i.fetch),fetch:i.fetch});try{return await r(a)}finally{Promise.allSettled([a.close(),i.close()])}}function EI({open:e,renderConversation:t,connection:n,commands:r,composeDraft:i,onPrefilled:a,onForked:o,onOpen:s,models:c,autoFocus:l,empty:u,modelPicker:d=!0,opening:f=!1,label:p=`Conversation`}){let m=e.session,h=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{h.current?.toggleAttribute(`inert`,f)},[f]);let[g,_]=(0,Q.useState)({kind:`loading`});return(0,Q.useEffect)(()=>{if(!n||t||!d)return;let r=new AbortController;return _({kind:`loading`}),DF(n.capabilities,e.agentId,r.signal).then(e=>{r.signal.aborted||_({kind:`ready`,models:e})},()=>{r.signal.aborted||_({kind:`unavailable`})}),()=>{r.abort()}},[n,e.agentId,t,d]),(0,Q.useEffect)(()=>{let i=r.contribute({sourceId:`grove-session`,namespace:`session`,commands:[...NC(m,{sourceId:`grove-session`,namespace:`session`,sessionResumeAvailable:!1,forkAvailable:!0,onForked:o}),...t||!d?[]:jx(m,{sourceId:`grove-session`,namespace:`session`,models:g.kind===`ready`?g.models:[],refreshModels:t=>n?DF(n.capabilities,e.agentId,t):Promise.reject(Error(`Agent connection is unavailable`)),availability:()=>g.kind===`ready`&&g.models.length>0?{status:`available`}:{status:`unavailable`,reason:g.kind===`loading`?`Loading this Agent's models`:g.kind===`ready`?`This Agent has no available models`:`This Agent's model catalog is unavailable`}})]});return()=>{i.dispose()}},[r,m,o,t,g,d,n,e.agentId]),(0,$.jsx)(`section`,{ref:h,className:`inbox-conversation min-h-0 min-w-0 flex-1`,"data-inbox-conversation":!0,"aria-busy":f,"aria-label":p,children:t?t(e,i,s):(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(Zg,{className:`m-auto`,framed:!1,message:`Opening conversation…`}),children:(0,$.jsx)(bI,{session:m,draftIdentity:{agentId:e.agentId,sessionId:e.sessionId},connection:n,commands:r,prefill:i,onPrefilled:a,onOpen:s,models:c,autoFocus:l,empty:u})})})}var DI={state:XC,error:null},OI=()=>()=>void 0;function kI(e){return wp(e.connection),(0,$.jsx)(AI,{...e},JSON.stringify(Vg.of(e.connection)))}function AI(e){let t=(0,Q.useMemo)(gF,[e.connection]);return(0,$.jsx)(dF,{value:(0,$.jsx)(jI,{...e,router:t}),children:(0,$.jsx)(sF,{router:t})})}function jI({router:e,connection:t,services:r=xI}){let{agentFilterId:i,setFilter:a,selection:o,open:s}=vF(e,t?.window.navigation),c=He(),l=vI(t,r),u=(0,Q.useMemo)(()=>t===null?null:ow({connection:t,queryClient:c,services:r,navigate:t=>t===null?e.navigate({to:`/`,search:!0,replace:!0}):s(t.agentId,t.sessionId),shownRoute:()=>_F(e)}),[t,s,c,e,r]),d=(0,Q.useSyncExternalStore)(u?.subscribe??OI,u?.snapshot??(()=>DI)),{directory:f,inbox:p,computerChoices:m,createAgent:h,renameAgent:g,setAgentAvatar:_}=OF(t),v=f.data??[],y=f.isPending&&(t?.capabilities.has(Gs)??!0),b=f.error?.message??null,x=h.isPending,S=Wc({mutationFn:e=>{if(!t)throw Error(`No App connection`);return TI(t,e.agentId,r,t=>t.createSession(e.requestId))}}),C=Wc({mutationFn:e=>{if(!t)throw Error(`No App connection`);return TI(t,e.agentId,r,t=>t.deleteSession(e.sessionId))},onError:()=>{t&&pr(t.ui,{variant:`error`,message:`The conversation could not be deleted. Try again.`})},onSuccess:(e,t)=>{o?.agentId===t.agentId&&o.sessionId===t.sessionId&&u?.leave(!0),p.refresh()}}),w=S.isPending?S.variables.agentId:null,T=aw(d.state),E=iw(d.state),[D,O]=(0,Q.useState)(!1),k=E?.agentId??null,A=E?.sessionId??null,[M,N]=(0,Q.useState)(null),ee=(0,Q.useRef)(null),[te,ne]=ZF((0,Q.useMemo)(()=>t?.capabilities.has(jw)?t.capabilities.require(jw):void 0,[t])),{agentRailOpen:P,listRailOpen:F,listWidth:re}=te,I=e=>{ne(t=>({...t,agentRailOpen:e(t.agentRailOpen)}))},L=e=>{ne(t=>({...t,listRailOpen:e(t.listRailOpen)}))},R=e=>{ne(t=>({...t,listWidth:JF(e(t.listWidth))}))},z=HF({begin:()=>!0,move:e=>{R(t=>t+e)},end:()=>void 0}),[ie,ae]=(0,Q.useState)(!1),oe=(0,Q.useRef)(null),se=vE(oe),B=se??!0,ce=(0,Q.useRef)(null),[le,ue]=(0,Q.useState)(null),V=h.error?.message??null,de=h.data,H=(0,Q.useRef)(null),[fe,pe]=(0,Q.useState)(null),[me,he]=(0,Q.useState)(null),ge=wp(t),_e=ge?.openRequest??null,U=ge?.setup?.models===`missing`,ve=(0,Q.useRef)(null),ye=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(u!==null)return u.observeRoute(ye.current),()=>{H.current=null,u.close()}},[u]);let[be,xe]=(0,Q.useState)(null),Se=(0,Q.useMemo)(()=>Ke(),[]),Ce=(0,Q.useMemo)(()=>t===null?null:YC({connection:t,queryClient:c,services:r,onPending:()=>void 0,onConversation:xe,onError:pe,reportsSelection:!1}),[t,c,r]);(0,Q.useEffect)(()=>Ce===null?void 0:()=>{Ce.close()},[Ce]);let we=(0,Q.useCallback)(e=>{let t=t=>e.params.find(e=>e.key===t)?.value,n=t(`agent`),r=t(`session`);n!==void 0&&r!==void 0&&Ce?.select(n,r)},[Ce]),Te=(0,Q.useCallback)((e,t,n=!1)=>{u!==null&&(S.isError&&S.reset(),l.clear(),O(!1),u.select({agentId:e,sessionId:t},n?`host`:`person`))},[u,l.clear,S.isError,S.reset]),Ee=o?.agentId,De=o?.sessionId;ye.current=Ee!==void 0&&De!==void 0?{agentId:Ee,sessionId:De}:null,(0,Q.useEffect)(()=>{u?.observeRoute(ye.current)},[u,Ee,De]);let Oe=(0,Q.useCallback)(e=>{E&&(Te(E.agentId,e),p.refresh())},[E,Te,p.refresh]);(0,Q.useEffect)(()=>{if(!t||_e===null){_e===null&&(ve.current=null);return}if(_e.kind!==`navigate`||ve.current===_e.requestId)return;let e=_e.params.find(e=>e.key===`agent`)?.value,n=_e.params.find(e=>e.key===`session`)?.value;!e||!n||(ve.current=_e.requestId,a(e),Te(e,n,!0))},[t,_e,Te,a]);let ke=(0,Q.useCallback)(async e=>{if(!t||x||!t.capabilities.has(ic))return!1;try{let t=await h.mutateAsync(e);return a(t.agentId),ue(t.agentId),N(null),!0}catch{return!1}},[t,x,h.mutateAsync,a]),Ae=!!E||l.selected!==void 0,je=(0,Q.useCallback)(async(e,n=`person`)=>{if(!t||!u||w!==null)return`Conversation creation is unavailable.`;let r=u.create(n);if(!r.accepted||r.ticket===null)return;pe(null);let i=H.current?.agentId===e?H.current:{agentId:e,requestId:wI.request.generate()};H.current=i;try{let t=await S.mutateAsync(i);u.created(r.ticket,{agentId:e,sessionId:t}).accepted&&(S.isError&&S.reset(),l.clear(),O(!1)),p.refresh(),N(null),ae(!1),H.current===i&&(H.current=null);return}catch(e){return u.createFailed(r.ticket),console.error(`Grove conversation creation failed`,e),Ae&&pr(t.ui,{variant:`error`,message:`The conversation could not be started. Try again.`}),e instanceof Error?e.message:`Couldn't start the conversation.`}},[t,Ae,u,w,S.isError,S.mutateAsync,S.reset,l.clear,p.refresh]);(0,Q.useEffect)(()=>{if(!(!t||_e?.kind!==`compose`)&&ve.current!==_e.requestId&&!(!E&&y)&&(ve.current=_e.requestId,he({requestId:_e.requestId,text:_e.text}),!E)){let e=t.capabilities.has(qs)?v.find(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)):void 0;e?je(e.agentId):N(`agent`)}},[v,t,y,E,_e,je]);let Ne=TF({setDraft:e=>T!==null||!E||!t?.capabilities.has(qs)||!v.some(e=>e.agentId===E.agentId&&e.sessionOperations.includes(`agent.send`))?!1:(he({requestId:No(),text:e}),!0),newConversation:()=>{E&&je(E.agentId)},openPermissions:()=>{t?.ui.requestAppPermissions({}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})}},t?.commands),Pe=new Set(l.rows.map(e=>`${e.agentId}:${e.conversation.sessionId}`)),Fe=p.items.filter(e=>!(`kind`in e)).filter(e=>!Pe.has(`${e.agentId}:${e.sessionId}`)),Ie=Vc({queries:(E?[E.session]:[]).map(e=>({...Er(e),enabled:!1}))}).at(0)?.data?.snapshot,Le=(0,Q.useMemo)(()=>E&&Ie?{agentId:E.agentId,sessionId:E.sessionId,state:j(Ie)}:void 0,[E,Ie]),Re=(0,Q.useMemo)(()=>cE(v,D&&l.canRead?[]:Fe,i,Le),[i,v,Fe,D,l.canRead,Le]),ze=(0,Q.useMemo)(()=>{let e=new Map;for(let t of Fe)`state`in t&&(t.state===`needs_you`?e.set(t.agentId,`speaking`):t.state===`running`&&!e.has(t.agentId)&&e.set(t.agentId,`thinking`));return e},[Fe]),Be=(0,Q.useMemo)(()=>new Map(v.map(e=>[e.agentId,e])),[v]),Ve=(0,Q.useRef)(null),Ue=Fe.find(e=>e.agentId===k&&e.sessionId===A),We=Ue!==void 0&&Ue.state!==`unavailable`,Ge=Ue!==void 0&&Ue.state!==`unavailable`?Ue.settledAt:void 0;(0,Q.useEffect)(()=>{!We||k===null||A===null||p.visit(k,A).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},[We,Ge,k,A,p.visit]);let qe=p.status===`loading`,Je=p.status===`error`,Ye=t?.capabilities.has(ic)??!1,Xe=t?.capabilities.has(qs)??!1,Ze=v.filter(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)),Qe=Ze.find(e=>e.agentId===(le??i))??Ze.at(0),$e=Xe&&Qe!==void 0,et=()=>{t?.ui.requestAppPermissions({agents:SI}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},tt=de&&(!de.sessionOperations.includes(`agent.read`)||!de.sessionOperations.includes(`agent.send`)||!de.sessionOperations.includes(`agent.manage`))?`Agent created. Allow Grove to read, send messages and manage its sessions to start a conversation.`:me&&!E&&!$e&&h.isIdle?`Choose an Agent to compose your game idea.`:null,nt=(0,Q.useMemo)(()=>cE(v,Fe,null,Le),[v,Fe,Le]),rt=(e,t)=>{ae(!1),Te(e,t)},it=()=>{ce.current=document.activeElement instanceof HTMLElement?document.activeElement:null,ae(!0)},at=uE(Re).length,ot=B&&F,st=B&&U&&at===0&&Re.unavailable.length===0&&l.rows.length===0&&!E&&!l.selected&&!y&&!qe&&!l.loading&&!Je&&!b&&!l.failed;Tp(t,[...B?[{kind:`button`,id:`agents`,text:`Agents`,expanded:P,title:P?`Hide Agents`:`Show Agents`},...st?[]:[{kind:`button`,id:`conversations`,text:`Conversations`,expanded:F,title:F?`Hide conversations`:`Show conversations`}]]:[{kind:`button`,id:`agents`,text:`Agents and conversations`,opens:`dialog`,expanded:ie}],...be===null?[]:[{kind:`button`,id:`close-beside`,text:`Close beside`,title:`Close beside conversation`}]],e=>{if(M!==null)return!1;if(e.itemId===`close-beside`&&be!==null)Ce?.clear();else if(B&&e.itemId===`agents`)I(e=>!e);else if(B&&e.itemId===`conversations`)L(e=>!e);else if(!B&&e.itemId===`agents`)ie?ae(!1):it();else return!1;return!0});let lt=e=>{a(e),ue(e);let t=[...nt.active,...nt.settled].filter(t=>t.agentId===e).sort((e,t)=>t.lastActivityAt-e.lastActivityAt).at(0);t&&rt(e,t.sessionId)},ut={"--grove-list-width":`${String(re)}px`},dt=E?Be.get(E.agentId):void 0,ft=i===null?void 0:Be.get(i),pt=t?.capabilities.has(Fs)??!1,mt=v.length===1?v[0]:void 0,ht=ft??mt,gt=t?.capabilities.has(tc)??!1,_t=kF(t,ft?.agentId??null),vt=AF(t,ft?.agentId??null),yt=(0,Q.useCallback)(async(e,t)=>{try{return await vt.save.mutateAsync({agentId:e,...t}),`saved`}catch(e){return e instanceof Z&&e.code===`CONFLICT`?`conflict`:e instanceof Z&&e.code===`FILE_TOO_LARGE`?`too_large`:`failed`}},[vt.save.mutateAsync]),bt=(0,Q.useCallback)(async()=>{let e=await vt.read.refetch({throwOnError:!0});if(e.data===void 0)throw Error(`No instructions file`);return e.data},[vt.read.refetch]),xt=(0,Q.useCallback)((e,n)=>{t?.ui.showToast({message:e,tone:n}).catch(e=>{console.error(`Instructions toast failed`,e)})},[t]),St=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{r.autoOpen!==!0||St.current||!t||E||_e!==null||y||qe||Je||b||U||at>0||Qe===void 0||!Xe||w!==null||(St.current=!0,je(Qe.agentId,`auto`))},[Xe,t,y,b,Je,at,qe,U,E,_e,r.autoOpen,Qe,je,w]);let Ct=(0,Q.useCallback)(async(e,n)=>{if(!t)return!1;try{return await g.mutateAsync({agentId:e,name:n}),!0}catch{return!1}},[t,g.mutateAsync]),wt=(0,Q.useCallback)(async(e,n)=>{if(!t)return!1;try{return await _.mutateAsync({agentId:e,avatar:n}),!0}catch{return!1}},[t,_.mutateAsync]),Tt=(0,Q.useCallback)(()=>{let e=_t.status.data;!ft||e==null||_t.approve.mutate({agentId:ft.agentId,expectedRevision:e.revision})},[ft,_t.status.data,_t.approve]),Et=(0,Q.useCallback)(e=>{if(!(!t||x||w!==null||e===`agent`&&!Ye)){if(e===`agent`&&U){t.ui.showToast({message:pE,tone:`info`}).catch(e=>{console.error(`Grove toast failed`,e)});return}M===null&&(ee.current=ie?ce.current:document.activeElement instanceof HTMLElement?document.activeElement:null),ae(!1),e===`session`&&ue(dt?.agentId??i??Ze.at(0)?.agentId??null),N(e)}},[t,x,w,Ye,U,M,ie,dt?.agentId,i,Ze]);(0,Q.useEffect)(()=>{let e=e=>{e.defaultPrevented||e.repeat||!e.ctrlKey||e.altKey||e.metaKey||e.key.toLowerCase()!==`n`||!t||e.shiftKey&&!Ye||(e.preventDefault(),Et(e.shiftKey?`agent`:`session`))};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[t,Ye,Et]);let Dt=S.isError?S.variables:null,Ot=Dt&&M!==`session`&&!Ae?(0,$.jsx)(n,{className:`inbox-empty m-auto max-w-[28rem]`,tone:`error`,title:`Couldn't start the conversation.`,description:S.error?.message,action:(0,$.jsx)(W,{variant:`outline`,onClick:()=>void je(Dt.agentId),children:`Retry`})}):null;return(0,$.jsxs)(`main`,{ref:oe,className:`inbox-app grove-shell @container/grove relative flex h-dvh min-h-0 bg-base-200 font-sans text-base-content`,"data-inbox-app":!0,"data-conversation":!!E||l.selected!==void 0,children:[t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(OA,{open:M===`agent`,pending:x,error:V,addCredit:h.error instanceof Z&&h.error.code===`INSUFFICIENT_CREDIT`?()=>t.ui.openTeamBilling():null,computers:m.isError?{status:`unavailable`,message:`Your Computers could not be loaded. New Computer and No Computer still work.`}:m.isPending?{status:`loading`}:m.data===null?{status:`not-offered`}:{status:`offered`,computers:m.data},create:ke,onClose:()=>{N(null)},returnFocus:ee}),M===`session`?(0,$.jsx)(kA,{open:!0,agents:Xe?Ze:[],defaultAgentId:Qe?.agentId??null,start:je,pending:w!==null,onClose:()=>{N(null)},onNewAgent:Ye?()=>{N(`agent`)}:void 0,returnFocus:ee}):null]}):null,se===null?null:(0,$.jsxs)(yE,{desktop:B,open:ie,onOpenChange:ae,returnFocus:ce,children:[(0,$.jsx)(hE,{open:P,agents:v,agentActivity:ze,agentFilterId:i,websitesSelected:D,websitesVisible:l.canRead,canCreate:t!==null&&Ye,modelsMissing:U,createOpen:M===`agent`,onAll:()=>{a(null),O(!1)},onWebsites:()=>{a(null),O(!0)},onAgent:e=>{O(!1),lt(e)},onCreate:()=>{Et(`agent`)}}),st?null:(0,$.jsxs)(`aside`,{id:`grove-list-rail`,className:`inbox-sidebar group relative min-h-0 min-w-0 flex-1 flex-col border-r border-base-300 @min-[900px]/grove:w-[var(--grove-list-width)] @min-[900px]/grove:flex-none ${F?`flex`:`flex @min-[900px]/grove:hidden`}`,style:ut,"aria-label":`Conversations`,children:[B?(0,$.jsx)(VF,{"aria-label":`Conversation list width`,"aria-controls":`grove-list-rail`,className:`absolute right-0 top-1/2 z-10 translate-x-1/2 -translate-y-1/2`,orientation:`vertical`,value:re,min:WF.min,max:WF.max,onValueChange:e=>{R(()=>e)},onDoubleClick:()=>{R(()=>WF.initial)},...z}):null,(0,$.jsxs)(`header`,{className:`inbox-header flex h-10 flex-none items-center gap-1 border-b border-base-300 pl-3 pr-1`,children:[ft?(0,$.jsx)(BF,{agentId:ft.agentId,name:fE(ft),avatar:ft.avatar,...gt?{setAvatar:wt}:{}},ft.agentId):null,(0,$.jsx)(Wt,{level:2,className:`m-0 min-w-0 flex-1 truncate text-sm`,children:D&&l.canRead?`Websites`:ft?fE(ft):`All agents`}),ht&&pt?(0,$.jsx)(bF,{agentId:ht.agentId,name:ht.name,rename:Ct},ht.agentId):null,ft&&vt.canUse?(0,$.jsx)(zF,{agentId:ft.agentId,name:ft.name,file:vt.read.data,loading:vt.read.isPending,save:yt,reload:bt,notify:xt},ft.agentId):null,t&&($e||Ye)?(0,$.jsx)(ct,{"aria-label":`New conversation`,"aria-haspopup":`dialog`,icon:(0,$.jsx)(HC,{}),iconSize:`sm`,size:`sm`,onClick:()=>{Et(`session`)}}):null]}),ft&&_t.canRead?(0,$.jsx)(xF,{status:_t.status.data,approving:_t.approve.isPending,onApprove:Tt}):null,tt?(0,$.jsx)(n,{tone:`info`,title:tt,action:(0,$.jsx)(W,{variant:`ghost`,onClick:()=>{t?.ui.requestAppPermissions({agents:CI}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},children:`Allow conversation access`})}):null,t&&v.length>0&&!$e&&!Ye?(0,$.jsxs)(`section`,{className:`inbox-create inbox-access flex flex-col items-start gap-3 border-b border-base-300 py-2`,"aria-labelledby":`inbox-agent-access-title`,children:[(0,$.jsx)(Wt,{level:2,id:`inbox-agent-access-title`,className:`inbox-access-title m-0`,children:`Let Grove manage your Agents`}),(0,$.jsx)(`p`,{children:`Grove creates Agents and carries their conversations. Your Team decides what it may do.`}),(0,$.jsx)(W,{size:`sm`,onClick:et,children:`Allow Agent access`})]}):null,b?(0,$.jsx)(n,{className:`inbox-error`,tone:`error`,title:b,action:(0,$.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>{f.refetch()},children:`Try again`})}):null,Je?(0,$.jsx)(n,{className:`inbox-error`,tone:`error`,title:`Conversations are unavailable.`,action:(0,$.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>{p.refresh()},children:`Retry conversations`})}):null,(0,$.jsx)(DT,{ref:Ve,className:`inbox-surface min-h-0 flex-1`,"aria-label":`Conversations`,children:t?y?(0,$.jsx)(Zg,{framed:!1,message:`Loading Agents…`}):(0,$.jsx)(nI,{viewport:Ve,view:Re,agents:Be,loading:qe||l.loading,failed:!!b||Je||l.failed,showEmptyState:!U,pendingSelection:T,selectedAgentId:k,selectedSessionId:A,onSelect:rt,onDelete:Xe?(e,t)=>{C.mutate({agentId:e,sessionId:t})}:void 0,deleting:C.isPending?C.variables:null,websites:l.rows.filter(e=>i===null||e.agentId===i),selectedWebsite:l.selected,onSelectWebsite:e=>{u?.leave(!1),ae(!1),l.select(e)}}):(0,$.jsx)(`p`,{className:`inbox-empty m-0 px-2 py-3 text-sm text-(--stipe-fg-muted)`,children:`Connect to the host to browse Agents.`})},i)]}),B&&!F&&!st?(0,$.jsx)(`div`,{className:`flex w-10 flex-none flex-col items-center border-r border-base-300 pt-1`,children:(0,$.jsx)(ct,{"aria-label":`Show conversations`,"aria-controls":`grove-list-rail`,"aria-expanded":!1,icon:(0,$.jsx)(zC,{}),iconSize:`sm`,size:`sm`,onClick:()=>{L(()=>!0)}})}):null]}),(0,$.jsxs)(`section`,{className:`inbox-conversation-shell flex min-h-0 min-w-0 flex-1 flex-col`,"aria-label":`Conversation`,children:[(0,$.jsx)(gE,{app:t}),fe??d.error?(0,$.jsx)(n,{className:`inbox-error m-2`,tone:`error`,title:fe??d.error??``}):null,l.selected?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(yI,{inbox:l,ui:t?.ui??null})}):T!==null&&E===null?(0,$.jsx)(Zg,{className:`m-auto`,framed:!1,message:`Opening conversation…`}):E?(0,$.jsx)(EI,{open:E,connection:t,commands:Ne,renderConversation:r.renderConversation,composeDraft:me,onPrefilled:()=>{he(null)},onForked:Oe,onOpen:we,models:ge?.setup?.models,autoFocus:B&&M===null,opening:T!==null}):!t||y?(0,$.jsx)(Zg,{className:`m-auto`,framed:!1,message:t?`Loading Agents…`:`Connecting to Oyster…`}):U&&(v.length>0||Ye)?(0,$.jsx)($F,{connection:t,navigation:B?void 0:{open:ie,onOpen:it}}):v.length===0&&!b?(0,$.jsx)(Me,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`speech`,thinking:x,renderVisual:({speaking:e,thinking:t})=>(0,$.jsx)(WC,{className:`h-full w-full`,state:{activity:t?`thinking`:e?`speaking`:`idle`,expression:`normal`}}),title:Ye?`Meet your first Agent`:`Welcome to Grove`,description:Ye?`An Agent is an AI helper. Name one to chat, write and make things together.`:`Let Grove find your AI helpers, create new ones, and open conversations. Your Team controls this access.`,actions:Ye?(0,$.jsx)(W,{onClick:()=>{Et(`agent`)},children:`Name your first Agent`}):(0,$.jsx)(W,{onClick:et,children:`Allow Agent access`})}):Ot??(0,$.jsx)(Me,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`panel`,title:at>0?`Pick up a conversation`:Qe?`Say hello to ${fE(Qe)}`:`No conversations yet`,description:at>0?`${ot?`Choose one from the list`:`Open the conversation list to choose one`}, or ask for something new. A short writing task is a good start.`:`Ask anything.`,actions:(0,$.jsxs)($.Fragment,{children:[B||at===0?null:(0,$.jsx)(W,{variant:`outline`,"aria-haspopup":`dialog`,"aria-controls":`grove-nav`,"aria-expanded":ie,onClick:it,children:`Agents and conversations`}),$e?(0,$.jsx)(W,{variant:`outline`,loading:w===Qe.agentId,disabled:w!==null,onClick:()=>void je(Qe.agentId),children:at>0?`Ask ${fE(Qe)} something`:`Start a conversation`}):null]})})]}),be===null?null:(0,$.jsx)(`section`,{className:`inbox-conversation-shell flex min-h-0 min-w-0 flex-1 flex-col border-l border-base-300`,"aria-label":`Beside conversation`,"data-inbox-beside":!0,children:(0,$.jsx)(EI,{open:be,connection:t,commands:Se,renderConversation:r.renderConversation,composeDraft:null,onPrefilled:()=>void 0,onForked:e=>{Ce?.select(be.agentId,e)},onOpen:we,models:ge?.setup?.models,label:`Beside conversation`})})]})}var MI=[`I write code`,`I run a small business`,`I make art and video`,`Just looking around`];function NI(e,t){return{appId:e.appId,intent:{kind:`navigate`,params:t}}}function PI(e){return[{key:`agent`,value:e.agentId},{key:`session`,value:e.sessionId}]}var FI={state:XC,error:null},II=()=>()=>void 0;function LI(e){let t=wp(e.connection)?.openRequest??null,n=t?.kind===`navigate`?t.params.find(e=>e.key===`gill`)?.value:void 0,[r,i]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{n!==void 0&&i(n)},[n]),(r??n)===`chat`?(0,$.jsx)(RI,{...e}):(0,$.jsx)(kI,{connection:e.connection,...e.services===void 0?{}:{services:e.services}})}function RI(e){return(0,$.jsx)(HI,{...e},JSON.stringify(Vg.of(e.connection)))}var zI=260;function BI(e){let t=(0,Q.useRef)(null),[n,r]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{let n=t.current;if(!n)return;let i=`ResizeObserver`in globalThis?new ResizeObserver(([t])=>{r(t.contentRect.height<e)}):void 0;return i?.observe(n),()=>{i?.disconnect()}},[e]),[t,n]}function VI({agent:e}){let t=Jn(),[n,r]=BI(zI),i=e===void 0?`your Agent`:fE(e);return(0,$.jsxs)(`div`,{ref:n,className:`chat-gill-empty flex h-full min-h-0 flex-col items-center justify-center gap-md overflow-y-auto px-md py-sm text-center`,children:[e===void 0||r?null:(0,$.jsx)(Ln,{avatar:e.avatar,className:`chat-gill-hero`,name:i,size:72}),(0,$.jsxs)(`h2`,{className:`text-lg font-semibold text-base-content`,children:[`Hi, I’m `,i,`. What brings you here?`]}),(0,$.jsx)(`div`,{"aria-label":`What brings you here?`,className:`flex flex-wrap justify-center gap-sm`,role:`group`,children:MI.map(e=>(0,$.jsx)(W,{size:`sm`,variant:`outline`,onClick:()=>{t.setDraft(e),t.send()},children:e},e))})]})}function HI({connection:e,services:t=xI,funding:n,openFunding:r}){let i=He(),a=wp(e),{directory:o,inbox:s}=OF(e),c=vI(e,t),l=(0,Q.useMemo)(()=>Ke(),[]),u=o.data??[],d=u.find(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)),f=e?.capabilities.has(qs)??!1,p=(0,Q.useMemo)(()=>e===null?null:ow({connection:e,queryClient:i,services:t}),[e,i,t]);(0,Q.useEffect)(()=>()=>{p?.close()},[p]);let m=(0,Q.useSyncExternalStore)(p?.subscribe??II,p?.snapshot??(()=>FI)),h=iw(m.state),g=aw(m.state),_=m.state.creating!==null,[v,y]=(0,Q.useState)(!1),b=(0,Q.useMemo)(()=>{if(d===void 0)return;let e=new Set(c.rows.map(e=>`${e.agentId}:${e.conversation.sessionId}`)),t=cE(u,s.items.filter(t=>!(`kind`in t)&&!e.has(`${t.agentId}:${t.sessionId}`)),d.agentId);return[...t.active,...t.settled].sort((e,t)=>t.lastActivityAt-e.lastActivityAt).at(0)},[d,u,s.items,c.rows]),x=(0,Q.useCallback)(async n=>{if(!e||!p||d===void 0)return;let r=p.create(n);if(!(!r.accepted||r.ticket===null)){y(!1);try{let n=await TI(e,d.agentId,t,e=>e.createSession(wI.request.generate()));p.created(r.ticket,{agentId:d.agentId,sessionId:n}),s.refresh()}catch(t){p.createFailed(r.ticket),console.error(`Grove chat widget could not start a conversation`,t),y(!0),pr(e.ui,{variant:`error`,message:`The conversation could not be started. Try again.`})}}},[d,e,s.refresh,t,p]),S=(0,Q.useRef)(null),C=e!==null&&!o.isPending&&s.status!==`loading`&&s.status!==`error`&&!c.loading;(0,Q.useEffect)(()=>{!C||!p||d===void 0||!f||m.state.view.kind!==`none`||_||S.current!==d.agentId&&(S.current=d.agentId,b===void 0?x(`auto`):p.select({agentId:d.agentId,sessionId:b.sessionId},`host`))},[d,f,_,b,C,m.state.view.kind,x,p]);let w=(0,Q.useCallback)(t=>{e&&(async()=>{try{await e.capabilities.require(Jg).open(NI(e.identity,t))}catch(t){console.error(`Grove chat widget could not open Grove`,t),pr(e.ui,{variant:`error`,message:`Grove could not be opened. Try again.`})}})()},[e]),T=e?.capabilities.has(Jg)??!1,E=(0,Q.useCallback)(e=>{!h||!p||(p.select({agentId:h.agentId,sessionId:e}),s.refresh())},[s.refresh,h,p]),D=(h===null?void 0:u.find(e=>e.agentId===h.agentId))??d,O=n?.resourceFunding===`setup`?n:void 0,k;return k=h?null:!e||o.isPending||g!==null||_?(0,$.jsx)(Zg,{className:`m-auto`,framed:!1,message:e?`Getting ready…`:`Connecting…`}):d===void 0||!f?(0,$.jsx)(`p`,{className:`m-auto max-w-[22rem] px-md text-center text-sm text-dim`,children:`Open Grove to set up an Agent and allow it to chat.`}):(0,$.jsxs)(`div`,{className:`m-auto flex flex-col items-center gap-sm`,children:[(0,$.jsx)(`p`,{className:`text-sm text-dim`,children:v||m.error!==null?`The conversation could not be started.`:`No conversation is open.`}),(0,$.jsx)(W,{variant:`outline`,onClick:()=>{x(`person`)},children:`Start a conversation`})]}),(0,$.jsxs)(`main`,{className:`chat-gill @container/grove relative flex h-dvh min-h-0 flex-col bg-base-100 font-sans text-base-content data-[funding=setup]:[&_.parakeet-composer-model-key]:hidden`,"data-chat-gill":!0,"data-funding":n?.resourceFunding??`unknown`,children:[(0,$.jsxs)(`header`,{className:`flex flex-none items-center gap-sm border-b border-base-300 px-md py-xs`,children:[D===void 0?null:(0,$.jsx)(Ln,{avatar:D.avatar,name:fE(D),size:20}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-semibold`,children:D===void 0?`Grove`:fE(D)}),(0,$.jsx)(W,{disabled:!T,size:`xs`,variant:`ghost`,onClick:()=>{w(h===null?[]:PI(h))},children:`Open in Grove`}),(0,$.jsxs)(rx,{children:[(0,$.jsx)(ax,{render:(0,$.jsx)(ct,{"aria-label":`Conversation options`,icon:(0,$.jsx)(PC,{}),size:`sm`})}),(0,$.jsx)(lx,{align:`end`,children:(0,$.jsx)(dx,{disabled:d===void 0||!f||_,onSelect:()=>{x(`person`)},children:`New conversation`})})]})]}),(0,$.jsx)(`section`,{"aria-label":`Conversation`,className:`flex min-h-0 min-w-0 flex-1 flex-col`,children:h?(0,$.jsx)(EI,{commands:l,composeDraft:null,connection:e,empty:(0,$.jsx)(VI,{agent:D}),label:`Chat`,modelPicker:O===void 0,models:a?.setup?.models,onForked:E,onOpen:e=>{w(e.params)},onPrefilled:()=>void 0,open:h,opening:g!==null,renderConversation:t.renderConversation},`${h.agentId}:${h.sessionId}`):k}),O===void 0?null:(0,$.jsxs)(`p`,{className:`flex-none px-md pb-sm text-center text-xs text-dim`,"data-chat-gill-footer":!0,children:[`Setup credit:`,` `,(0,$.jsx)(`strong`,{className:`font-semibold`,children:O.setupCredit}),` · `,r===void 0?`Start Pro`:(0,$.jsx)(W,{className:`align-baseline`,size:`xs`,variant:`link`,onClick:r,children:`Start Pro`})]})]})}var UI=document.getElementById(`inbox-root`);if(!UI)throw Error(`Inbox root is missing`);xp(UI,{name:`Grove`,queryClient:Ug()},({app:e})=>(0,Q.createElement)(LI,{connection:e}));export{Rx as a,Uc as c,BS as i,nA as n,Yg as o,eC as r,Vg as s,aA as t};
|