@fungi.computer/grove 0.22.2 → 0.22.4

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.
@@ -1,25 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/website-conversation-CAaCsY4j.js","assets/rolldown-runtime-CbXtAM7H.js","assets/conversation-toast-DLjWIccZ.js","assets/document-DZTTyAQ6.js","assets/parakeet-B4_DpKWW.js","assets/parakeet-conversation-Dluuo5dN.js","assets/parakeet-conversation-COndlivb.css"])))=>i.map(i=>d[i]);
2
- import{n as e,t}from"./rolldown-runtime-CbXtAM7H.js";import{$ as n,$a as r,$i as i,$n as a,$o as o,$r as s,$t as c,A as l,Aa as u,Ai as d,An as f,Ao as p,Ar as m,B as h,Ba as g,Bi as _,Bn as v,Bo as y,Br as b,C as x,Ca as S,Ci as C,Cn as w,Co as T,Cr as E,D,Da as O,Dn as k,Do as A,Dr as j,E as M,Ea as ee,Ei as te,En as ne,Eo as N,Er as P,F as re,Fa as F,Fi as I,Fn as ie,Fo as L,Fr as ae,G as oe,Ga as se,Gi as ce,Gn as le,Go as R,Gr as ue,Gt as de,H as fe,Ha as pe,Hi as me,Hn as he,Ho as z,Hr as ge,Ht as _e,I as ve,Ia as ye,Ii as be,In as xe,Io as Se,Ir as Ce,J as we,Ja as Te,Ji as Ee,Jn as De,Jo as Oe,Jr as ke,K as Ae,Ka as je,Ki as Me,Kn as Ne,Ko as Pe,Kr as Fe,L as Ie,La as Le,Li as Re,Ln as ze,Lo as Be,Lr as Ve,M as He,Ma as Ue,Mi as We,Mn as Ge,Mo as Ke,Mr as qe,Mt as Je,N as Ye,Na as Xe,Ni as Ze,Nn as Qe,No as $e,Nr as et,Nt as tt,O as nt,Oa as rt,Oi as it,On as at,Oo as ot,Or as st,P as ct,Pa as lt,Pi as ut,Pn as dt,Po as ft,Pr as pt,Q as mt,Qa as B,Qn as ht,Qo as gt,Qr as _t,Qt as vt,R as yt,Ra as bt,Rn as xt,S as St,Sa as Ct,Si as wt,Sn as Tt,So as V,Sr as Et,T as Dt,Ta as Ot,Ti as kt,Tn as At,To as jt,Tr as Mt,U as Nt,Ua as Pt,Un as Ft,Uo as H,Ur as It,V as Lt,Va as Rt,Vi as zt,Vn as Bt,Vo as Vt,Vr as Ht,W as Ut,Wa as Wt,Wi as Gt,Wn as Kt,Wo as qt,Wr as Jt,X as Yt,Xa as Xt,Xi as U,Xn as Zt,Xo as Qt,Xr as $t,Xt as en,Y as tn,Ya as nn,Yi as rn,Yn as an,Yo as on,Yr as sn,Z as cn,Za as ln,Zi as un,Zn as dn,Zo as fn,Zr as pn,Zt as mn,_ as hn,_a as gn,_i as _n,_n as vn,_o as yn,_r as bn,_s as xn,a as Sn,aa as Cn,ai as wn,an as Tn,ao as W,ar as En,as as Dn,b as On,ba as kn,bn as An,bo as jn,br as Mn,bs as Nn,ca as Pn,ci as Fn,cn as In,co as Ln,cr as Rn,cs as zn,d as Bn,da as Vn,di as Hn,dn as Un,do as Wn,dr as Gn,ds as Kn,ea as qn,ei as Jn,eo as Yn,er as Xn,es as Zn,fa as Qn,fi as $n,fn as er,fo as G,fr as tr,fs as nr,g as rr,ga as ir,gi as ar,gn as or,go as sr,gr as cr,gs as lr,gt as ur,h as dr,ha as fr,hi as pr,hn as mr,ho as hr,hr as gr,hs as _r,ht as vr,i as yr,ia as br,ii as xr,in as Sr,io as K,ir as Cr,is as wr,j as Tr,ja as Er,ji as Dr,jn as Or,jo as kr,jr as Ar,jt as jr,k as Mr,ka as Nr,ki as Pr,kn as Fr,kr as Ir,la as Lr,li as Rr,ln as zr,lo as Br,lr as Vr,ls as Hr,m as Ur,ma as Wr,mi as Gr,mn as Kr,mo as qr,mr as Jr,mt as Yr,n as Xr,na as Zr,ni as Qr,no as $r,nr as ei,ns as ti,nt as ni,o as ri,oa as ii,oi as ai,on as oi,or as si,os as ci,p as li,pa as ui,pi as di,pn as fi,po as q,pr as pi,ps as mi,q as hi,qa as gi,qi as _i,qn as vi,qo as yi,qr as bi,r as xi,ra as Si,ri as Ci,rn as wi,ro as Ti,rr as Ei,rs as Di,sa as Oi,si as ki,sn as Ai,so as ji,sr as Mi,ss as Ni,t as Pi,ta as Fi,ti as Ii,to as Li,tr as Ri,ts as zi,ui as Bi,un as Vi,uo as Hi,ur as Ui,us as Wi,v as Gi,va as Ki,vn as qi,vr as Ji,vs as Yi,wa as Xi,wi as Zi,wn as Qi,wo as $i,wr as ea,x as ta,xa as na,xi as ra,xn as ia,xo as aa,xr as oa,xs as sa,y as ca,ya as la,yi as ua,yn as da,yo as J,yr as fa,ys as pa,z as ma,za as ha,zn as ga,zo as Y,zr as _a}from"./conversation-toast-DLjWIccZ.js";import{$a as va,Aa as ya,Cr as ba,Dr as xa,Ea as Sa,Er as Ca,Fa as wa,G as Ta,Gi as Ea,Ha as Da,Ia as Oa,Ii as ka,Ja as Aa,Jt as ja,Ka as Ma,La as Na,Ma as Pa,Mr as Fa,Or as Ia,Pa as La,Pr as Ra,Ra as za,Ua as Ba,Vi as Va,Xa as Ha,Xt as Ua,Ya as Wa,Yi as Ga,_a as Ka,aa as qa,ba as Ja,br as Ya,bt as Xa,ca as Za,da as Qa,en as $a,et as eo,fa as to,ga as no,ha as ro,i as io,ia as ao,ja as oo,jr as so,ka as co,kr as lo,la as uo,ma as fo,na as po,oa as mo,pa as ho,ra as go,ro as _o,sa as vo,tn as yo,to as bo,ua as xo,va as So,wa as Co,xa as wo,za as To}from"./document-DZTTyAQ6.js";import{t as Eo}from"./document-Cfd1McDA.js";import{a as Do,i as Oo,n as ko,r as Ao,t as jo}from"./base-face-9ObbS-xX.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 X=e(sa(),1),Mo=new WeakMap;function No(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=Mo.get(e)??new Map;Mo.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:Nn(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()}}}var Po=G.pipe(V(y(1)),V(Y(80))),Fo=[`CANCELLED`,`CAPABILITY_DENIED`,`CAPABILITY_REVOKED`,`COMMAND_NOT_DECLARED`,`CONFLICT`,`DAILY_LIMIT_REACHED`,`DELIVERY_PENDING`,`DISCONNECTED`,`FILE_TOO_LARGE`,`HOST_FAILURE`,`IDENTITY`,`INSUFFICIENT_CREDIT`,`INVALID_ARGUMENT`,`MEDIA_PROVIDER_FAILURE`,`MEDIA_PROVIDER_FAILURE_UNCHARGED`,`PROTOCOL`,`SAFETY_FILTER_REFUSED`,`SELECTION_CHANGED`,`SETUP_REQUIRED`,`TIMEOUT`];q({name:K(`AppError`),code:W(Fo),retryable:r,need:H(G)});var Z=class extends Error{code;retryable;need;constructor(e,t){super(e,{cause:t.cause}),this.name=`AppError`,this.code=t.code,this.retryable=t.retryable,this.need=t.need}};function Io(e){return`This needs ${e??`setup`} first.`}Io(void 0),ro(`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 Lo=`data-theme`;function Ro(e){return e||(globalThis.document?.documentElement??null)}function zo(e){let t=e.trim();if(t.length===0)throw TypeError(`Theme must be a non-empty string`);return t}function Bo(e,t){let n=zo(e),r=Ro(t);r&&r.setAttribute(Lo,n)}function Vo(e){return Ro(e)?.getAttribute(Lo)??null}function Ho(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var Uo=class extends Wt{#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,Pt.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||!gi(e,n)});!o&&!s||(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(Ho(e,n).forEach(e=>{e.destroy()}),Ho(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=je(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 pe(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)&&Pt.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},Wo=X.createContext(!1),Go=()=>X.useContext(Wo);Wo.Provider;var Q=ln();function Ko(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var qo=X.createContext(Ko()),Jo=()=>X.useContext(qo),Yo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?Te(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Xo=e=>{X.useEffect(()=>{e.clearReset()},[e])},Zo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Te(n,[e.error,r])),Qo=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))}},$o=(e,t)=>e?.suspense&&t.isPending,es=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function ts({queries:e,...t},n){let r=Xt(n),i=Go(),a=Jo(),o=t.subscribed!==!1,s=X.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=>{Qo(e);let t=r.getQueryCache().get(e.queryHash);Yo(e,a,t)}),Xo(a);let[c]=X.useState(()=>new Uo(r,s,t)),[l,u,d]=c.getOptimisticResult(s,t.combine),f=!i&&o;X.useSyncExternalStore(X.useCallback(e=>f?c.subscribe(Pt.batchCalls(e)):se,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),X.useEffect(()=>{c.setQueries(s,t)},[s,t,c]);let p=l.some((e,t)=>$o(s[t],e))?l.flatMap((e,t)=>{let n=s[t];return n&&$o(n,e)?es(n,new pe(r,n),a):[]}):[];if(p.length>0)throw Promise.all(p);let m=l.find((e,t)=>{let n=s[t];return n&&Zo({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 ns(e,t,n){let r=Go(),i=Jo(),a=Xt(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Qo(o),Yo(o,i,s),Xo(i);let[l]=X.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(X.useSyncExternalStore(X.useCallback(e=>{let t=d?l.subscribe(Pt.batchCalls(e)):se;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),X.useEffect(()=>{l.setOptions(o)},[o,l]),$o(o,u))throw es(o,l,i);if(Zo({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function rs(e,t){return ns(e,pe,t)}function is(e,t){let n=Xt(t),[r]=X.useState(()=>new Rt(n,e));X.useEffect(()=>{r.setOptions(e)},[r,e]);let i=X.useSyncExternalStore(X.useCallback(e=>r.subscribe(Pt.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=X.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(se)},[r]);if(i.error&&Te(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var as=t((e=>{var t=Le();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot}))();function os(e,t){console.error(JSON.stringify({source:`agar`,operation:e,failureKind:t instanceof Error?`Error`:`NonErrorThrown`}),mi(t))}var ss=Symbol(`workers-module`);Symbol.dispose||(Symbol.dispose=Symbol.for(`dispose`)),Symbol.asyncDispose||(Symbol.asyncDispose=Symbol.for(`asyncDispose`)),Promise.withResolvers||(Promise.withResolvers=function(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}});var cs=globalThis[ss],ls=cs?cs.RpcTarget:class{},us=async function(){}.constructor,ds=typeof Buffer<`u`?Buffer.prototype:void 0;function fs(e){switch(typeof e){case`boolean`:case`number`:case`string`:return`primitive`;case`undefined`:return`undefined`;case`object`:case`function`:break;case`bigint`:return`bigint`;default:return`unsupported`}if(e===null)return`primitive`;let t=Object.getPrototypeOf(e);switch(t){case Object.prototype:return`object`;case Function.prototype:case us.prototype:return`function`;case Array.prototype:return`array`;case Date.prototype:return`date`;case Uint8Array.prototype:case ds:case ArrayBuffer.prototype:case DataView.prototype:case Int8Array.prototype:case Uint8ClampedArray.prototype:case Int16Array.prototype:case Uint16Array.prototype:case Int32Array.prototype:case Uint32Array.prototype:case BigInt64Array.prototype:case BigUint64Array.prototype:case Float32Array.prototype:case Float64Array.prototype:return`bytes`;case WritableStream.prototype:return`writable`;case ReadableStream.prototype:return`readable`;case URL.prototype:return`url`;case Headers.prototype:return`headers`;case Request.prototype:return`request`;case Response.prototype:return`response`;case Blob.prototype:return`blob`;case ws.prototype:return`stub`;case Ts.prototype:return`rpc-promise`;default:if(cs){if(t==cs.RpcStub.prototype||e instanceof cs.ServiceStub)return`rpc-target`;if(t==cs.RpcPromise.prototype||t==cs.RpcProperty.prototype)return`rpc-thenable`}return e instanceof ls?`rpc-target`:e instanceof Error?`error`:`unsupported`}}function ps(){throw Error(`RPC map() implementation was not loaded.`)}var ms={applyMap:ps,sendMap:ps};function hs(){throw Error(`Stream implementation was not loaded.`)}var gs={createWritableStreamHook:hs,createWritableStreamFromHook:hs,createReadableStreamHook:hs},_s=class{stream(e,t){let n=this.call(e,t),r;try{r=n.pull()}catch(e){throw n.dispose(),e}let i;return r instanceof Promise?i=r.then(e=>{e.dispose()}):(r.dispose(),i=Promise.resolve()),{promise:i}}},vs=class extends _s{error;constructor(e){super(),this.error=e}call(e,t){return t.dispose(),this}map(e,t,n){for(let e of t)e.dispose();return this}get(e){return this}dup(){return this}pull(){return Promise.reject(this.error)}ignoreUnhandledRejections(){}dispose(){}onBroken(e){try{e(this.error)}catch(e){Promise.resolve(e)}}},ys=new vs(Error(`Attempted to use RPC stub after it has been disposed.`)),bs=(e,t,n)=>e.call(t,n);function xs(e,t){let n=bs;bs=e;try{return t()}finally{bs=n}}var Ss=Symbol(`realStub`),Cs={apply(e,t,n){let r=e.raw;return new Ts(bs(r.hook,r.pathIfPromise||[],Ms.fromAppParams(n)),[])},get(e,t,n){let r=e.raw;if(t===Ss)return r;if(t in Ts.prototype)return r[t];if(typeof t==`string`)return new Ts(r.hook,r.pathIfPromise?[...r.pathIfPromise,t]:[t]);if(t===Symbol.dispose&&(!r.pathIfPromise||r.pathIfPromise.length==0))return()=>{r.hook.dispose(),r.hook=ys}},has(e,t){let n=e.raw;return t===Ss?!0:t in Ts.prototype?t in n:typeof t==`string`||t===Symbol.dispose&&(!n.pathIfPromise||n.pathIfPromise.length==0)},construct(e,t){throw Error(`An RPC stub cannot be used as a constructor.`)},defineProperty(e,t,n){throw Error(`Can't define properties on RPC stubs.`)},deleteProperty(e,t){throw Error(`Can't delete properties on RPC stubs.`)},getOwnPropertyDescriptor(e,t){},getPrototypeOf(e){return Object.getPrototypeOf(e.raw)},isExtensible(e){return!1},ownKeys(e){return[]},preventExtensions(e){return!0},set(e,t,n,r){throw Error(`Can't assign properties on RPC stubs.`)},setPrototypeOf(e,t){throw Error(`Can't override prototype of RPC stubs.`)}},ws=class e extends ls{constructor(e,t){if(super(),!(e instanceof _s)){let n=e;if(e=n instanceof ls||n instanceof Function?Ls.create(n,void 0):new Fs(Ms.fromAppReturn(n)),t)throw TypeError(`RpcStub constructor expected one argument, received two.`)}this.hook=e,this.pathIfPromise=t;let n=()=>{};return n.raw=this,new Proxy(n,Cs)}hook;pathIfPromise;dup(){let t=this[Ss];return t.pathIfPromise?new e(t.hook.get(t.pathIfPromise)):new e(t.hook.dup())}onRpcBroken(e){this[Ss].hook.onBroken(e)}map(e){let{hook:t,pathIfPromise:n}=this[Ss];return ms.sendMap(t,n||[],e)}toString(){return`[object RpcStub]`}},Ts=class extends ws{constructor(e,t){if(e instanceof _s)super(e,t??[]);else{if(t!==void 0)throw TypeError(`RpcPromise constructor expected one argument, received two.`);let n=fs(e);if(n===`rpc-promise`){let t=As(e);if(t.pathIfPromise.length>0)super(t.hook,t.pathIfPromise);else{let e=t.hook;t.hook=ys,super(e,[])}}else if(n===`rpc-thenable`)super(Ls.create(e,void 0),[]);else{let t=new Rs(Promise.resolve(e).then(e=>new Fs(Ms.fromAppReturn(e))));t.ignoreUnhandledRejections(),super(t,[])}}}then(e,t){return js(this).then(...arguments)}catch(e){return js(this).catch(...arguments)}finally(e){return js(this).finally(...arguments)}toString(){return`[object RpcPromise]`}};function Es(e){let{hook:t,pathIfPromise:n}=e[Ss];return n&&n.length>0?t.get(n):t}function Ds(e){let{hook:t,pathIfPromise:n}=e[Ss];return n?t.get(n):t.dup()}function Os(e){let{hook:t,pathIfPromise:n}=e[Ss];if(!(n&&n.length>0))return t}function ks(e){return e[Ss].hook}function As(e){return e[Ss]}async function js(e){let{hook:t,pathIfPromise:n}=e[Ss];return n.length>0&&(t=t.get(n)),(await t.pull()).deliverResolve()}var Ms=class e{value;source;hooks;promises;static fromAppParams(t){return new e(t,`params`)}static fromAppReturn(t){return new e(t,`return`)}static fromArray(t){let n=[],r=[],i=[];for(let e of t){e.ensureDeepCopied();for(let t of e.hooks)n.push(t);for(let t of e.promises)t.parent===e&&(t={parent:i,property:i.length,promise:t.promise}),r.push(t);i.push(e.value)}return new e(i,`owned`,n,r)}static forEvaluate(t,n){return new e(null,`owned`,t,n)}static deepCopyFrom(t,n,r){let i=new e(null,`owned`,[],[]);return i.value=i.deepCopy(t,n,`value`,i,!0,r),i}constructor(e,t,n,r){this.value=e,this.source=t,this.hooks=n,this.promises=r}rpcTargets;getHookForRpcTarget(e,t,n=!0){if(this.source===`params`){if(n){let t=e;typeof t.dup==`function`&&(e=t.dup())}return Ls.create(e,t)}if(this.source===`return`){let r=this.rpcTargets?.get(e);return r?n?r.dup():(this.rpcTargets?.delete(e),r):(r=Ls.create(e,t),n?(this.rpcTargets||=new Map,this.rpcTargets.set(e,r),r.dup()):r)}throw Error(`owned payload shouldn't contain raw RpcTargets`)}getHookForWritableStream(e,t,n=!0){if(this.source===`params`)return gs.createWritableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=gs.createWritableStreamHook(e),n?(this.rpcTargets||=new Map,this.rpcTargets.set(e,t),t.dup()):t)}throw Error(`owned payload shouldn't contain raw WritableStreams`)}getHookForReadableStream(e,t,n=!0){if(this.source===`params`)return gs.createReadableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=gs.createReadableStreamHook(e),n?(this.rpcTargets||=new Map,this.rpcTargets.set(e,t),t.dup()):t)}throw Error(`owned payload shouldn't contain raw ReadableStreams`)}deepCopy(e,t,n,r,i,a){switch(fs(e)){case`unsupported`:return e;case`primitive`:case`bigint`:case`date`:case`bytes`:case`blob`:case`url`:case`error`:case`undefined`:return e;case`array`:{let t=e,n=t.length,r=Array(n);for(let e=0;e<n;e++)r[e]=this.deepCopy(t[e],t,e,r,i,a);return r}case`object`:{let t={},n=e;for(let e in n)t[e]=this.deepCopy(n[e],n,e,t,i,a);return t}case`stub`:case`rpc-promise`:{let t=e,a;if(a=i?Ds(t):Es(t),t instanceof Ts){let e=new Ts(a,[]);return this.promises.push({parent:r,property:n,promise:e}),e}return this.hooks.push(a),new ws(a)}case`function`:case`rpc-target`:{let n=e,r;return r=a?a.getHookForRpcTarget(n,t,i):Ls.create(n,t),this.hooks.push(r),new ws(r)}case`rpc-thenable`:{let o=e,s;return s=a?new Ts(a.getHookForRpcTarget(o,t,i),[]):new Ts(Ls.create(o,t),[]),this.promises.push({parent:r,property:n,promise:s}),s}case`writable`:{let n=e,r;return r=a?a.getHookForWritableStream(n,t,i):gs.createWritableStreamHook(n),this.hooks.push(r),n}case`readable`:{let n=e,r;return r=a?a.getHookForReadableStream(n,t,i):gs.createReadableStreamHook(n),this.hooks.push(r),n}case`headers`:return new Headers(e);case`request`:{let t=e;return t.body&&this.deepCopy(t.body,t,`body`,t,i,a),new Request(t)}case`response`:{let t=e;return t.body&&this.deepCopy(t.body,t,`body`,t,i,a),new Response(t.body,t)}default:throw Error(`unreachable`)}}ensureDeepCopied(){if(this.source!==`owned`){let e=this.source===`params`;this.hooks=[],this.promises=[];try{this.value=this.deepCopy(this.value,void 0,`value`,this,e,this)}catch(e){throw this.hooks=void 0,this.promises=void 0,e}if(this.source=`owned`,this.rpcTargets&&this.rpcTargets.size>0)throw Error(`Not all rpcTargets were accounted for in deep-copy?`);this.rpcTargets=void 0}}deliverTo(t,n,r){if(this.ensureDeepCopied(),this.value instanceof Ts)e.deliverRpcPromiseTo(this.value,t,n,r);else{t[n]=this.value;for(let t of this.promises)e.deliverRpcPromiseTo(t.promise,t.parent,t.property,r)}}static deliverRpcPromiseTo(t,n,r,i){let a=Os(t);if(!a)throw Error(`property promises should have been resolved earlier`);let o=a.pull();o instanceof e?o.deliverTo(n,r,i):i.push(o.then(e=>{let t=[];if(e.deliverTo(n,r,t),t.length>0)return Promise.all(t)}))}async deliverCall(t,n){try{let r=[];this.deliverTo(this,`value`,r),r.length>0&&await Promise.all(r);let i=Function.prototype.apply.call(t,n,this.value);return i instanceof Ts?e.fromAppReturn(i):e.fromAppReturn(await i)}finally{this.dispose()}}async deliverStreamWrite(t){try{let n=[];this.deliverTo(this,`value`,n),n.length>0&&await Promise.all(n);let r=this.value[0];return(this.hooks.length>0||this.promises.length>0)&&r instanceof Object?(Symbol.dispose in r||Object.defineProperty(r,Symbol.dispose,{value:()=>this.dispose(),writable:!0,enumerable:!1,configurable:!0}),await t.write(r),e.fromAppReturn(void 0)):(await t.write(r),this.dispose(),e.fromAppReturn(void 0))}catch(e){throw this.dispose(),e}}async deliverResolve(){try{let e=[];this.deliverTo(this,`value`,e),e.length>0&&await Promise.all(e);let t=this.value;return t instanceof Object&&(Symbol.dispose in t||Object.defineProperty(t,Symbol.dispose,{value:()=>this.dispose(),writable:!0,enumerable:!1,configurable:!0})),t}catch(e){throw this.dispose(),e}}dispose(){if(this.source===`owned`)this.hooks.forEach(e=>e.dispose()),this.promises.forEach(e=>e.promise[Symbol.dispose]());else if(this.source===`return`&&(this.disposeImpl(this.value,void 0),this.rpcTargets&&this.rpcTargets.size>0))throw Error(`Not all rpcTargets were accounted for in disposeImpl()?`);this.source=`owned`,this.hooks=[],this.promises=[]}disposeImpl(e,t){switch(fs(e)){case`unsupported`:case`primitive`:case`bigint`:case`bytes`:case`blob`:case`date`:case`url`:case`error`:case`undefined`:return;case`array`:{let t=e,n=t.length;for(let e=0;e<n;e++)this.disposeImpl(t[e],t);return}case`object`:{let t=e;for(let e in t)this.disposeImpl(t[e],t);return}case`stub`:case`rpc-promise`:{let t=Os(e);t&&t.dispose();return}case`function`:case`rpc-target`:{let t=e,n=this.rpcTargets?.get(t);n?(n.dispose(),this.rpcTargets.delete(t)):Is(t);return}case`rpc-thenable`:return;case`headers`:return;case`request`:{let t=e;t.body&&this.disposeImpl(t.body,t);return}case`response`:{let t=e;t.body&&this.disposeImpl(t.body,t);return}case`writable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=gs.createWritableStreamHook(t),n.dispose();return}case`readable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=gs.createReadableStreamHook(t),n.dispose();return}default:return}}ignoreUnhandledRejections(){this.hooks?(this.hooks.forEach(e=>{e.ignoreUnhandledRejections()}),this.promises.forEach(e=>ks(e.promise).ignoreUnhandledRejections())):this.ignoreUnhandledRejectionsImpl(this.value)}ignoreUnhandledRejectionsImpl(e){switch(fs(e)){case`unsupported`:case`primitive`:case`bigint`:case`bytes`:case`blob`:case`date`:case`error`:case`undefined`:case`function`:case`rpc-target`:case`writable`:case`readable`:case`url`:case`headers`:case`request`:case`response`:return;case`array`:{let t=e,n=t.length;for(let e=0;e<n;e++)this.ignoreUnhandledRejectionsImpl(t[e]);return}case`object`:{let t=e;for(let e in t)this.ignoreUnhandledRejectionsImpl(t[e]);return}case`stub`:case`rpc-promise`:ks(e).ignoreUnhandledRejections();return;case`rpc-thenable`:e.then(e=>{},e=>{});return;default:return}}};function Ns(e,t,n,r){for(let i=0;i<n.length;i++){t=e;let a=n[i];if(a in Object.prototype){e=void 0;continue}switch(fs(e)){case`object`:case`function`:e=Object.hasOwn(e,a)?e[a]:void 0;break;case`array`:e=Number.isInteger(a)&&a>=0?e[a]:void 0;break;case`rpc-target`:case`rpc-thenable`:if(Object.hasOwn(e,a))throw TypeError(`Attempted to access property '${a}', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`);e=e[a],r=null;break;case`stub`:case`rpc-promise`:{let{hook:t,pathIfPromise:r}=As(e);return{hook:t,remainingPath:r?r.concat(n.slice(i)):n.slice(i)}}case`writable`:e=void 0;break;case`readable`:e=void 0;break;case`primitive`:case`bigint`:case`bytes`:case`blob`:case`date`:case`error`:case`url`:case`headers`:case`request`:case`response`:e=void 0;break;case`undefined`:e=e[a];break;case`unsupported`:if(i===0)throw TypeError(`RPC stub points at a non-serializable type.`);{let e=n.slice(0,i).join(`.`),t=n.slice(0,i).join(`.`);throw TypeError(`'${e}' is not a serializable type, so property ${t} cannot be accessed.`)}default:throw TypeError(`unreachable`)}}if(e instanceof Ts){let{hook:t,pathIfPromise:n}=As(e);return{hook:t,remainingPath:n||[]}}return{value:e,parent:t,owner:r}}var Ps=class extends _s{call(e,t){let n;try{let{value:t,owner:r}=this.getValue();n=Ns(t,void 0,e,r)}catch(e){return t.dispose(),new vs(e)}return n.hook?n.hook.call(n.remainingPath,t):typeof n.value==`function`?new Rs(t.deliverCall(n.value,n.parent).then(e=>new Fs(e))):(t.dispose(),new vs(TypeError(`'${e.join(`.`)}' is not a function.`)))}map(e,t,n){try{let r;try{let{value:t,owner:n}=this.getValue();r=Ns(t,void 0,e,n)}catch(e){for(let e of t)e.dispose();throw e}return r.hook?r.hook.map(r.remainingPath,t,n):ms.applyMap(r.value,r.parent,r.owner,t,n)}catch(e){return new vs(e)}}get(e){try{let{value:t,owner:n}=this.getValue();if(e.length===0&&n===null){if(t instanceof Object&&`then`in t)return this.dup();throw Error(`Can't dup an RpcTarget stub as a promise.`)}let r=Ns(t,void 0,e,n);return r.hook?r.hook.get(r.remainingPath):new Fs(Ms.deepCopyFrom(r.value,r.parent,r.owner))}catch(e){return new vs(e)}}},Fs=class e extends Ps{constructor(e){super(),this.payload=e}payload;getPayload(){if(this.payload)return this.payload;throw Error(`Attempted to use an RPC StubHook after it was disposed.`)}getValue(){let e=this.getPayload();return{value:e.value,owner:e}}dup(){let t=this.getPayload();return new e(Ms.deepCopyFrom(t.value,void 0,t))}pull(){return this.getPayload()}ignoreUnhandledRejections(){this.payload&&this.payload.ignoreUnhandledRejections()}dispose(){this.payload&&=(this.payload.dispose(),void 0)}onBroken(e){this.payload&&this.payload.value instanceof ws&&this.payload.value.onRpcBroken(e)}};function Is(e){if(Symbol.dispose in e)try{e[Symbol.dispose]()}catch(e){Promise.reject(e)}}var Ls=class e extends Ps{static create(t,n){return typeof t!=`function`&&(n=void 0),new e(t,n)}constructor(e,t,n){super(),this.target=e,this.parent=t,n?n.refcount&&(this.refcount=n.refcount,++this.refcount.count):Symbol.dispose in e&&(this.refcount={count:1})}target;parent;refcount;getTarget(){if(this.target)return this.target;throw Error(`Attempted to use an RPC StubHook after it was disposed.`)}getValue(){return{value:this.getTarget(),owner:null}}dup(){return new e(this.getTarget(),this.parent,this)}pull(){let e=this.getTarget();return`then`in e?Promise.resolve(e).then(e=>Ms.fromAppReturn(e)):Promise.reject(Error(`Tried to resolve a non-promise stub.`))}ignoreUnhandledRejections(){}dispose(){this.target&&=(this.refcount&&--this.refcount.count==0&&Is(this.target),void 0)}onBroken(e){let t=this.target;t&&`then`in t&&Promise.resolve(t).then(()=>{},e)}},Rs=class e extends _s{promise;resolution;constructor(e){super(),this.promise=e.then(e=>(this.resolution=e,e))}call(t,n){return n.ensureDeepCopied(),new e(this.promise.then(e=>e.call(t,n),e=>{throw n.dispose(),e}))}stream(e,t){return t.ensureDeepCopied(),{promise:this.promise.then(n=>n.stream(e,t).promise,e=>{throw t.dispose(),e})}}map(t,n,r){return new e(this.promise.then(e=>e.map(t,n,r),e=>{for(let e of n)e.dispose();throw e}))}get(t){return new e(this.promise.then(e=>e.get(t)))}dup(){return this.resolution?this.resolution.dup():new e(this.promise.then(e=>e.dup()))}pull(){return this.resolution?this.resolution.pull():this.promise.then(e=>e.pull())}ignoreUnhandledRejections(){this.resolution?this.resolution.ignoreUnhandledRejections():this.promise.then(e=>{e.ignoreUnhandledRejections()},e=>{})}dispose(){this.promise.then(e=>e.dispose(),()=>{})}onBroken(e){this.resolution?this.resolution.onBroken(e):this.promise.then(t=>{t.onBroken(e)},e)}},zs={maxBigIntDigits:16384,maxDepth:256,maxMessageSize:33554432},Bs=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,Vs=[`ArrayBuffer`,`DataView`,`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`,`Float32Array`,`Float64Array`];function Hs(e){return Vs.includes(e)}var Us={ArrayBuffer:void 0,DataView:void 0,Int8Array:void 0,Uint8Array:void 0,Uint8ClampedArray:void 0,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,BigInt64Array:8,BigUint64Array:8,Float32Array:4,Float64Array:8},Ws={ArrayBuffer:ArrayBuffer.prototype,DataView:DataView.prototype,Int8Array:Int8Array.prototype,Uint8ClampedArray:Uint8ClampedArray.prototype,Int16Array:Int16Array.prototype,Uint16Array:Uint16Array.prototype,Int32Array:Int32Array.prototype,Uint32Array:Uint32Array.prototype,BigInt64Array:BigInt64Array.prototype,BigUint64Array:BigUint64Array.prototype,Float32Array:Float32Array.prototype,Float64Array:Float64Array.prototype},Gs=new Map;for(let e of Object.keys(Ws))Gs.set(Ws[e],e);function Ks(e,t){if(t!==2&&t!==4&&t!==8)throw RangeError(`Unsupported element size: ${t}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let r=0;r<e.byteLength;r+=t)switch(t){case 2:n.setUint16(r,n.getUint16(r,!1),!0);break;case 4:n.setUint32(r,n.getUint32(r,!1),!0);break;case 8:n.setBigUint64(r,n.getBigUint64(r,!1),!0)}}var qs=new class{exportStub(e){throw Error(`Cannot serialize RPC stubs without an RPC session.`)}exportPromise(e){throw Error(`Cannot serialize RPC stubs without an RPC session.`)}getImport(e){}unexport(e){}createPipe(e){throw Error(`Cannot create pipes without an RPC session.`)}onSendError(e){}};async function Js(e,t){let n=await new Response(e).blob();return n.type===t?n:n.slice(0,n.size,t)}var Ys={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError},Xs=class e{exporter;source;encodingLevel;constructor(e,t,n){this.exporter=e,this.source=t,this.encodingLevel=n}static devaluate(t,n,r=qs,i,a=`string`){let o=new e(r,i,a);try{return o.devaluateImpl(t,n,0)}catch(e){if(o.exports)try{r.unexport(o.exports)}catch{}throw e}}exports;devaluateImpl(e,t,n){if(n>=256)throw Error(`Serialization exceeded maximum allowed depth. (Does the message contain cycles?)`);switch(fs(e)){case`unsupported`:{let t;try{t=`Cannot serialize value: ${e}`}catch{t=`Cannot serialize value: (couldn't stringify value)`}throw TypeError(t)}case`primitive`:return typeof e==`number`&&!isFinite(e)?this.encodingLevel===`structuredClonable`?e:e===1/0?[`inf`]:e===-1/0?[`-inf`]:[`nan`]:e;case`object`:{let t=e,r={};for(let e in t)r[e]=this.devaluateImpl(t[e],t,n+1);return r}case`array`:{let t=e,r=t.length,i=Array(r);for(let e=0;e<r;e++)i[e]=this.devaluateImpl(t[e],t,n+1);return[i]}case`bigint`:return this.encodingLevel===`structuredClonable`?e:[`bigint`,e.toString()];case`date`:{if(this.encodingLevel===`structuredClonable`)return e;let t=e.getTime();return[`date`,Number.isNaN(t)?null:t]}case`bytes`:{let t=Gs.get(Object.getPrototypeOf(e)),n;if(t===`ArrayBuffer`)n=new Uint8Array(e);else if(t===void 0)n=e;else{let r=e;n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);let i=Us[t];!Bs&&i&&(n=n.slice(),Ks(n,i))}if(this.encodingLevel===`structuredClonable`||this.encodingLevel===`jsonCompatibleWithBytes`)return t===void 0?[`bytes`,n]:[`bytes`,n,t];let r;if(n.toBase64)r=n.toBase64({omitPadding:!0});else if(typeof Buffer<`u`)r=(n instanceof Buffer?n:Buffer.from(n.buffer,n.byteOffset,n.byteLength)).toString(`base64`);else{let e=``;for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);r=btoa(e)}return r=r.replace(/=+$/,``),t===void 0?[`bytes`,r]:[`bytes`,r,t]}case`url`:return[`url`,e.href];case`headers`:return[`headers`,[...e]];case`request`:{let t=e,r={};t.method!==`GET`&&(r.method=t.method);let i=[...t.headers];if(i.length>0&&(r.headers=i),t.body)r.body=this.devaluateImpl(t.body,t,n+1),r.duplex=t.duplex||`half`;else if(t.body===void 0&&![`GET`,`HEAD`,`OPTIONS`,`TRACE`,`DELETE`].includes(t.method)){let e=t.arrayBuffer(),n=new ReadableStream({async start(t){try{t.enqueue(new Uint8Array(await e)),t.close()}catch(e){t.error(e)}}}),i=gs.createReadableStreamHook(n);r.body=[`readable`,this.exporter.createPipe(n,i)],r.duplex=t.duplex||`half`}t.cache&&t.cache!=="default"&&(r.cache=t.cache),t.redirect!==`follow`&&(r.redirect=t.redirect),t.integrity&&(r.integrity=t.integrity),t.mode&&t.mode!==`cors`&&(r.mode=t.mode),t.credentials&&t.credentials!==`same-origin`&&(r.credentials=t.credentials),t.referrer&&t.referrer!==`about:client`&&(r.referrer=t.referrer),t.referrerPolicy&&(r.referrerPolicy=t.referrerPolicy),t.keepalive&&(r.keepalive=t.keepalive);let a=t;return a.cf&&(r.cf=a.cf),a.encodeResponseBody&&a.encodeResponseBody!==`automatic`&&(r.encodeResponseBody=a.encodeResponseBody),[`request`,t.url,r]}case`response`:{let t=e,r=this.devaluateImpl(t.body,t,n+1),i={};t.status!==200&&(i.status=t.status),t.statusText&&(i.statusText=t.statusText);let a=[...t.headers];a.length>0&&(i.headers=a);let o=t;if(o.cf&&(i.cf=o.cf),o.encodeBody&&o.encodeBody!==`automatic`&&(i.encodeBody=o.encodeBody),o.webSocket)throw TypeError(`Can't serialize a Response containing a webSocket.`);return[`response`,r,i]}case`blob`:{let t=e,n=t.stream(),r=gs.createReadableStreamHook(n),i=this.exporter.createPipe(n,r);return[`blob`,t.type,[`readable`,i]]}case`error`:{let t=e,r=this.exporter.onSendError(t);r&&(t=r);let i=t,a,o=(e,r)=>{let i=this.exports?.length??0;try{let i=this.devaluateImpl(r,t,n+1);a||={},a[e]=i}catch{if(this.exports&&this.exports.length>i){let e=this.exports.splice(i);try{this.exporter.unexport(e)}catch{}}}};for(let e of Object.keys(t))e!==`name`&&e!==`message`&&e!==`stack`&&o(e,i[e]);`cause`in t&&o(`cause`,i.cause),t instanceof AggregateError&&o(`errors`,t.errors);let s=[`error`,t.name,t.message];return a?(s.push(r&&r.stack?r.stack:null),s.push(a)):r&&r.stack&&s.push(r.stack),s}case`undefined`:return this.encodingLevel===`structuredClonable`?void 0:[`undefined`];case`stub`:case`rpc-promise`:{if(!this.source)throw Error(`Can't serialize RPC stubs in this context.`);let{hook:t,pathIfPromise:n}=As(e),r=this.exporter.getImport(t);return r===void 0?(t=n?t.get(n):t.dup(),this.devaluateHook(n?`promise`:`export`,t)):n?n.length>0?[`pipeline`,r,n]:[`pipeline`,r]:[`import`,r]}case`function`:case`rpc-target`:{if(!this.source)throw Error(`Can't serialize RPC stubs in this context.`);let n=this.source.getHookForRpcTarget(e,t);return this.devaluateHook(`export`,n)}case`rpc-thenable`:{if(!this.source)throw Error(`Can't serialize RPC stubs in this context.`);let n=this.source.getHookForRpcTarget(e,t);return this.devaluateHook(`promise`,n)}case`writable`:{if(!this.source)throw Error(`Can't serialize WritableStream in this context.`);let n=this.source.getHookForWritableStream(e,t);return this.devaluateHook(`writable`,n)}case`readable`:{if(!this.source)throw Error(`Can't serialize ReadableStream in this context.`);let n=e,r=this.source.getHookForReadableStream(n,t);return[`readable`,this.exporter.createPipe(n,r)]}default:throw Error(`unreachable`)}}devaluateHook(e,t){this.exports||=[];let n=e===`promise`?this.exporter.exportPromise(t):this.exporter.exportStub(t);return this.exports.push(n),[e,n]}};new class{importStub(e){throw Error(`Cannot deserialize RPC stubs without an RPC session.`)}importPromise(e){throw Error(`Cannot deserialize RPC stubs without an RPC session.`)}getExport(e){}getPipeReadable(e){throw Error(`Cannot retrieve pipe readable without an RPC session.`)}getLimits(){return zs}};function Zs(e,t){return new Ts(new Rs(new Response(t).arrayBuffer().then(t=>{let n=new Uint8Array(t),r=new Request(e,{body:n});return new Fs(Ms.fromAppReturn(r))})),[])}function Qs(e,t){return new Ts(new Rs(Js(e,t).then(e=>new Fs(Ms.fromAppReturn(e)))),[])}var $s=class e{importer;encodingLevel;limits;constructor(e,t=`string`){this.importer=e,this.encodingLevel=t,this.limits=e.getLimits()}hooks=[];promises=[];evaluate(e){return this.evaluateWithDepth(e,0)}evaluateWithDepth(e,t){let n=Ms.forEvaluate(this.hooks,this.promises);try{return n.value=this.evaluateImpl(e,n,`value`,t),n}catch(e){throw n.dispose(),e}}evaluateCopy(e){return this.evaluate(structuredClone(e))}evaluateImpl(t,n,r,i){let a=this.limits.maxDepth;if(i>=a)throw TypeError(`Deserialization exceeded maximum allowed message depth of ${a}.`);if(this.encodingLevel===`structuredClonable`&&(t instanceof Date||typeof t==`bigint`))return t;if(t instanceof Array){if(t.length==1&&t[0]instanceof Array){let e=t[0];for(let t=0;t<e.length;t++)e[t]=this.evaluateImpl(e[t],e,t,i+1);return e}switch(t[0]){case`bigint`:if(typeof t[1]==`string`){let e=t[1],n=this.limits.maxBigIntDigits;if(e.length>n)throw TypeError(`Deserialized bigint exceeds maximum length of ${n} digits.`);return BigInt(e)}break;case`date`:if(t[1]===null)return new Date(NaN);if(typeof t[1]==`number`)return new Date(t[1]);break;case`bytes`:{let e;if(t[1]instanceof Uint8Array)e=t[1];else if(typeof t[1]==`string`){if(typeof Buffer<`u`)e=Buffer.from(t[1],`base64`);else if(Uint8Array.fromBase64)e=Uint8Array.fromBase64(t[1]);else{let n=atob(t[1]),r=n.length;e=new Uint8Array(r);for(let t=0;t<r;t++)e[t]=n.charCodeAt(t)}}else break;if(t.length===2)return e;if(typeof t[2]!=`string`)throw TypeError(`Unknown bytes type marker type: ${typeof t[2]}`);if(!Hs(t[2])){let e=t[2].slice(0,64);throw TypeError(`Unknown bytes type marker: ${e}`)}let n=t[2],r=Us[n];if(r!==void 0&&e.byteLength%r!==0)throw TypeError(`Invalid byte length ${e.byteLength} for ${n}; expected a multiple of ${r}`);let i=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);switch(!Bs&&r!==void 0&&Ks(new Uint8Array(i),r),n){case`ArrayBuffer`:return i;case`DataView`:return new DataView(i);case`Int8Array`:return new Int8Array(i);case`Uint8Array`:return new Uint8Array(i);case`Uint8ClampedArray`:return new Uint8ClampedArray(i);case`Int16Array`:return new Int16Array(i);case`Uint16Array`:return new Uint16Array(i);case`Int32Array`:return new Int32Array(i);case`Uint32Array`:return new Uint32Array(i);case`BigInt64Array`:return new BigInt64Array(i);case`BigUint64Array`:return new BigUint64Array(i);case`Float32Array`:return new Float32Array(i);case`Float64Array`:return new Float64Array(i)}}case`error`:if(t.length>=3&&typeof t[1]==`string`&&typeof t[2]==`string`){let e=Ys[t[1]]||Error,n=e===AggregateError?new e([],t[2]):new e(t[2]);if(typeof t[3]==`string`&&(n.stack=t[3]),t.length>=5){let e=t[4];if(!e||typeof e!=`object`||Array.isArray(e))break;let r=n,a=e;for(let e of Object.keys(a))if(e!==`name`&&e!==`message`&&e!==`stack`){if(e in Object.prototype||e===`toJSON`){this.evaluateImpl(a[e],n,e,i+1);continue}r[e]=this.evaluateImpl(a[e],n,e,i+1)}}return n}break;case`undefined`:if(t.length===1)return;break;case`inf`:return 1/0;case`-inf`:return-1/0;case`nan`:return NaN;case`url`:if(t.length===2&&typeof t[1]==`string`)return new URL(t[1]);break;case`headers`:if(t.length===2&&t[1]instanceof Array)return new Headers(t[1]);break;case`request`:{if(t.length!==3||typeof t[1]!=`string`)break;let e=t[1],a=t[2];if(typeof a!=`object`||!a)break;if(a.body&&(a.body=this.evaluateImpl(a.body,a,`body`,i+1),!(a.body===null||typeof a.body==`string`||a.body instanceof Uint8Array||a.body instanceof ReadableStream)))throw TypeError(`Request body must be of type ReadableStream.`);if(a.signal&&(a.signal=this.evaluateImpl(a.signal,a,`signal`,i+1),!(a.signal instanceof AbortSignal)))throw TypeError(`Request siganl must be of type AbortSignal.`);if(a.headers&&!(a.headers instanceof Array))throw TypeError(`Request headers must be serialized as an array of pairs.`);let o=new Request(e,a);if(a.body instanceof ReadableStream&&o.body===void 0){let e=Zs(o,a.body);return this.promises.push({promise:e,parent:n,property:r}),e}return o}case`response`:{if(t.length!==3)break;let e=this.evaluateImpl(t[1],n,r,i+1);if(!(e===null||typeof e==`string`||e instanceof Uint8Array||e instanceof ReadableStream))throw TypeError(`Response body must be of type ReadableStream.`);let a=t[2];if(typeof a!=`object`||!a)break;if(a.webSocket)throw TypeError(`Can't deserialize a Response containing a webSocket.`);if(a.headers&&!(a.headers instanceof Array))throw TypeError(`Request headers must be serialized as an array of pairs.`);return new Response(e,a)}case`blob`:{if(t.length!==3||typeof t[1]!=`string`)break;let e=t[1],a=this.evaluateImpl(t[2],n,r,i+1);if(!(a instanceof ReadableStream))throw TypeError(`Blob content must be serialized as a ReadableStream.`);let o=Qs(a,e);return this.promises.push({promise:o,parent:n,property:r}),o}case`import`:case`pipeline`:{if(t.length<2||t.length>4||typeof t[1]!=`number`)break;let a=this.importer.getExport(t[1]);if(!a)throw Error(`no such entry on exports table: ${t[1]}`);let o=t[0]==`pipeline`,s=e=>{if(o){let t=new Ts(e,[]);return this.promises.push({promise:t,parent:n,property:r}),t}return this.hooks.push(e),new Ts(e,[])};if(t.length==2)return s(o?a.get([]):a.dup());let c=t[2];if(!(c instanceof Array)||!c.every(e=>typeof e==`string`||typeof e==`number`))break;if(t.length==3)return s(a.get(c));let l=t[3];if(!(l instanceof Array))break;return l=new e(this.importer).evaluateWithDepth([l],i),s(a.call(c,l))}case`remap`:{if(t.length!==5||typeof t[1]!=`number`||!(t[2]instanceof Array)||!(t[3]instanceof Array)||!(t[4]instanceof Array))break;let e=this.importer.getExport(t[1]);if(!e)throw Error(`no such entry on exports table: ${t[1]}`);let i=t[2];if(!i.every(e=>typeof e==`string`||typeof e==`number`))break;let a=t[3].map(e=>{if(!(e instanceof Array)||e.length!==2||e[0]!==`import`&&e[0]!==`export`||typeof e[1]!=`number`)throw TypeError(`unknown map capture: ${JSON.stringify(e)}`);if(e[0]===`export`)return this.importer.importStub(e[1]);{let t=this.importer.getExport(e[1]);if(!t)throw Error(`no such entry on exports table: ${e[1]}`);return t.dup()}}),o=t[4],s=new Ts(e.map(i,a,o),[]);return this.promises.push({promise:s,parent:n,property:r}),s}case`export`:case`promise`:if(typeof t[1]==`number`){if(t[0]==`promise`){let e=new Ts(this.importer.importPromise(t[1]),[]);return this.promises.push({parent:n,property:r,promise:e}),e}{let e=this.importer.importStub(t[1]);return this.hooks.push(e),new ws(e)}}break;case`writable`:if(typeof t[1]==`number`){let e=this.importer.importStub(t[1]),n=gs.createWritableStreamFromHook(e);return this.hooks.push(e),n}break;case`readable`:if(typeof t[1]==`number`){let e=this.importer.getPipeReadable(t[1]),n=gs.createReadableStreamHook(e);return this.hooks.push(n),e}}throw TypeError(`unknown special value: ${JSON.stringify(t)}`)}if(t instanceof Object){let e=t;for(let t in e)t in Object.prototype||t===`toJSON`?(this.evaluateImpl(e[t],e,t,i+1),delete e[t]):e[t]=this.evaluateImpl(e[t],e,t,i+1);return e}return t}},ec=16,tc=8,nc=16,rc=64;function ic(e){return 2+e.length*3}function ac(e,t,n=0){if(n>=rc)return tc;switch(typeof e){case`string`:return ic(e);case`number`:return 16;case`bigint`:return 16;case`boolean`:return 8;case`undefined`:return 16;case`object`:{if(e===null)return 8;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return nc+e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return nc+e.size;if(e instanceof Date)return 16;if(t??=new WeakSet,t.has(e))return tc;if(t.add(e),e instanceof Array){let r=ec;for(let i of e)r+=tc+ac(i,t,n+1);return r}if(e instanceof Error){let r=ec+ic(e.name)+ic(e.message)+ic(e.stack??``);for(let i of Object.keys(e))r+=tc+ic(i)+ac(e[i],t,n+1);return r}let r=ec;for(let i of Object.keys(e))r+=tc+ic(i)+ac(e[i],t,n+1);return r}default:return 16}}var oc=class{session;importId;constructor(e,t,n){this.session=e,this.importId=t,n&&(this.activePull=Promise.withResolvers())}localRefcount=0;remoteRefcount=1;activePull;resolution;onBrokenRegistrations;resolve(e){if(this.localRefcount==0){e.dispose();return}if(this.resolution=e,this.sendRelease(),this.onBrokenRegistrations){for(let t of this.onBrokenRegistrations){let n=this.session.onBrokenCallbacks[t],r=this.session.onBrokenCallbacks.length;e.onBroken(n),this.session.onBrokenCallbacks[r]===n?delete this.session.onBrokenCallbacks[r]:delete this.session.onBrokenCallbacks[t]}this.onBrokenRegistrations=void 0}this.activePull&&=(this.activePull.resolve(),void 0)}async awaitResolution(){return this.activePull||=(this.session.sendPull(this.importId),Promise.withResolvers()),await this.activePull.promise,this.resolution.pull()}dispose(){this.resolution?this.resolution.dispose():(this.abort(Error(`RPC was canceled because the RpcPromise was disposed.`)),this.sendRelease())}abort(e){if(!this.resolution){if(this.resolution=new vs(e),this.activePull&&=(this.activePull.reject(e),void 0),this.onBrokenRegistrations)for(let e of this.onBrokenRegistrations)delete this.session.onBrokenCallbacks[e];this.onBrokenRegistrations=void 0}}onBroken(e){if(this.resolution)this.resolution.onBroken(e);else{let t=this.session.onBrokenCallbacks.length;this.session.onBrokenCallbacks.push(e),this.onBrokenRegistrations||=[],this.onBrokenRegistrations.push(t)}}sendRelease(){this.remoteRefcount>0&&(this.session.sendRelease(this.importId,this.remoteRefcount),this.remoteRefcount=0)}},sc=class e extends _s{isPromise;entry;constructor(e,t){super(),this.isPromise=e,++t.localRefcount,this.entry=t}collectPath(e){return this}getEntry(){if(this.entry)return this.entry;throw Error(`This RpcImportHook was already disposed.`)}getEntryTakingOwnership(e){try{return this.getEntry()}catch(t){throw e(),t}}call(e,t){let n=this.getEntryTakingOwnership(()=>t.dispose());return n.resolution?n.resolution.call(e,t):n.session.sendCall(n.importId,e,t)}stream(e,t){let n=this.getEntryTakingOwnership(()=>t.dispose());return n.resolution?n.resolution.stream(e,t):n.session.sendStream(n.importId,e,t)}map(e,t,n){let r=this.getEntryTakingOwnership(()=>{for(let e of t)e.dispose()});return r.resolution?r.resolution.map(e,t,n):r.session.sendMap(r.importId,e,t,n)}get(e){let t=this.getEntry();return t.resolution?t.resolution.get(e):t.session.sendCall(t.importId,e)}dup(){return new e(!1,this.getEntry())}pull(){let e=this.getEntry();if(!this.isPromise)throw Error(`Can't pull this hook because it's not a promise hook.`);return e.resolution?e.resolution.pull():e.awaitResolution()}ignoreUnhandledRejections(){}dispose(){let e=this.entry;this.entry=void 0,e&&--e.localRefcount===0&&e.dispose()}onBroken(e){this.entry&&this.entry.onBroken(e)}},cc=class extends sc{session;constructor(e){super(!1,e),this.session=e.session}dispose(){if(this.session){let e=this.session;this.session=void 0,e.shutdown()}}},lc=class{transport;options;exports=[];reverseExports=new Map;imports=[];abortReason;cancelReadLoop;nextExportId=-1;onBatchDone;pullCount=0;onBrokenCallbacks=[];encodingLevel;limits;constructor(e,t,n){this.transport=e,this.options=n;let r=`string`;if(`encodingLevel`in e){let t=e.encodingLevel;if(t!==void 0){if(t!==`string`&&t!==`jsonCompatible`&&t!==`jsonCompatibleWithBytes`&&t!==`structuredClonable`)throw TypeError(`Unknown transport encodingLevel: ${String(t)}`);r=t}}this.encodingLevel=r,this.limits={...zs,...n.limits},this.exports.push({hook:t,refcount:1}),this.imports.push(new oc(this,0,!1)),this.readLoop().catch(e=>this.abort(e))}getMainImport(){return new cc(this.imports[0])}shutdown(){this.abort(Error(`RPC session was shut down by disposing the main stub`),!1)}exportStub(e){if(this.abortReason)throw this.abortReason;let t=this.reverseExports.get(e);if(t!==void 0)return++this.exports[t].refcount,t;{let t=this.nextExportId--;return this.exports[t]={hook:e,refcount:1},this.reverseExports.set(e,t),this.watchExport(t,e),t}}exportPromise(e){if(this.abortReason)throw this.abortReason;let t=this.nextExportId--;return this.exports[t]={hook:e,refcount:1},this.reverseExports.set(e,t),this.ensureResolvingExport(t),t}unexport(e){for(let t of e)this.releaseExport(t,1)}watchExport(e,t){t.onBroken(n=>{queueMicrotask(()=>{if(this.abortReason===void 0&&this.exports[e]?.hook===t)try{this.send([`reject`,e,Xs.devaluate(n,void 0,this,void 0,this.encodingLevel)])}catch(e){this.abort(e)}})})}releaseExport(e,t){let n=this.exports[e];if(!n)throw Error(`no such export ID: ${e}`);if(n.refcount<t)throw Error(`refcount would go negative: ${n.refcount} < ${t}`);n.refcount-=t,n.refcount===0&&(delete this.exports[e],this.reverseExports.delete(n.hook),n.hook.dispose())}onSendError(e){if(this.options.onSendError)return this.options.onSendError(e)}ensureResolvingExport(e){let t=this.exports[e];if(!t)throw Error(`no such export ID: ${e}`);if(!t.pull){let n=async()=>{let e=t.hook;for(;;){let t=await e.pull();if(t.value instanceof ws){let{hook:n,pathIfPromise:r}=As(t.value);if(r&&r.length==0&&this.getImport(e)===void 0){e=n;continue}}return t}},r=t.autoRelease;++this.pullCount,t.pull=n().then(t=>{let n=Xs.devaluate(t.value,void 0,this,t,this.encodingLevel);this.send([`resolve`,e,n]),r&&this.releaseExport(e,1)},t=>{this.send([`reject`,e,Xs.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}).catch(t=>{try{this.send([`reject`,e,Xs.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}catch(e){this.abort(e)}}).finally(()=>{--this.pullCount===0&&this.onBatchDone&&this.onBatchDone.resolve()})}}getImport(e){if(e instanceof sc&&e.entry&&e.entry.session===this)return e.entry.importId}importStub(e){if(this.abortReason)throw this.abortReason;let t=this.imports[e];return t||(t=new oc(this,e,!1),this.imports[e]=t),new sc(!1,t)}importPromise(e){if(this.abortReason)throw this.abortReason;if(this.imports[e])return new vs(Error(`Bug in RPC system: The peer sent a promise reusing an existing export ID.`));let t=new oc(this,e,!0);return this.imports[e]=t,new sc(!0,t)}getExport(e){return this.exports[e]?.hook}getPipeReadable(e){let t=this.exports[e];if(!t||!t.pipeReadable)throw Error(`Export ${e} is not a pipe or its readable end was already consumed.`);let n=t.pipeReadable;return t.pipeReadable=void 0,n}getLimits(){return this.limits}createPipe(e,t){if(this.abortReason)throw this.abortReason;this.send([`pipe`]);let n=this.imports.length,r=new oc(this,n,!1);this.imports.push(r);let i=new sc(!1,r),a=gs.createWritableStreamFromHook(i);return e.pipeTo(a).catch(()=>{}).finally(()=>t.dispose()),n}send(e){if(this.abortReason!==void 0)return 0;if(this.encodingLevel===`string`){let t;try{t=JSON.stringify(e)}catch(e){try{this.abort(e)}catch{}throw e}try{let e=this.transport.send(t);e!==void 0&&typeof e.catch==`function`&&e.catch(e=>this.abort(e,!1))}catch(e){queueMicrotask(()=>this.abort(e,!1))}return t.length}try{let t=this.transport.send(e);if(typeof t==`number`)return t;let n=t;n&&typeof n.then==`function`&&Promise.resolve(n).catch(e=>this.abort(e,!1));return}catch(e){queueMicrotask(()=>this.abort(e,!1));return}}sendCall(e,t,n){if(this.abortReason)throw n?.dispose(),this.abortReason;let r=[`pipeline`,e,t];if(n){let e;try{e=Xs.devaluate(n.value,void 0,this,n,this.encodingLevel)}catch(e){throw n.dispose(),e}r.push(e[0])}this.send([`push`,r]);let i=new oc(this,this.imports.length,!1);return this.imports.push(i),new sc(!0,i)}sendStream(e,t,n){if(this.abortReason)throw n.dispose(),this.abortReason;let r=[`pipeline`,e,t],i;try{i=Xs.devaluate(n.value,void 0,this,n,this.encodingLevel)}catch(e){throw n.dispose(),e}r.push(i[0]);let a=[`stream`,r],o=this.send(a);o===void 0&&(o=ac(a));let s=this.imports.length,c=new oc(this,s,!0);return c.remoteRefcount=0,c.localRefcount=1,this.imports.push(c),{promise:c.awaitResolution().then(e=>{e.dispose(),delete this.imports[s]},e=>{throw delete this.imports[s],e}),size:o}}sendMap(e,t,n,r){if(this.abortReason){for(let e of n)e.dispose();throw this.abortReason}let i=[`remap`,e,t,n.map(e=>{let t=this.getImport(e);return t===void 0?[`export`,this.exportStub(e)]:[`import`,t]}),r];this.send([`push`,i]);let a=new oc(this,this.imports.length,!1);return this.imports.push(a),new sc(!0,a)}sendPull(e){if(this.abortReason)throw this.abortReason;this.send([`pull`,e])}sendRelease(e,t){this.abortReason||(this.send([`release`,e,t]),delete this.imports[e])}abort(e,t=!0){if(this.abortReason===void 0){if(this.cancelReadLoop?.(e),this.cancelReadLoop=void 0,t)try{let t=[`abort`,Xs.devaluate(e,void 0,this,void 0,this.encodingLevel)];if(this.encodingLevel===`string`){let e=this.transport.send(JSON.stringify(t));e!==void 0&&typeof e.catch==`function`&&e.catch(e=>{})}else{let e=this.transport.send(t);e&&typeof e.then==`function`&&Promise.resolve(e).catch(e=>{})}}catch{}if(e===void 0&&(e=`undefined`),this.abortReason=e,this.onBatchDone&&this.onBatchDone.reject(e),this.transport.abort)try{this.transport.abort(e)}catch(e){Promise.resolve(e)}for(let t of Object.values(this.onBrokenCallbacks))try{t(e)}catch(e){Promise.resolve(e)}for(let t in this.imports)this.imports[t].abort(e);for(let e in this.exports)this.exports[e].hook.dispose()}}async readLoop(){for(;!this.abortReason;){let e=Promise.withResolvers();this.cancelReadLoop=e.reject;let t;try{t=await Promise.race([this.transport.receive(),e.promise])}finally{this.cancelReadLoop===e.reject&&(this.cancelReadLoop=void 0)}if(this.encodingLevel===`string`&&t.length>this.limits.maxMessageSize)throw TypeError(`Incoming message exceeds maximum size of ${this.limits.maxMessageSize} UTF-16 code units.`);if(this.abortReason)break;let n=this.encodingLevel===`string`?JSON.parse(t):t;if(n instanceof Array)switch(n[0]){case`push`:if(n.length>1){let e=new Fs(new $s(this,this.encodingLevel).evaluate(n[1]));e.ignoreUnhandledRejections(),this.exports.push({hook:e,refcount:1});continue}break;case`stream`:if(n.length>1){let e=new Fs(new $s(this,this.encodingLevel).evaluate(n[1]));e.ignoreUnhandledRejections();let t=this.exports.length;this.exports.push({hook:e,refcount:1,autoRelease:!0}),this.ensureResolvingExport(t);continue}break;case`pipe`:{let{readable:e,writable:t}=new TransformStream,n=gs.createWritableStreamHook(t),r=this.exports.length;this.exports.push({hook:n,refcount:1,pipeReadable:e}),this.watchExport(r,n);continue}case`pull`:{let e=n[1];if(typeof e==`number`){this.ensureResolvingExport(e);continue}break}case`resolve`:case`reject`:{let e=n[1];if(typeof e==`number`&&n.length>2){let t=this.imports[e];if(t){if(n[0]==`resolve`)t.resolve(new Fs(new $s(this,this.encodingLevel).evaluate(n[2])));else{let e=new $s(this,this.encodingLevel).evaluate(n[2]);e.dispose(),t.resolve(new vs(e.value))}}else n[0]==`resolve`&&new $s(this,this.encodingLevel).evaluate(n[2]).dispose();continue}break}case`release`:{let e=n[1],t=n[2];if(typeof e==`number`&&typeof t==`number`){this.releaseExport(e,t);continue}break}case`abort`:{let e=new $s(this,this.encodingLevel).evaluate(n[1]);e.dispose(),this.abort(e.value,!1);break}}throw Error(`bad RPC message: ${JSON.stringify(n)}`)}}async drain(){if(this.abortReason)throw this.abortReason;if(this.pullCount>0){let{promise:e,resolve:t,reject:n}=Promise.withResolvers();this.onBatchDone={resolve:t,reject:n},await e}}getStats(){let e={imports:0,exports:0};for(let t in this.imports)++e.imports;for(let t in this.exports)++e.exports;return e}},uc=class{#e;#t;constructor(e,t,n={}){let r;r=t?new Fs(Ms.fromAppReturn(t)):new vs(Error(`This connection has no main object.`)),this.#e=new lc(e,r,n),this.#t=new ws(this.#e.getMainImport())}getRemoteMain(){return this.#t}getStats(){return this.#e.getStats()}drain(){return this.#e.drain()}};function dc(e,t,n){return new uc(new fc(e),t,n).getRemoteMain()}var fc=class{encodingLevel=`structuredClonable`;constructor(e){this.#e=e,e.start(),e.addEventListener(`message`,e=>{this.#i||(e.data===null?this.#a(Error(`Peer closed MessagePort connection.`)):this.#t?(this.#t(e.data),this.#t=void 0,this.#n=void 0):this.#r.push(e.data))}),e.addEventListener(`messageerror`,e=>{this.#a(Error(`MessagePort message error.`))})}#e;#t;#n;#r=[];#i;send(e){if(this.#i)throw this.#i;this.#e.postMessage(e)}async receive(){if(this.#r.length>0)return this.#r.shift();if(this.#i)throw this.#i;return new Promise((e,t)=>{this.#t=e,this.#n=t})}abort(e){try{this.#e.postMessage(null)}catch{}this.#e.close(),this.#i||=e}#a(e){this.#i||(this.#i=e,this.#n&&=(this.#n(e),this.#t=void 0,void 0))}},pc,mc=class{context;captureMap=new Map;instructions=[];constructor(e,t){this.context=pc?{parent:pc,captures:[],subject:pc.capture(e),path:t}:{parent:void 0,captures:[],subject:e,path:t},pc=this}unregister(){pc=this.context.parent}makeInput(){return new gc(this,0)}makeOutput(e){let t;try{t=Xs.devaluate(e.value,void 0,this,e)}finally{e.dispose()}return this.instructions.push(t),this.context.parent?(this.context.parent.instructions.push([`remap`,this.context.subject,this.context.path,this.context.captures.map(e=>[`import`,e]),this.instructions]),new gc(this.context.parent,this.context.parent.instructions.length)):this.context.subject.map(this.context.path,this.context.captures,this.instructions)}pushCall(e,t,n){let r=Xs.devaluate(n.value,void 0,this,n);r=r[0];let i=this.capture(e.dup());return this.instructions.push([`pipeline`,i,t,r]),new gc(this,this.instructions.length)}pushGet(e,t){let n=this.capture(e.dup());return this.instructions.push([`pipeline`,n,t]),new gc(this,this.instructions.length)}capture(e){if(e instanceof gc&&e.mapper===this)return e.idx;let t=this.captureMap.get(e);if(t===void 0){if(this.context.parent){let t=this.context.parent.capture(e);this.context.captures.push(t)}else this.context.captures.push(e);t=-this.context.captures.length,this.captureMap.set(e,t)}return t}exportStub(e){throw Error(`Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback.`)}exportPromise(e){return this.exportStub(e)}getImport(e){return this.capture(e)}unexport(e){}createPipe(e){throw Error(`Cannot send ReadableStream inside a mapper function.`)}onSendError(e){}};ms.sendMap=(e,t,n)=>{let r=new mc(e,t),i;try{i=Ms.fromAppReturn(xs(r.pushCall.bind(r),()=>n(new Ts(r.makeInput(),[]))))}finally{r.unregister()}if(i instanceof Promise)throw i.catch(e=>{}),Error(`RPC map() callbacks cannot be async.`);return new Ts(r.makeOutput(i),[])};function hc(){throw Error(`Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.`)}var gc=class extends _s{mapper;idx;constructor(e,t){super(),this.mapper=e,this.idx=t}dup(){return this}dispose(){}get(e){if(e.length==0)return this;if(pc)return pc.pushGet(this,e);hc()}call(e,t){t.dispose(),hc()}map(e,t,n){for(let e of t)e.dispose();hc()}pull(){hc()}ignoreUnhandledRejections(){}onBroken(e){hc()}},_c=class{captures;variables;constructor(e,t){this.captures=e,this.variables=[t]}dispose(){for(let e of this.variables)e.dispose()}apply(e){try{if(e.length<1)throw Error(`Invalid empty mapper function.`);for(let t of e.slice(0,-1)){let e=new $s(this).evaluateCopy(t);if(e.value instanceof ws){let t=Os(e.value);if(t){this.variables.push(t);continue}}this.variables.push(new Fs(e))}return new $s(this).evaluateCopy(e[e.length-1])}finally{for(let e of this.variables)e.dispose()}}importStub(e){throw Error(`A mapper function cannot refer to exports.`)}importPromise(e){return this.importStub(e)}getExport(e){return e<0?this.captures[-e-1]:this.variables[e]}getPipeReadable(e){throw Error(`A mapper function cannot use pipe readables.`)}getLimits(){return zs}};function vc(e,t,n,r,i){let a=new _c(r,new Fs(Ms.deepCopyFrom(e,t,n)));try{return a.apply(i)}finally{a.dispose()}}ms.applyMap=(e,t,n,r,i)=>{try{let a;if(e instanceof Ts)throw Error(`applyMap() can't be called on RpcPromise`);if(e instanceof Array){let t=[];try{for(let a of e)t.push(vc(a,e,n,r,i))}catch(e){for(let e of t)e.dispose();throw e}a=Ms.fromArray(t)}else a=e==null?Ms.fromAppReturn(e):vc(e,t,n,r,i);return new Fs(a)}finally{for(let e of r)e.dispose()}};var yc=class e extends _s{state;static create(t){let n=t.getWriter();return new e({refcount:1,writer:n,closed:!1})}constructor(e,t){super(),this.state=e,t&&++e.refcount}getState(){if(this.state)return this.state;throw Error(`Attempted to use a WritableStreamStubHook after it was disposed.`)}call(e,t){try{let n=this.getState();if(e.length!==1||typeof e[0]!=`string`)throw Error(`WritableStream stub only supports direct method calls`);let r=e[0];if(r!==`write`&&r!==`close`&&r!==`abort`)throw Error(`Unknown WritableStream method: ${r}`);return(r===`close`||r===`abort`)&&(n.closed=!0),new Rs((r===`write`?t.deliverStreamWrite(n.writer):t.deliverCall(n.writer[r],n.writer)).then(e=>new Fs(e)))}catch(e){return t.dispose(),new vs(e)}}map(e,t,n){for(let e of t)e.dispose();return new vs(Error(`Cannot use map() on a WritableStream`))}get(e){return new vs(Error(`Cannot access properties on a WritableStream stub`))}dup(){let t=this.getState();return new e(t,this)}pull(){return Promise.reject(Error(`Cannot pull a WritableStream stub`))}ignoreUnhandledRejections(){}dispose(){let e=this.state;this.state=void 0,e&&--e.refcount===0&&(e.closed||e.writer.abort(Error(`WritableStream RPC stub was disposed without calling close()`)).catch(()=>{}),e.writer.releaseLock())}onBroken(e){this.getState().writer.closed.then(void 0,e)}},bc=262144,xc=1073741824,Sc=65536,Cc=2,wc=1.25,Tc=.9,Ec=3,Dc=class{now;window=bc;bytesInFlight=0;inStartupPhase=!0;delivered=0;deliveredTime=0;firstAckTime=0;firstAckDelivered=0;minRtt=1/0;roundsWithoutIncrease=0;lastRoundWindow=0;roundStartTime=0;constructor(e){this.now=e}onSend(e){this.bytesInFlight+=e;let t={sentTime:this.now(),size:e,deliveredAtSend:this.delivered,deliveredTimeAtSend:this.deliveredTime,windowAtSend:this.window,windowFullAtSend:this.bytesInFlight>=this.window};return{token:t,shouldBlock:t.windowFullAtSend}}onError(e){this.bytesInFlight-=e.size}onAck(e){let t=this.now();this.delivered+=e.size,this.deliveredTime=t,this.bytesInFlight-=e.size;let n=t-e.sentTime;if(this.minRtt=Math.min(this.minRtt,n),this.firstAckTime===0)this.firstAckTime=t,this.firstAckDelivered=this.delivered;else{let n,r;e.deliveredTimeAtSend===0?(n=this.firstAckTime,r=this.firstAckDelivered):(n=e.deliveredTimeAtSend,r=e.deliveredAtSend);let i=t-n,a=(this.delivered-r)/i,o=this.inStartupPhase?Cc:wc,s=a*this.minRtt*o;s=Math.min(s,e.windowAtSend*o),s=e.windowFullAtSend?Math.max(s,e.windowAtSend*Tc):Math.max(s,this.window),this.window=Math.max(Math.min(s,xc),Sc),this.inStartupPhase&&e.sentTime>=this.roundStartTime&&(this.window>this.lastRoundWindow*wc?this.roundsWithoutIncrease=0:++this.roundsWithoutIncrease>=Ec&&(this.inStartupPhase=!1),this.roundStartTime=t,this.lastRoundWindow=this.window)}return this.bytesInFlight<this.window}};function Oc(e){let t,n=!1,r=new Dc(()=>performance.now()),i,a,o=()=>{n||(n=!0,e.dispose())};return new WritableStream({start(n){e.onBroken(e=>{t===void 0&&(t=e,n.error(e),o()),a&&=(a(e),i=void 0,void 0)})},write(n,s){if(t!==void 0)throw t;let c=Ms.fromAppParams([n]),{promise:l,size:u}=e.stream([`write`],c);if(u===void 0)return l.catch(e=>{throw t===void 0&&(t=e),e});{let{token:e,shouldBlock:n}=r.onSend(u);if(l.then(()=>{r.onAck(e)&&i&&(i(),i=void 0,a=void 0)},n=>{r.onError(e),t===void 0&&(t=n,s.error(n),o()),a&&=(a(n),i=void 0,void 0)}),n)return new Promise((e,t)=>{i=e,a=t})}},async close(){if(t!==void 0)throw o(),t;let{promise:n}=e.stream([`close`],Ms.fromAppParams([]));try{await n}catch(e){throw t??e}finally{o()}},abort(n){if(t!==void 0)return;t=n??Error(`WritableStream was aborted`),a&&=(a(t),i=void 0,void 0);let{promise:r}=e.stream([`abort`],Ms.fromAppParams([n]));r.then(()=>o(),()=>o())}})}var kc=class e extends _s{state;static create(t){return new e({refcount:1,stream:t,canceled:!1})}constructor(e,t){super(),this.state=e,t&&++e.refcount}call(e,t){return t.dispose(),new vs(Error(`Cannot call methods on a ReadableStream stub`))}map(e,t,n){for(let e of t)e.dispose();return new vs(Error(`Cannot use map() on a ReadableStream`))}get(e){return new vs(Error(`Cannot access properties on a ReadableStream stub`))}dup(){let t=this.state;if(!t)throw Error(`Attempted to dup a ReadableStreamStubHook after it was disposed.`);return new e(t,this)}pull(){return Promise.reject(Error(`Cannot pull a ReadableStream stub`))}ignoreUnhandledRejections(){}dispose(){let e=this.state;this.state=void 0,e&&--e.refcount===0&&(e.canceled||(e.canceled=!0,e.stream.locked||e.stream.cancel(Error(`ReadableStream RPC stub was disposed without being consumed`)).catch(()=>{})))}onBroken(e){}};gs.createWritableStreamHook=yc.create,gs.createWritableStreamFromHook=Oc,gs.createReadableStreamHook=kc.create;var Ac=ws,jc=ls,Mc=dc;function Nc(e){return e<32||e>=127&&e<=159||e===1564||e>=8203&&e<=8207||e===8232||e===8233||e>=8234&&e<=8238||e>=8294&&e<=8297||e===65279}function Pc(e,t){let n=e.find(e=>e.id===t.itemId);if(n===void 0||n.kind===`text`)return!1;if(n.kind===`menu`){let e=n.options.find(e=>e.id===t.optionId);return e!==void 0&&e.disabled!==!0}return t.optionId===void 0?n.kind!==`button`||n.disabled!==!0:!1}Object.freeze({publish:()=>Promise.resolve(),onBack:()=>()=>void 0,onForward:()=>()=>void 0,onActivate:()=>()=>void 0});function Fc(e,t){if(t.kind===`action`){let n=[...e.primary??[],...e.menu??[]].find(e=>e.id===t.actionId);return n!==void 0&&n.disabled!==!0}let n=e.crumbs?.find(e=>e.id===t.crumbId);return n===void 0?!1:t.siblingId===void 0||n.siblings?.some(e=>e.id===t.siblingId)===!0}function Ic(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid keymap token: token cannot be empty`);return t}function Lc(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid key name: key name cannot be empty`);return t}function Rc(e){return{name:Lc(e.name),ctrl:e.ctrl??!1,shift:e.shift??!1,meta:e.meta??!1,super:e.super??!1,hyper:e.hyper||void 0}}function zc(e){return{name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super,hyper:e.hyper||void 0}}function Bc(e,t){let n=zc(Rc(e));return{stroke:n,display:t?.display??Jc(n),match:t?.match??Wc(n),tokenName:t?.tokenName?Ic(t.tokenName):void 0}}function Vc(e){return{stroke:zc(e.stroke),display:e.display,match:e.match,tokenName:e.tokenName,patternName:e.patternName,payloadKey:e.payloadKey}}function Hc(e){return e.map(e=>Vc(e))}function Uc(e){return`match`in e?e.match:`stroke`in e?Wc(e.stroke):Wc(e)}function Wc(e){return`key:${Yc(Rc(e))}`}function Gc(e){let t=e.trim();if(!t)throw Error(`Invalid keymap match id: id cannot be empty`);return`text:${t}`}function Kc(e,t){return`stroke`in e?t?.preferDisplay&&e.display?e.display:Jc(e.stroke):Jc(Rc(e))}function qc(e,t){return e.map(e=>Kc(e,t)).join(t?.separator??``)}function Jc(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 Yc(e){return`${e.name}:${+!!e.ctrl}:${+!!e.shift}:${+!!e.meta}:${+!!e.super}:${+!!e.hyper}`}var Xc=Symbol(`keymap-extension-context`);function Zc(e){return e.isDestroyed?null:e.getFocusedTarget()}function Qc(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 $c(e,t){let n=new Set;return Qc(e,t,e=>{n.add(e)}),n}function el(e,t,n){let r=[],i=$c(t,n),a=Array.isArray(e)?e:tl(e);for(let e of a)nl(t,e,n,i)&&r.push(e);return r}function tl(e){return[...e].sort((e,t)=>t.priority-e.priority||t.order-e.order)}function nl(e,t,n,r=$c(e,n)){let i=t.target;return i?e.isTargetDestroyed(i)?!1:t.targetMode===`focus`?i===n:r.has(i):!0}function rl(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 il(e,t,n=!0){let r=e.binding.sequence[e.index];if(!r?.patternName)return!0;let i=t.get(r.patternName);return i?rl(e)>=i.min:n}function al(e,t,n=!0){let r=e.binding.sequence[e.index];if(r?.patternName){let n=t.get(r.patternName);if(n&&rl(e)<n.max)return!0}return il(e,t,n)&&e.index+1<e.binding.sequence.length}function ol(e,t){return e.index===e.binding.sequence.length-1&&il(e,t,!1)}function sl(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 cl(e,t){let n=sl(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=sl(e,n.stroke,n.match,r),e.patternChildren.push(i))}else i=e.children.get(n.match),i||(i=sl(e,n.stroke,n.match),e.children.set(n.match,i));i.reachableBindings.push(r),e=i}e.bindings.push(r)}return n}function ll(e,t){let n=[];for(let r of e){if(!il(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 ul(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 dl(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 fl(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 ul({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 pl(e,t,n,r,i,a){let o=e.binding.sequence[e.index];if(o?.patternName){let s=r.get(o.patternName);if(s&&rl(e)<s.max){let t=i(s.name,n);if(t){let r=a(n,s.name,t);return ul(e,e.index,r,t.value??n.name)}}return il(e,r,!1)?fl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a):void 0}return fl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a)}function ml(e,t,n,r,i){let a=[],o=1/0;for(let s of e.bindings){if(s.event!==`press`)continue;let c=fl(e,s,0,[],void 0,t,n,r,i);if(!c)continue;let l=dl(c,t);l<o&&(o=l,a.length=0),l===o&&a.push(c)}return a}import.meta.require;function hl(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 gl(){let e=[];return{get:()=>e,set:t=>{e=t},remove(t){e=e.filter(e=>e!==t)},has:()=>e.length>0,clear:()=>{e=[]}}}function _l(){let e=gl();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 vl(){let e=gl(),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 yl(e){return typeof e==`string`||!!e&&typeof e==`object`&&!Array.isArray(e)}function bl(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(!yl(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 xl(e){let t=bl(e);if(!t.ok)throw Error(t.reason);return e.map(e=>({...e,key:typeof e.key==`string`?e.key:{...e.key}}))}function Sl(e){return{...e,sequence:Hc(e.sequence)}}function Cl(e,t){let n=_l();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=wl(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 wl(e){return e.map(t=>({sequence:Hc(t.sequence),command:t.command,attrs:t.attrs,event:t.event,preventDefault:t.preventDefault,fallthrough:t.fallthrough,parsedBinding:Sl(t.parsedBinding),sourceTarget:t.sourceTarget,sourceLayerOrder:t.sourceLayerOrder,bindingIndex:t.bindingIndex,hasCommandAtSequence:e.some(e=>e.event===`press`&&e.command!==void 0&&Tl(e,t)),hasContinuations:e.some(e=>e.event===`press`&&El(t,e))}))}function Tl(e,t){return e.sequence.length===t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function El(e,t){return e.sequence.length<t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function Dl(){return{version:-1,notifyVersion:-1,focused:void 0,value:[],targets:new WeakMap}}function Ol(){return{plain:Dl(),bindings:Dl(),metadata:Dl(),bindingsAndMetadata:Dl()}}function kl(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 Al(e,t,n){let r=n?e.targets.get(n):e.nullTarget;return r?.version===t?r:void 0}function jl(e,t,n,r){let i={version:t,value:r};n?e.targets.set(n,i):e.nullTarget=i}function Ml(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 Nl(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 Pl(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=Kc(i.stroke)),c&&(o=void 0),n.push(Bc(i.stroke,{display:a,match:i.match,tokenName:o}))}return n}function Fl(e){if(e.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);return e}function Il(e,t,n,r,i,a,o={}){let s=Ol(),c=-1,l=[],u=()=>Fl(t).getFocusedTarget(),d=()=>Zc(t),f=t=>{let n=e.pending;Ml(n,t)||(e.pending=t,o.onPendingSequenceChanged?.(n,t),se(),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)&&al(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?Pl(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=Nl(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=kl(s,t);return i.notifyVersion===e.derivedVersion?i.value:y(i,n,r)},y=(n,r,i)=>{t.isDestroyed&&Fl(t);let o=u(),s=Al(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?ne(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,jl(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 ne(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?ne(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=el(e.sortedLayers,t,n),e.activeLayersCache),C=(e,n)=>nl(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?Kc(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 re(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=ee(o,r,i,a);if(!s)continue;let c=t.get(e);c?ae(c,s,r):t.set(e,L(o.stroke,s,r)),s.stop&&n.add(e)}},ee=(e,t,n,r)=>{if(!(e.children.size>0||e.patternChildren.length>0)){let i=ie(te(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=ie(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}},te=t=>{if(e.commandResolvers.has())return!0;for(let e of t.bindings)if(e.matchers.length>0)return!0;return!1},ne=(t,n,r,i,a)=>{let o=new Map,s=new Set;return N(ll(t,e.patterns),o,s,n,i,a),re(o,n,r,i,a)},N=(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=F(e,t,i,a,o);if(!c)return;let l=n.get(s);l?ae(l,c,i):n.set(s,L(e.part.stroke,c,i)),c.stop&&r.add(s)},re=(e,t,n,r,i)=>{let a=[];for(let o of e.values()){let e=oe(o,t,n,r,i);e&&a.push(e)}return a},F=(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=ie(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?Kc(a.stroke):``),i&&(n=void 0),{display:t,tokenName:n}},ie=(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}},L=(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}),ae=(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)}},oe=(e,t,n,r,i)=>{if(!e.commandBinding&&!e.continues)return;let o={stroke:zc(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},se=()=>{n.has(`pendingSequence`)&&n.emit(`pendingSequence`,e.pending?Pl(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:Pl,collectMatchingBindings:E,collectActiveBindings:A}}var Ll=new Set([`name`,`run`,`fields`,`attrs`,`rejectedResult`]),Rl=new Set([`key`,`cmd`,`event`,`preventDefault`,`fallthrough`]),zl=new Set([`target`,`targetMode`,`priority`,`bindings`,`commands`]);function Bl(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 Vl(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 Hl(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function Ul(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),Hl(n,e.command.name,i)}return{entries:t,chainsByName:n}}function Wl(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),Hl(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 Gl(e,t,n,r){return(e.activeLayersCacheVersion!==e.cacheVersion||e.activeLayersCacheFocused!==r)&&(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=r,e.activeLayersCache=el(e.sortedLayers,t,r)),Wl(e.activeLayersCache,n,!0)}function Kl(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 ql(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 Jl(e){let t=`field ${e.fieldName}`;return{require(n,r){Kl(e.requirements,n,r,t)},attr(n,r){if(!e.attrs)throw Error(`Keymap ${t} cannot publish attrs`);ql(e.attrs,n,r,t)},activeWhen(n){e.matchers.push(e.conditions.buildRuntimeMatcher(n,t))}}}function Yl(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Xl(e,t){return e instanceof Error&&e.message?e.message:t}function Zl(e){return!e||typeof e!=`object`&&typeof e!=`function`?!1:typeof e.then==`function`}function Ql(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=>Ql(e,t)):[...e];return r?Object.freeze(i):i}if(e&&typeof e==`object`){if(i&&!Yl(e))return e;let a={};for(let[r,i]of Object.entries(e))a[r]=n?Ql(i,t):i;return r?Object.freeze(a):a}return e}var $l=[`name`],eu=Object.freeze({}),tu=new WeakMap;function nu(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=>iu({commands:t,commandFields:e.commandFields,conditions:r,onError:(e,t,r)=>{n.emitError(e,t,r)}}),v=t=>re(()=>e.commandResolvers.prepend(t),t),y=t=>re(()=>e.commandResolvers.append(t),t),b=()=>{e.commandResolvers.has()&&n.runWithStateChangeBatch(()=>{e.commandResolvers.clear(),i.onCommandResolversChanged(),n.queueStateChange()})},x=e=>le(e).map(e=>ru(e.commandState)),S=e=>{let t=ce(e),n=le(e,t);if(n.length===0)return[];let r=n.map(e=>({entry:e,command:ru(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&&R(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:(ue(n,ce(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=z(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=z(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=L(ie(t));return g.set(t,n??null),n},E=(e,t)=>L(M(t).chainsByName.get(e)),D=(e,t)=>z(e,null,{mode:`registered`,execution:t}),O=(e,t,n)=>z(e,t,{mode:`active`,execution:n}),k=(e,t)=>F(e,t)?.command,A=e=>I(e)?.commandState.command,j=(e,n,i)=>{let a=ee().chainsByName.get(e);if(!a||a.length===0)return;let o,s;for(let e of a){if(!nl(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=Gl(e,t,r,n);return te()&&(s=e.derivedVersion,c=n,l=i),i},ee=()=>a===e.derivedVersion&&o?o:(a=e.derivedVersion,o=Ul(e),o),te=()=>e.activeCommandViewCacheBlockers===0,ne=(e,t,n)=>e.command===void 0||e.run?!0:typeof e.command==`string`?n.reachableByName.has(e.command)?!0:ae(e.command,t,`active`)!==void 0:!1,N=(e,t,n)=>{if(typeof e.command!=`string`)return;let r=n.reachableByName.get(e.command);return r?r.commandState.attrs:ae(e.command,t,`active`)?.attrs},P=(e,n)=>{if(n?.some(t=>t.command.name===e)||ee().chainsByName.has(e))return`resolved`;let r=z(e,Zc(t));return r.resolved||r.hadError?r.resolved?`resolved`:`error`:`unresolved`},re=(t,r)=>n.runWithStateChangeBatch(()=>{let a=t();return i.onCommandResolversChanged(),n.queueStateChange(),()=>{n.runWithStateChangeBatch(()=>{a(),!e.commandResolvers.values().includes(r)&&(i.onCommandResolversChanged(),n.queueStateChange())})}}),F=(e,t)=>{let n=M(t).reachableByName.get(e);return n?{target:n.layer.target,command:n.commandState.command,attrs:n.commandState.attrs}:ae(e,t,`active`)},I=e=>ie(e)?.[0],ie=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},L=e=>{if(e?.length)return e.map(e=>({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs}))},ae=(e,t,n)=>z(e,t,{mode:n}).resolved,oe=()=>ee().entries,se=()=>{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},ce=e=>{let n=e?.visibility??`reachable`,r=e&&Object.prototype.hasOwnProperty.call(e,`focused`)?e.focused??null:Zc(t);return n===`registered`?{visibility:n,focused:r}:{visibility:n,focused:r,activeView:M(r)}},le=(e,t=ce(e))=>{let r;return r=t.visibility===`registered`?oe():t.visibility===`active`?t.activeView?.entries??[]:t.activeView?.reachable??[],lu({entries:r,query:e,getCommand:e=>ru(e),onFilterError:e=>{n.emitError(`command-query-filter-error`,e,`[Keymap] Error in command query filter:`)}})},R=(e,t,n)=>{de(n,n=>{fe(e,t,n)})},ue=(e,t)=>{if(t.visibility===`registered`){let t=se();for(let[n,r]of e){let e=ee().chainsByName.get(n)?.[0]?.commandState.attrs;for(let i of t.get(n)??[])r.push(me(i,e))}return}de(t,n=>{pe(e,n,t)})},de=(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)&&ne(a,t.focused,i)&&n(a)}},fe=(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(me(n,r.commandAttrs))}},pe=(e,t,n)=>{if(typeof t.command!=`string`)return;let r=e.get(t.command);r&&r.push(me(t,he(t,n)))},me=(e,t)=>({sequence:e.sequence,command:e.command,commandAttrs:t,attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),he=(e,t)=>{if(typeof e.command!=`string`)return;if(t.visibility===`registered`)return ee().chainsByName.get(e.command)?.[0]?.commandState.attrs;let n=t.activeView;if(n)return N(e,t.focused,n)},z=(t,r,i)=>{let a=i?.mode??`active`,o=i?.execution??{input:t},s=au(t,e.commandResolvers.values(),()=>ve(r,a,o),e=>{n.emitError(`command-resolver-error`,e,`[Keymap] Error in command resolver for "${t}":`)}),c=s.resolved;if(c){let e=_e(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=ge(c.command.name,r,a)??cu(c.command);e&&(s.resolved={...c,attrs:e})}return s},ge=(e,t,n)=>n===`registered`?I(e)?.commandState.attrs:M(t).reachableByName.get(e)?.commandState.attrs,_e=(e,t,n)=>n===`registered`?I(e):M(t).reachableByName.get(e),ve=(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:ne,getBindingCommandAttrs:N,getCommandResolutionStatus:P}}function ru(e){return e.command}function iu(e){let t=[],n=new Set;for(let r of e.commands)try{let i={},a=[],o=Vl(r.name),s=ou(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,Jl({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,Xl(t,`Failed to register keymap command "${String(r.name)}"`));continue}return t}function au(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:su(t,o.getExecutionFields())}}return{hadError:i}}function ou(e){let t={};for(let[n,r]of Object.entries(e))!Ll.has(n)&&r!==void 0&&(t[n]=r);return Object.keys(t).length===0?eu:t}function su(e,t){return{command:e,input:t.input,payload:t.payload}}function cu(e){let t=ou(e);return t===eu?void 0:t}function lu(e){let t=e.query?.namespace,n=uu(e.query?.limit);if(n===0)return[];let r=e.query?.search?.trim().toLowerCase()??``,i=$l;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(fu(u,t)&&du(u,r,i)&&!(c&&!c.has(u.command.name))&&pu(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 uu(e){if(e===void 0)return;let t=Math.floor(Number(e));return!Number.isFinite(t)||t<=0?0:t}function du(e,t,n){if(!t)return!0;for(let r of n)if(mu(e,r,t))return!0;return!1}function fu(e,t){if(t===void 0)return!0;let n=e.fields;return Object.prototype.hasOwnProperty.call(n,`namespace`)?xu(n.namespace,t):!1}function pu(e,t,n){if(!t)return!0;for(let[r,i]of t)if(!vu(e,r,i,n))return!1;return!0}function mu(e,t,n){return hu(e,t)?.includes(n)===!0}function hu(e,t){let n=tu.get(e);if(n||(n=new Map,tu.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=gu(a);return n.set(t,o),o}function gu(e){if(Array.isArray(e)){let t=[];for(let n of e){let e=gu(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 _u(e,t,n,r){try{return e(t,n)}catch(e){return r(e),!1}}function vu(e,t,n,r){return typeof n==`function`?yu(e,t,n,r):bu(e,t,n)}function yu(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,_u(n,i.name,l(),r.onFilterError))||Object.prototype.hasOwnProperty.call(a,t)&&(c=!0,_u(n,a[t],l(),r.onFilterError))||o&&Object.prototype.hasOwnProperty.call(o,t)&&(c=!0,_u(n,o[t],l(),r.onFilterError))?!0:!c&&_u(n,void 0,l(),r.onFilterError)}function bu(e,t,n){let r=e.command,i=e.fields,a=e.attrs;return t===`name`&&xu(r.name,n)||Object.prototype.hasOwnProperty.call(i,t)&&xu(i[t],n)?!0:!!a&&Object.prototype.hasOwnProperty.call(a,t)&&xu(a[t],n)}function xu(e,t){return Array.isArray(t)?t.some(t=>Su(e,t)):Su(e,t)}function Su(e,t){return Array.isArray(e)?e.some(e=>Su(e,t)):Object.is(e,t)}function Cu(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(Zl(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(wu(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=Bl(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`&&(Tu(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 Tu(n,i),!0;return!1}}}function wu(e){return typeof e==`object`&&!!e&&`ok`in e}function Tu(e,t){e.preventDefault&&(t.preventDefault(),t.stopPropagation())}var Eu=Object.freeze({}),Du=[],Ou=[];function ku(e){if(Object.keys(e).length!==0)return Ql(e,{freeze:!0})}function Au(e,t,n,r){let i=t=>Iu(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:Eu,parseObjectKey:(e,t)=>c(e,t)}),a=t=>{if(typeof t!=`string`)return[c(t)];let n=Fu(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:Eu,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)=>qc(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=Nu(b.key,m,{layer:d})}catch(e){t.emitError(`binding-expand-error`,e,Xl(e,`Failed to expand keymap binding`));continue}for(let m of i){let i=m.key,x;try{x=typeof i==`string`?Fu(i,h,{tokens:a,patterns:e.patterns,layer:d,parseObjectKey:(e,t)=>c(e,t)}):{parts:[c(i)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1},x=Pu(x,m)}catch(e){t.emitError(`binding-parse-error`,e,Xl(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`||Rl.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,Jl({fieldName:e,conditions:n,requirements:c,matchers:d,attrs:u}))}let p=Object.keys(u).length>0?ku(u):void 0,m=Bl(i.cmd),h={binding:b,sequence:a,command:m,event:t,parsedBinding:Sl(i),sourceTarget:o,sourceLayerOrder:s,bindingIndex:r,requires:Object.keys(c).length>0?Object.entries(c):Du,matchers:d.length>0?d:Ou,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`&&!_&&Mu(f,h),f.push(h)}catch(e){t.emitError(`binding-compile-error`,e,Xl(e,`Failed to compile keymap binding`))}}}return{bindings:f,hasTokenBindings:p}},c=(e,t)=>Bc(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:Hc(r)}];let l={...n,sequence:Hc(r)},u=[],d=!0,f=o??Eu;for(let n of s)try{n(l,{layer:f,parseKey:t=>Iu(t,a,{tokens:i,patterns:e.patterns,layer:f,parseObjectKey:(e,t)=>c(e,t)}),add:e=>{u.push(Sl(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 ju(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 Mu(e,t){for(let n of e)if(n.event===`press`&&(n.command!==void 0&&ju(n.sequence,t.sequence)||t.command!==void 0&&ju(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 Nu(e,t,n){if(typeof e!=`string`||t.length===0)return[{key:e}];let r=n?.layer??Eu,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 Pu(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 Fu(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??Eu,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:Ic,createMatch:Gc,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 Iu(e,t,n){if(typeof e!=`string`)return n.parseObjectKey(e);let{parts:r}=Fu(e,t,n),[i]=r;if(!i||r.length!==1)throw Error(`Invalid key "${String(e)}": expected a single key stroke`);return i}function Lu(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.get==`function`&&typeof t.subscribe==`function`}function Ru(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(Lu(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 zu=Symbol(`keymap-disambiguation-decision`),Bu=Symbol(`keymap-deferred-disambiguation-decision`);function Vu(e,t){return{[zu]:!0,action:e,handler:t}}function Hu(e){return{[Bu]:!0,action:e}}function Uu(e){return!!e&&typeof e==`object`&&e[zu]===!0}function Wu(e){return!!e&&typeof e==`object`&&e[Bu]===!0}function Gu(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 Ku(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 qu(e,t,n,r){let i=e.get(n)?.payloadKey??n;return{...Bc({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 Ju(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 Yu(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&&me()}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:Hc(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:Hc(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?Hc(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 ee(e){e.preventDefault(),e.stopPropagation()}function te(e,t,n,i){r.setPendingSequence({captures:t});let a=O(`sequence-pending`,t);return T(e,t,n),ee(i),a}function ne(e,t,n,i){let a=O(e,t);return T(`sequence-clear`,t,n),r.setPendingSequence(null),ee(i),a}function N(i,a){a||me();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=re(i);o&&j(o,i,a,s,e);return}let u=F(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 re(e){let t=r.getFocusedTarget(),n=r.getActiveLayers(t),a=ye(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=be(a,r,e,t);if(o=A(o,n.outcome),n.handled){if(n.stop)return o;continue layerLoop}}return o}function F(e){let t=r.getFocusedTarget(),n=r.ensureValidPendingSequence(),i=ye(e);if(n)return I(n,i,e,t);let a=r.getActiveLayers(t),o=M();for(let n of i){let r=L(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=pl(r,n,i,e.patterns,xe,Se);t&&c.push(t)}let l=c.reduce((e,t)=>Math.min(e,dl(t,n)),1/0),u=c.filter(e=>dl(e,n)===l);if(u.length===0||!u.some(e=>Ee(e,a,o))){let e=O(`sequence-miss`,t.captures);return T(`sequence-clear`,t.captures,a),r.setPendingSequence(null),e}return ie(u,0,!1,i,a)}function ie(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=_e(t,i,n);if(u.length>0){if(s)continue;let e=ve(t,n);return se(t,i,u,e,a,o,s)||te(`sequence-advance`,u,o,a)}if(!ol(n,e.patterns))continue;let d=ve(t,n);for(let e of d)l.add(e);let f=De(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 L(e,t,n,r){return ae(e,0,t,n,r)}function ae(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=Ce(n,r,a,o,c);if(u.length===0)continue;if(u.filter(t=>al(t,e.patterns,!1)).length>0){let n=u.filter(t=>ol(t,e.patterns)),i=ge(t,s,r,a,o);return oe(t,s,r,i,n,a,o)||te(`sequence-start`,i,o,a)}let d=De(n,u.filter(t=>ol(t,e.patterns)),a,o);if(l=A(l,d.outcome),d.handled&&d.stop)return l}return l}function oe(e,t,n,i,a,o,s){return ce({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=De(i,a,o,s);return c.stop?c.outcome:A(c.outcome,ae(e,t+1,n,o,s))}})}function se(e,t,n,i,a,o,s){return ce({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=De(n,i,a,o);return c.stop?c.outcome:A(c.outcome,ie(e,t+1,s||c.handled,a,o))}})}function ce(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=()=>te(c,a,i,n),p=()=>ne(`sequence-cleared`,a,i,n),m,h=()=>(m??=r.collectSequencePartsFromPending({captures:a}),m),g=R({event:n,focused:i,getSequence:h,exactBindings:d,continuationCaptures:a,activeView:u});return g?le(g,a,l,f,p,i,h):(z(h()),f())}function le(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 ue(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 R(i){let a,o,s,c,l={event:i.event,focused:i.focused,get sequence(){return a??=Hc(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:zc(e.stroke)},c},get exact(){return o??=r.collectActiveBindings(i.exactBindings,i.focused,i.activeView).map(e=>({...e,sequence:Hc(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:()=>Vu(`run-exact`),continueSequence:()=>Vu(`continue-sequence`),clear:()=>Vu(`clear`),defer:e=>Vu(`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(Zl(e)){t.emitError(`invalid-disambiguation-resolver-return`,e,`[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling`);continue}if(!Uu(e)){t.emitError(`invalid-disambiguation-decision`,e,`[Keymap] Invalid disambiguation decision returned by resolver:`);continue}return e}}}function ue(e,t,n,r,i){me();let a=new AbortController,o={id:f++,controller:a,captures:e,apply:i};d=o,queueMicrotask(()=>{de(o,t,n,r)})}function de(e,n,r,i){if(!he(e))return;let a={signal:e.controller.signal,sequence:Hc(i),focused:r,sleep:t=>Gu(t,e.controller.signal),runExact:()=>Hu(`run-exact`),continueSequence:()=>Hu(`continue-sequence`),clear:()=>Hu(`clear`)},o;try{o=n(a)}catch(n){he(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),pe(e));return}if(Zl(o)){o.then(t=>{fe(e,t)}).catch(n=>{he(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),pe(e))});return}fe(e,o)}function fe(e,n){if(he(e)){if(n!==void 0&&!Wu(n)){t.emitError(`invalid-deferred-disambiguation-decision`,n,`[Keymap] Invalid deferred disambiguation decision returned by handler:`),pe(e);return}pe(e),e.apply(n)}}function pe(e){he(e)&&(d=null)}function me(){let e=d;e&&(d=null,e.controller.abort())}function he(e){return d===e}function z(e){let n=qc(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 ge(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 Ce(n,r,a,o,l))al(t,e.patterns,!1)&&c.push(t)}return c}function _e(t,n,r){return t.filter((t,i)=>i>=n&&al(t,e.patterns,!1)&&Zu(t.parts,r.parts))}function ve(t,n){return t.filter(t=>t.layer===n.layer&&ol(t,e.patterns)&&Zu(t.parts,n.parts))}function ye(n){let r=e.eventMatchResolvers.values();if(r.length===0)return[];if(r.length===1)return Xu(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 be(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 xe(n,r){return Ku(e.patterns,t,n,r)}function Se(t,n,r){return qu(e.patterns,t,n,r)}function Ce(e,t,n,r,i){let a=ml(e,t,n,xe,Se);return a.some(e=>Ee(e,r,i))?a:[]}function we(n){return Ju(e.patterns,t,n)}function Te(e,t,n){return i.matchesConditions(e)&&s.isBindingVisible(e,t,n)}function Ee(e,t,n){return Te(e.binding,t,n)}function De(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,we(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:N}}function Xu(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 Zu(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 Qu=()=>{};function $u(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 ed(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 td(e,t,n,r,i){let a;try{a=Ic(i.name)}catch(e){return t.emitError(`token-name-normalize-error`,e,Xl(e,`Failed to register keymap token`)),Qu}if(e.tokens.has(a)||e.patterns.has(a))return t.emitError(`duplicate-token`,{token:a},`Keymap token "${a}" is already registered`),Qu;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,Xl(e,`Failed to register keymap token "${a}"`)),Qu}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,Xl(e,`Failed to register keymap token "${a}"`)),Qu}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,Xl(e,`Failed to unregister keymap token "${a}"`))}}}function nd(e,t,n,r){let i,a;try{i=Ic(r.name);let e=$u(i,`min`,r.min,1),t=$u(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:Gc(`pattern:${i}`),min:e,max:t,matcher:e=>r.match(e),finalize:r.finalize}}catch(e){return t.emitError(`sequence-pattern-register-error`,e,Xl(e,`Failed to register keymap sequence pattern`)),Qu}return e.tokens.has(i)||e.patterns.has(i)?(t.emitError(`duplicate-sequence-pattern`,{pattern:i},`Keymap sequence pattern "${i}" is already registered`),Qu):(e.patterns.set(i,a),n.recompileBindings(),()=>{e.patterns.get(i)===a&&(e.patterns.delete(i),n.recompileBindings())})}function rd(e,t,n,r){return ed(r,{kind:n,reservedFields:n===`layer`?zl:n===`binding`?Rl:Ll,registeredFields:n===`layer`?e.layerFields:n===`binding`?e.bindingFields:e.commandFields,emitError:(e,n,r)=>t.emitError(e,n,r)})}var id=()=>{};function ad(e,t){return t.priority-e.priority||t.order-e.order}function od(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 sd(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 cd(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`),id;let o,s,c,p,m,v,y;try{y=l(n),o=u(xl(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,Xl(e,`Failed to register keymap layer`)),id}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 id;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:cl(x.bindings,e.patterns),hasTokenBindings:x.hasTokenBindings,activeKeyCacheBlocked:!1,activeCommandViewCacheBlocked:!1};_(S),e.layers.add(S),e.sortedLayers=[...e.sortedLayers,S].sort(ad),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=>bl(e)});t&&(i=xl(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(zl.has(c)||l===void 0)continue;o[c]=Ql(l);let t=e.layerFields.get(c);if(!t){i.warnUnknownField(`layer`,c);continue}t(l,Jl({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?Ql(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=cl(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,Xl(e,`Failed to subscribe to reactive matcher from ${n.source}`))}},_=t=>{let n=od(t),r=sd(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,Xl(e,`Failed to dispose reactive matcher from ${n.source}`))}n.dispose=void 0}};return{registerLayer:a,applyTokenState:o,recompileBindings:s,cleanup:c}}var ld=1e3;function ud(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>=ld){e.stateChangePending=!1,i(`state-change-feedback-loop`,{iterations:ld},`[Keymap] Possible infinite state listener feedback loop detected after ${ld} 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 dd(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 fd=Object.freeze({});function pd(){return{order:0,tokens:new Map,patterns:new Map,layerFields:new Map,layerBindingsTransformers:_l(),bindingExpanders:_l(),bindingParsers:_l(),bindingTransformers:_l(),bindingFields:new Map,commandTransformers:_l(),commandFields:new Map,eventMatchResolvers:_l(),disambiguationResolvers:_l(),keyHooks:vl(),keyAfterHooks:vl(),rawHooks:vl(),layers:new Set,sortedLayers:[],activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],activeKeyCacheBlockers:0,activeCommandViewCacheBlockers:0,commandResolvers:_l(),pending:null,data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:fd,cacheVersion:0,derivedVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}function md(e){return Uc(e)}var hd=class{#e=pd();#t=!1;#n=new Map;#r=[];#i=hl(()=>{});#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=hl((e,t)=>{this.#o.reportListenerError(e,t)}),this.#o=ud(this.#e,this.#i,this.#a),this.#l=Ru(this.#e,this.#o),this.#u=nu(this.#e,this.#b,this.#o,this.#l,{onCommandResolversChanged:()=>{this.#s.ensureValidPendingSequence()}}),this.#s=Il(this.#e,this.#b,this.#a,this.#o,this.#l,this.#u,{onPendingSequenceChanged:(e,t)=>{this.#p?.handlePendingSequenceChange(e,t)}}),this.#c=dd(this.#e,this.#o,this.#s),this.#d=Cu(this.#o,this.#c,this.#s,this.#u,{keymap:this,createCommandEvent:()=>this.#b.createCommandEvent()}),this.#f=Au(this.#e,this.#o,this.#l,{warnUnknownField:(e,t)=>{this.#C(e,t)},warnUnknownToken:(e,t)=>{this.#w(e,t)}}),this.#h=Cl(this.#o,this.#u),this.#m=cd(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=Yu(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()}))}[Xc](){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?md(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 rd(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 td(this.#e,this.#o,this.#f,this.#m,e)}registerSequencePattern(e){return nd(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 rd(this.#e,this.#o,`binding`,e)}registerCommandFields(e){return rd(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)))}},gd=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(`.`)),_d=new Set([`ctrl`,`control`,`shift`,`meta`,`alt`,`option`,`super`,`hyper`]),vd=bd(gd),yd=bd(_d);function bd(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 xd(e){return e>=65&&e<=90?e+32:e}function Sd(e){return e>=48&&e<=57}function Cd(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(xd(e.charCodeAt(n+r))!==t.charCodeAt(r))return!1;return!0}function wd(e,t,n){let r=t.charCodeAt(n);if(Number.isNaN(r))return;let i=e.get(xd(r));if(i){for(let e of i)if(Cd(t,e,n))return e}}function Td(e,t,n,r,i){return e.parseObjectKey(t,{display:n,match:r,tokenName:i})}function Ed(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 Dd(e,t){let n=e.trim().toLowerCase();return t.parseObjectKey({name:n},{display:n})}function Od(e,t){let n=wd(vd,e,t);if(n)return n;if(xd(e.charCodeAt(t))!==102||!Sd(e.charCodeAt(t+1)))return;let r=Sd(e.charCodeAt(t+2))?t+3:t+2;return e.slice(t,r).toLowerCase()}function kd(e,t){return wd(yd,e,t)}function Ad(e,t,n){let r=t,i=!1,a=!1,o=!1,s=!1,c=!1;for(;r<e.length;){let t=kd(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=Od(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 jd=e=>{let{input:t,index:n,tokens:r,normalizeTokenName:i}=e;if(n===0&&t.includes(`+`)&&/\s/.test(t))return{parts:[Ed(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:[Ed(a,e)],nextIndex:n+1};let s=i(t.slice(n+1,o)),c=r.get(s);return c?{parts:[Td(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:[Ed(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=Ad(t,n,e);if(o)return{parts:[o.part],nextIndex:o.nextIndex};let s=Od(t,n);return s?{parts:[Dd(s,e)],nextIndex:n+s.length}:{parts:[Ed(a,e)],nextIndex:n+1}},Md=(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 Nd(e){return e.appendBindingParser(e=>jd(e))}function Pd(e){return e.appendEventMatchResolver((e,t)=>Md(e,t))}function Fd(e){let t=Nd(e),n=Pd(e);return()=>{n(),t()}}var Id=Symbol(`keymap:mod-bindings`),Ld=/(^|[+,\s])mod(?=\s*\+)/i,Rd=/(^|[+,\s])mod(?=\s*\+)/gi;function zd(e){let t=e.primaryModifier;return(t===`ctrl`||t===`super`)&&e.modifiers[t]!==`unsupported`?t:e.modifiers.ctrl===`unsupported`?`super`:`ctrl`}function Bd(e){if(e.includes(`,`))return[e];let t=e.trim();return t.includes(` `)?t.split(/\s+/):[e]}function Vd(e){return e.acquireResource(Id,()=>e.appendBindingExpander(({input:t,displays:n})=>{if(!Ld.test(t))return;let r=zd(e.getHostMetadata());return[{key:t.replace(Rd,(e,t)=>`${t}${r}`),displays:n??Bd(t)}]}))}var Hd=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 Ud(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 Wd(){let e=globalThis.navigator,t=e?.userAgentData?.platform,n=Ud(t);return n===`unknown`?Ud(e?.platform??e?.userAgent):n}function Gd(){let e=Wd();return{platform:e,primaryModifier:e===`macos`?`super`:e===`unknown`?`unknown`:`ctrl`,modifiers:{ctrl:`supported`,shift:`supported`,meta:`supported`,super:`supported`,hyper:`unsupported`}}}function Kd(e){return e.length===1&&!/^[a-z0-9]$/i.test(e)}function qd(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||!Kd(t.name)?[t]:[t,{...t,shift:!1}]}var Jd=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 Yd(){return globalThis.MutationObserver}function Xd(e){return Hd.get(e)||(/^F\d{1,2}$/i.test(e)||e.length===1?e.toLowerCase():e.trim().toLowerCase().replace(/\s+/g,``))}function Zd(e){if(!e)return new Jd(`command`,!1,!1,!1,!1);let t=globalThis.KeyboardEvent;return new Jd(Xd(e.key),e.ctrlKey,e.shiftKey,e.altKey,e.metaKey,t&&e instanceof t?e:void 0)}var Qd=class{metadata=Gd();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(Zd(t))};return this.rootTarget.addEventListener(`keydown`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keydown`,t,{capture:!0})}}onKeyRelease(e){let t=t=>{e(Zd(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 Zd()}ensureObserver(){if(this.observer||this.targetDestroyListeners.size===0)return;let e=Yd();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 $d(e){return new Qd(e)}var ef=(e,t)=>qd(e).map(e=>t.resolveKey(e)),tf=[2,3],nf=`fungi.app.ready.v3`,rf=`fungi.app.ready`,af=`fungi.app.connect`,of=e=>G.pipe(V(y(1)),V(Y(e))),sf=e=>H(of(e)),cf=Hi.pipe(V(Be()),V(z(Number.isSafeInteger,{message:`Expected a safe integer`}))),lf=cf.pipe(V(Se(0))),uf=cf.pipe(V(L(0))),df=q({appId:of(160),releaseId:of(160),surfaceId:of(160)}),ff=q({editing:r,surface:J([of(160),Ln])}),pf=J([q({kind:K(`compose`),requestId:of(160),text:of(2e3)}),q({kind:K(`navigate`),requestId:of(160),params:B(q({key:of(64),value:of(4096)})).pipe(V(Y(16)))})]),mf=qt(W([`granted`,`missing`])),hf=q({"agent.list":mf,"agent.manage":mf,"agent.read":mf,"agent.send":mf,"computer.list":mf,"computer.readFile":mf,"computer.writeFile":mf,"computer.execute":mf,"git.repository":mf,"workflow.publish":mf,"workflow.arm":mf,"workflow.run":mf,"app.events.emit":mf,"llm.generation":mf,"media.generation":mf,"media.share":mf}),gf=W([`ready`,`missing`,`unknown`]),_f=q({models:gf,media:gf,git:gf,terminal:W([`ready`,`exec-only`,`missing`,`unknown`]),terminalReason:H(G)}),vf=W([`model`,`media`,`git`,`computer`]),yf=W([`opened`,`unavailable`]),bf=q({computerId:J([of(256),Ln]),computerName:H(Br(G)),teamHasComputers:H(Br(r)),computerAccessGranted:H(r),setup:H(_f),permissions:H(hf),focus:ff,openRequest:J([Ln,pf]),visibility:W([`visible`,`hidden`])}),xf=W([`connecting`,`connected`,`suspended`,`disconnected`,`disposing`,`disposed`]),Sf=q({altKey:r,ctrlKey:r,id:of(160),key:of(64),metaKey:r,shiftKey:r}),Cf=q({action:H(jn),availability:H(jn),category:of(160),description:sf(512),id:of(160),projections:H(jn),title:of(160)}),wf=q({arguments:H(jn),commandId:of(321),origin:W([`agent`,`browser`,`keyboard`,`menu`,`palette`,`programmatic`,`slash`,`terminal`]),requestId:of(160)}),Tf=J([q({result:H(jn),status:K(`handled`)}),q({error:jn,status:K(`failed`)})]),Ef=e=>of(e).pipe(V(z(e=>{for(let t=0;t<e.length;t+=1)if(Nc(e.charCodeAt(t)))return!1;return!0},{message:`Expected one line of plain text`}))),Df={id:of(64),text:Ef(80),end:qt(r),priority:qt(K(`low`))},Of=qt(Hi.pipe(V(Be()),V($e({minimum:0,maximum:9999})))),kf=B(J([q({...Df,kind:K(`text`),tone:qt(W([`neutral`,`success`,`warning`,`error`]))}),q({...Df,kind:K(`button`),icon:qt(W([`folder`,`ports`,`processes`,`access`])),count:Of,tone:qt(W([`neutral`,`success`,`warning`,`error`])),busy:qt(r),title:qt(Ef(1024)),disabled:qt(r),opens:qt(K(`dialog`)),expanded:qt(r)}),q({...Df,kind:K(`toggle`),pressed:r}),q({...Df,kind:K(`menu`),count:Of,title:qt(Ef(1024)),options:B(q({id:of(64),text:Ef(80),checked:qt(r),disabled:qt(r)})).pipe(V(Y(16)),V(z(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status option ids`})))})])).pipe(V(Y(6)),V(z(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status item ids`}))),Af=q({computerId:of(256),path:of(1024)}),jf=of(80).pipe(V(z(e=>e.trim()===e,{message:`Expected a trimmed title`}))),Mf=of(64),Nf=of(80),Pf=e=>new Set(e.map(e=>e.id)).size===e.length,Ff=q({id:Mf,label:Nf,siblings:H(B(q({id:Mf,label:Nf})).pipe(V(Y(16)),V(z(Pf,{message:`Expected unique crumb sibling ids`}))))}),If=q({id:Mf,label:Nf,icon:H(K(`play`)),variant:H(W([`primary`,`outline`,`ghost`])),tone:H(K(`destructive`)),disabled:H(r)}),Lf=e=>B(If).pipe(V(Y(e)),V(z(Pf,{message:`Expected unique header command ids`}))),Rf=q({id:Mf,label:Nf,presentation:H(K(`bead`)),tone:H(W([`neutral`,`info`,`warning`,`success`,`error`]))}),zf={status:H(B(Rf).pipe(V(Y(4)),V(z(Pf,{message:`Expected unique header status ids`})))),crumbs:H(B(Ff).pipe(V(Y(8)),V(z(Pf,{message:`Expected unique crumb ids`})))),primary:H(Lf(3)),menu:H(Lf(12))},Bf=q({contractVersion:K(2),canGoBack:r,canGoForward:r,title:H(jf),...zf}),Vf=q({canGoBack:r,canGoForward:r,title:H(G),...zf}),Hf=J([q({kind:K(`crumb`),crumbId:Mf,siblingId:H(Mf)}),q({kind:K(`action`),actionId:Mf})]),Uf=Br(q({agentId:of(256),sessionId:of(256)})),Wf=e=>H(B(W(e)).pipe(V(Y(e.length)))),Gf=q({agents:H(B(W([`agent.list`,`agent.manage`,`agent.read`,`agent.send`])).pipe(V(Y(4)))),computers:H(B(W([`computer.list`,`computer.readFile`,`computer.writeFile`,`computer.execute`])).pipe(V(Y(4)))),git:Wf([`git.repository`]),workflows:Wf([`workflow.publish`,`workflow.arm`,`workflow.run`]),events:Wf([`app.events.emit`]),generation:Wf([`llm.generation`,`media.generation`,`media.share`])}),Kf=W([`granted`,`declined`,`customize`]),qf=q({message:of(512),tone:H(W([`info`,`success`,`warning`,`error`]))}),Jf=W(Fo);q({code:Jf.pick([`DELIVERY_PENDING`])});var Yf=q({code:Jf,message:of(512),retryable:r,need:qt(Po)}),Xf=J([q({protocolVersion:K(3),type:K(nf)}),q({protocolVersion:K(2),type:K(rf)})]),Zf=q({epoch:of(160),protocolVersion:W(tf),type:K(af)}),Qf=q({epoch:of(160),protocolVersion:W(tf)}),$f={[Symbol.dispose]:H(jn)},ep=J([q({...$f,ok:K(!0),value:jn}),q({...$f,error:Yf,ok:K(!1)})]);function tp(e,t,n=`PROTOCOL`){return Ga(A(e,{onExcessProperty:`error`}),ba({onFailure:e=>{throw new Z(`The peer sent malformed protocol data`,{cause:e,code:n,retryable:!1})},onSuccess:t}))}function $(e){return Object.freeze(e)}function np(e,t){let n=e.arguments===void 0?void 0:Nn(e.arguments),r={origin:e.origin,signal:t};return n!==void 0&&Object.assign(r,{arguments:n}),$(r)}var rp=tp(Cf,e=>{let t={category:e.category,id:e.id,title:e.title};return e.action!==void 0&&Object.assign(t,{action:e.action}),e.availability!==void 0&&Object.assign(t,{availability:e.availability}),e.description!==void 0&&Object.assign(t,{description:e.description}),e.projections!==void 0&&Object.assign(t,{projections:e.projections}),$(Jp(()=>xn(t)))},`INVALID_ARGUMENT`),ip=tp(of(321),e=>e),ap=tp(wf,e=>{let t=e.arguments===void 0?void 0:Nn(e.arguments),n={commandId:e.commandId,origin:e.origin,requestId:e.requestId};return t!==void 0&&Object.assign(n,{arguments:t}),$(n)}),op=tp(J([yn,jn]),e=>e===void 0?void 0:Nn(e)),sp=tp(Zf,e=>$(e));tp(Qf,e=>$(e));var cp=tp(bf,e=>{let t={computerId:e.computerId,focus:$({...e.focus}),openRequest:e.openRequest===null?null:$({...e.openRequest}),visibility:e.visibility};return e.teamHasComputers!==void 0&&(t.teamHasComputers=e.teamHasComputers),e.computerName!==void 0&&(t.computerName=e.computerName),e.computerAccessGranted!==void 0&&(t.computerAccessGranted=e.computerAccessGranted),e.setup!==void 0&&(t.setup=$({...e.setup})),e.permissions!==void 0&&(t.permissions=$({...e.permissions})),$(t)}),lp=tp(Yf,e=>$({...e})),up=tp(ff,e=>$({...e}),`INVALID_ARGUMENT`),dp=tp(df,e=>$({...e})),fp=tp(xf,e=>e),pp=tp(kf,e=>$(e.map(e=>e.kind===`menu`?$({...e,options:$(e.options.map(e=>$(e)))}):$(e))),`INVALID_ARGUMENT`),mp=tp(q({itemId:of(64),optionId:qt(of(64)),anchor:qt(q({start:Hi.pipe(V($e({minimum:0,maximum:1e5}))),width:Hi.pipe(V($e({minimum:0,maximum:1e5})))}))}),e=>$(e.anchor===void 0?{...e}:{...e,anchor:$({...e.anchor})}),`INVALID_ARGUMENT`),hp=tp(Af,e=>$({...e}),`INVALID_ARGUMENT`);function gp(e){let t={id:e.id,label:e.label};return e.presentation!==void 0&&(t={...t,presentation:e.presentation}),e.tone!==void 0&&(t={...t,tone:e.tone}),$(t)}function _p(e){let t={id:e.id,label:e.label};return e.siblings===void 0?$(t):$({...t,siblings:$(e.siblings.map(e=>$({...e})))})}function vp(e){let t={id:e.id,label:e.label};return e.icon!==void 0&&(t={...t,icon:e.icon}),e.variant!==void 0&&(t={...t,variant:e.variant}),e.tone!==void 0&&(t={...t,tone:e.tone}),e.disabled!==void 0&&(t={...t,disabled:e.disabled}),$(t)}function yp(e){let t={canGoBack:e.canGoBack,canGoForward:e.canGoForward};return e.title!==void 0&&(t={...t,title:e.title}),e.crumbs!==void 0&&(t={...t,crumbs:$(e.crumbs.map(_p))}),e.primary!==void 0&&(t={...t,primary:$(e.primary.map(vp))}),e.menu!==void 0&&(t={...t,menu:$(e.menu.map(vp))}),e.status!==void 0&&(t={...t,status:$(e.status.map(gp))}),$(t)}var bp=tp(Bf,yp,`INVALID_ARGUMENT`),xp=tp(Vf,e=>{let t=e.title?.trim();return Sp({...yp({...e,title:t===void 0||t.length===0?void 0:t}),contractVersion:2})},`INVALID_ARGUMENT`),Sp=tp(Bf,e=>$({...yp(e),contractVersion:2}),`INVALID_ARGUMENT`),Cp=tp(Hf,e=>e.kind===`action`?$({...e}):$(e.siblingId===void 0?{kind:e.kind,crumbId:e.crumbId}:e),`INVALID_ARGUMENT`),wp=tp(Uf,e=>e===null?null:$({...e}),`INVALID_ARGUMENT`),Tp=tp(Gf,e=>$({agents:$([...new Set(e.agents??[])]),computers:$([...new Set(e.computers??[])]),...e.git&&{git:$([...new Set(e.git)])},...e.workflows&&{workflows:$([...new Set(e.workflows)])},...e.events&&{events:$([...new Set(e.events)])},...e.generation&&{generation:$([...new Set(e.generation)])}}),`INVALID_ARGUMENT`),Ep=tp(vf,e=>e,`INVALID_ARGUMENT`);tp(Xf,e=>$(e));var Dp=tp(of(512),e=>e),Op=tp(qf,e=>$({...e}),`INVALID_ARGUMENT`);tp(q({id:of(160),repeat:r}),e=>$(e));var kp=tp(B(Sf).pipe(V(Y(64))),e=>{if(new Set(e.map(e=>e.id)).size!==e.length)throw new Z(`Reserved chords are invalid`,{code:`PROTOCOL`,retryable:!1});return $(e.map(e=>$({...e})))});function Ap(e){return tp(q({value:jn,version:lf}),t=>$({value:e(t.value),version:t.version}))}var jp=Ap(cp),Mp=tp(q({capabilities:B(jn).pipe(V(Y(128))),context:jn}),e=>$({capabilities:$(e.capabilities.map(e=>Rp(e))),context:jp(e.context)})),Np=Ap(fp),Pp=Ap(kp),Fp=Ap(Dp),Ip=Ga(Np,e=>{if(e.value!==`connected`&&e.value!==`suspended`)throw new Z(`The host lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return $({value:e.value,version:e.version})});function Lp(e){return tp(q({handle:jn,id:of(160),version:uf}),t=>{if(!(t.handle instanceof Ac)&&!(e&&t.handle instanceof jc))throw new Z(`A capability handle is invalid`,{code:`PROTOCOL`,retryable:!1});return $({handle:t.handle,id:t.id,version:t.version})})}var Rp=Lp(!1),zp=Lp(!0);function Bp(e){let t=e?zp:Rp;return tp(q({capabilities:B(jn).pipe(V(Y(128))),context:jn,identity:jn,lifecycle:jn,reservedChords:jn,theme:jn}),e=>$({capabilities:$(e.capabilities.map(e=>t(e))),context:jp(e.context),identity:dp(e.identity),lifecycle:Ip(e.lifecycle),reservedChords:Pp(e.reservedChords),theme:Fp(e.theme)}))}var Vp=Bp(!1);Bp(!0);function Hp(e){return tp(ep,t=>t.ok?$({ok:!0,value:e(t.value)}):$({ok:!1,error:lp(t.error)}))}var Up=Hp(Vp),Wp=Hp(tp(q({commandId:of(321)}),e=>$(e)));Hp(tp(Tf,e=>{if(e.status===`failed`)return $({status:`failed`,error:Jp(()=>Yi(e.error))});let t=e.result===void 0?void 0:Nn(e.result);return $(t===void 0?{status:`handled`}:{status:`handled`,result:t})}));var Gp=Hp(tp(yn,()=>void 0)),Kp=Hp(tp(Kf,e=>e)),qp=Hp(tp(yf,e=>e));Hp(tp(r,e=>e)),Hp(tp(r,e=>e));function Jp(e){try{return e()}catch(e){throw new Z(`The command metadata is invalid`,{cause:e,code:`INVALID_ARGUMENT`,retryable:!1})}}var Yp=J([q({kind:K(`saveFile`),name:of(255).pipe(V(Vt(/^[^\p{Cc}/\\]+$/u))),mime:of(255),bytes:sr}),q({kind:K(`copyText`),text:G})]);function Xp(e){let t=A(Yp,{onExcessProperty:`error`})(e);if(Ya(t))return{kind:`refused`,reason:`invalid-request`};let n=t.success;return n.kind===`saveFile`?n.name===`.`||n.name===`..`?{kind:`refused`,reason:`invalid-request`}:n.bytes.byteLength>33554432?{kind:`refused`,reason:`too-large`}:{...n,bytes:new Uint8Array(n.bytes)}:n.text.length>1048576||new TextEncoder().encode(n.text).byteLength>1048576?{kind:`refused`,reason:`too-large`}:n}var Zp=Hp(tp(J([q({kind:K(`saved`)}),q({kind:K(`copied`)}),q({kind:K(`refused`),reason:W([`no-user-gesture`,`too-large`,`invalid-request`,`unavailable`,`denied`,`busy`])})]),e=>$(e)));function Qp(e){return e instanceof Z?{code:e.code,message:em(e.message),retryable:e.retryable,...e.need!==void 0&&{need:e.need}}:{code:`HOST_FAILURE`,message:`Host operation failed`,retryable:!1}}function $p(e){try{let t=lp(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 em(e){return e.trim().slice(0,512)||`Host operation failed`}var tm=e=>({ok:!0,value:e}),nm=e=>({error:Qp(e),ok:!1});async function rm(e,t){let n,r=new Set;try{return n=await e,im(t(n))}catch(e){throw am(e)&&om(e,r),e instanceof Z?e:new Z(`The remote operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}finally{n!==e&&am(n)&&om(n,r)}}function im(e){if(e.ok)return e.value;throw $p(e.error)}function am(e){return Va(e)&&Symbol.dispose in e&&ka(e[Symbol.dispose])}function om(e,t){if(!t.has(e)){t.add(e);try{e[Symbol.dispose]()}catch(e){console.warn(`RPC result disposal failed`,e)}}}function sm(){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 cm(e){let t=kp(e),n=new Set;return{get:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e)),update:e=>{t=kp(e);for(let e of Array.from(n))try{e()}catch(e){console.warn(`Reserved chord subscriber failed`,e)}}}}function lm(e){let t=!0,n,r=e.window.document.querySelector(`html`);if(!r)return()=>{t=!1};let i=$d(r),a=new hd(i);Fd(a),Vd(a),a.prependEventMatchResolver(ef);let o=dm(e.onBroken),s=hm(a,e.chords,e.remote,o),c=um(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=()=>fm(e.window.document,e.identity.surfaceId).editing,p=d===void 0?()=>void 0:pm(a,d,f),m=d===void 0?()=>void 0:d.subscribe(()=>{p(),p=pm(a,d,f)}),h=e.chords.subscribe(()=>{s(),s=hm(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 um(e,t,n,r,i){return()=>{if(!n())return;let a=fm(e.window.document,e.identity.surfaceId),o=i();(a.editing!==o?.editing||a.surface!==o.surface)&&(r(a),t(()=>e.remote.reportFocus(a)))}}function dm(e){return t=>{try{rm(t(),Gp).catch(t=>{os(`browser-bridge.host-call`,t),e(t)})}catch(t){os(`browser-bridge.host-call`,t),e(t)}}}function fm(e,t){let n=e.activeElement;return up({editing:!!(n?.matches(`input, textarea, select, [contenteditable='true']`)===!0||n?.closest(`[contenteditable='true']`)),surface:e.hasFocus()?t:null})}function pm(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||mm(e.key)&&n())return!1;e.run()}})),priority:500})}function mm(e){return!/(?:^|\+)(?:ctrl|control|super|meta|cmd|alt|option|mod)\+/iu.test(e)}function hm(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:Xd(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 gm(e){let t=t=>{if(t.defaultPrevented||t.isComposing)return;let n=ym(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=vm(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 _m)e.window.addEventListener(t,n);return()=>{e.window.removeEventListener(`keydown`,t);for(let t of _m)e.window.removeEventListener(t,n)}}var _m=[`mousedown`,`mouseup`,`auxclick`];function vm(e){return e===3?`back`:e===4?`forward`:null}function ym(e,t){return e.shiftKey||e.ctrlKey?null:t?!e.metaKey||e.altKey?null:e.key===`[`?`back`:e.key===`]`?`forward`:bm(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 bm(e){return e instanceof HTMLElement?e.isContentEditable||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement:!1}function xm(){return!Ea(globalThis.navigator)&&/Mac|iPhone|iPad/u.test(globalThis.navigator.userAgent)}function Sm(e){let t=e,n=new Set;return{get:()=>t,subscribe(e){n.add(e);let t=!0;return()=>{t&&(t=!1,n.delete(e))}},update(e){if(!Object.is(t,e)){t=e;for(let e of Array.from(n))try{e(t)}catch(e){console.warn(`App store subscriber failed`,e)}}}}}function Cm(e){let t=new Map,n=Sm(0),r=!1,i=e=>{let t=new Map;try{for(let n of e){let e=Rp(n),r=Dm(e.id,e.version);if(t.has(r))throw Tm(e.handle),new Z(`Duplicate capability grant`,{code:`PROTOCOL`,retryable:!1});t.set(r,e.handle)}}catch(e){for(let e of t.values())Tm(e);throw e}return t};for(let[n,r]of i(e))t.set(n,r);let a=e=>{for(let t of e)Tm(t)},o=e=>{if(r)throw new Z(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let n=Dm(e.id,e.version);return t.get(n)};return{directory:Object.freeze({get version(){return n.get()},subscribe:e=>n.subscribe(e),has(e){return!!o(e)},require(e){let t=o(e);if(!t)throw new Z(`The capability is not granted`,{code:`CAPABILITY_DENIED`,retryable:!1});try{return e.schema.parse(t)}catch(e){throw new Z(`The capability interface is malformed`,{cause:e,code:`PROTOCOL`,retryable:!1})}}}),replace(e){if(r)throw new Z(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let o=i(e),s=[...t.values()];t.clear();for(let[e,n]of o)t.set(e,n);a(s.filter(e=>![...o.values()].includes(e))),n.update(n.get()+1)},disconnect(){r||(r=!0,a(t.values()),t.clear(),n.update(n.get()+1))}}}var wm=Ba().transform(e=>{let t=Ka(Object).safeParse(e);if(!t.success)return;let n=Object.create(t.data),r=ot(q({[Symbol.dispose]:H(kr(Function))}))(n);return{owner:t.data,dispose:r[Symbol.dispose]}});function Tm(e){try{let t=wm.parse(e);if(t===void 0||Em.has(t.owner))return;Em.add(t.owner),t.dispose?.call(t.owner)}catch(e){console.warn(`RPC value disposal failed`,e)}}var Em=new WeakSet;function Dm(e,t){return`${e}@${String(t)}`}var Om=class extends jc{#e=!0;#t;#n=new Map;constructor(e){super(),this.#t=e}cancel(e){try{return this.#n.get(ip(e))?.abort(),Promise.resolve(tm(void 0))}catch(e){return Promise.resolve(nm(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=ap(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=op(await this.#t(np(t,n.signal)));return tm(e===void 0?{status:`handled`}:{status:`handled`,result:e})}finally{this.#n.delete(t.requestId)}}catch(e){if(e instanceof _r)try{let t={code:e.code,message:e.message,details:e.details};return tm({status:`failed`,error:Yi(t)})}catch(e){return nm(e)}return nm(e)}}[Symbol.dispose](){this.dispose()}};function km(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=im(await i.invoke({commandId:e,origin:`keyboard`,requestId:lt()}));if(t.status===`failed`)throw new _r(t.error.code,t.error.message,t.error.details)}).catch(e=>{console.warn(`App key command failed`,e)})}})}return t}function Am(e,t,n,r){let i=new Map,a=!1,o=()=>{r?.update(a?[]:km(i))},s=e=>{try{n()}catch(t){console.warn(`App command failure callback failed`,t,e)}},c=e=>{try{rm(e(),Gp).catch(e=>{s(e)})}catch(e){console.warn(`App command RPC supervision failed`,e),s(e)}};return{commands:Mm(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 jm(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 Mm(e,t,n,r,i,a){return Object.freeze({async register(o,s){if(t(),!ka(s))throw new Z(`Command handler must be a function`,{code:`INVALID_ARGUMENT`,retryable:!1});let c=rp(o),l=new Om(s),u=jm(n,c,l);try{let t=await Nm(e,c,u.target);r()&&await Pm(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 Nm(e,t,n){return rm(e.registerCommand(t,n),Wp)}async function Pm(e,t,n){throw n.dispose(),await rm(e.unregisterCommand(t),Gp),new Z(`The command controller is disposed`,{code:`DISCONNECTED`,retryable:!0})}var Fm=T(e=>e instanceof Ac),Im=class extends jc{#e=!1;#t;constructor(e){super(),this.#t=e}disconnect(e){try{if(this.#e)throw qm();let t=e===void 0?void 0:lp(e);return setTimeout(()=>this.#t.disconnect?.(t??Zm()),0),Promise.resolve(tm(void 0))}catch(e){return Promise.resolve(nm(e))}}async requestClose(){try{if(this.#e)throw qm();return tm(await(this.#t.beforeClose?.()??!0))}catch(e){return nm(e)}}async requestBack(){try{if(this.#e)throw qm();return tm(await(this.#t.back?.()??!1))}catch(e){return nm(e)}}async requestForward(){try{if(this.#e)throw qm();return tm(await(this.#t.forward?.()??!1))}catch(e){return nm(e)}}async activateNavigation(e){try{if(this.#e)throw qm();let t=Cp(e);return Fc(this.#t.navigation,t)?tm(await(this.#t.activate?.(t)??!1)):tm(!1)}catch(e){return nm(e)}}async activateStatus(e){try{if(this.#e)throw qm();let t=mp(e);return Pc(this.#t.statusItems,t)?tm(await(this.#t.statusAction?.(t)??!1)):tm(!1)}catch(e){return nm(e)}}[Symbol.dispose](){this.#e=!0}async updateContext(e){return this.#e?nm(qm()):this.#n(e,`context`,cp,e=>{this.#t.context.update(e)})}reconfigure(e){let t=[];try{if(this.#e)throw qm();let n=Mp(e);if(n.context.version<=this.#t.versions.context)return Promise.resolve(tm(void 0));for(let e of n.capabilities)t.push({...e,handle:ot(Fm)(e.handle).dup()});if(!this.#t.capabilities)throw qm();return this.#t.capabilities.replace(t),t=[],this.#t.versions.context=n.context.version,this.#t.context.update(n.context.value),Promise.resolve(tm(void 0))}catch(e){for(let e of t)Tm(e.handle);return Promise.resolve(nm(e))}}updateLifecycle(e){try{if(this.#e)throw qm();let t=Ap(fp)(e);if(t.version<=this.#t.versions.lifecycle)return Promise.resolve(tm(void 0));if(!Qm(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(tm(void 0))}catch(e){return Promise.resolve(nm(e))}}async updateReservedChords(e){return this.#e?nm(qm()):this.#n(e,`chords`,kp,e=>{this.#t.chords.update(e)})}async updateTheme(e){return this.#e?nm(qm()):this.#n(e,`theme`,Dp,e=>{this.#t.theme.update(e)})}#n(e,t,n,r){try{let i=Ap(n)(e);return i.version>this.#t.versions[t]&&(this.#t.versions[t]=i.version,r(i.value)),Promise.resolve(tm(void 0))}catch(e){return Promise.resolve(nm(e))}}};async function Lm(e){let t=Vm(),n=new Im(t),r=Mc(e.port,n),i,a=Bm(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=im(Up(o));if(!e.isActive())throw zm();let c=Hm({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 eh(t,e,n,r,i)}}function Rm(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 zm(){return new Z(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function Bm(e){let t,n=new Promise((e,n)=>{t=n});return n.catch(e=>{os(`app-session.rpc-disconnect`,e)}),e.onRpcBroken(()=>t?.(new Z(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0}))),n}function Vm(){return{statusItems:[],navigation:{canGoBack:!1,canGoForward:!1},bindings:sm(),chords:cm([]),context:Sm({computerId:null,focus:{editing:!1,surface:null},openRequest:null,visibility:`hidden`}),lifecycle:Sm(`connecting`),theme:Sm(`default`),canGoBack:!1,canGoForward:!1,versions:{chords:-1,context:-1,lifecycle:-1,theme:-1}}}function Hm(e){let t=dp(e.bootstrap.identity),n=$m(e.bootstrap);Rm(e.state,n);let r=Cm(e.bootstrap.capabilities);return e.state.capabilities=r,Wm(e,t,r)}function Um(e,t,n){return lm({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 Wm(e,t,n){let r=!1,i=t=>{r||(r=!0,Ym([()=>{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]()},()=>{Tm(e.bootstrapOwner)},()=>{Tm(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=Am(e.remote,a,()=>{i({code:`DISCONNECTED`,message:`The app host rejected a terminal command operation`,retryable:!0})},e.state.bindings),s=Km(e.remote,a,e.state),c=Gm(e.state,e.remote,a),l=Um(e,t,i),u=gm({window:e.options.window,mac:xm(),canGoBack:()=>e.state.canGoBack&&e.state.back!==void 0,back:()=>{let t=e.state.back;t&&Promise.resolve().then(t).catch(e=>{os(`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=>{os(`app-window.forward-input`,e)})}});return e.state.disconnect=i,e.remote.onRpcBroken(()=>{Jm(i)}),Xm({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 Gm(e,t,n){let r=Object.freeze({async publish(r){n();let i=xp(r);e.canGoBack=i.canGoBack,e.canGoForward=i.canGoForward,e.navigation=bp(i),await rm(t.reportNavigation(i),Gp)},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 Km(e,t,n){return Object.freeze({async requestComputerChoice(){t(),await rm(e.requestComputerChoice(),Gp)},async requestBrowserAction(n){t();let r=Xp(n);return r.kind===`refused`?r:await rm(e.requestBrowserAction(r),Zp)},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 rm(e.requestAppPermissions(Tp(n)),Kp)},async openDesktopSettings(){t(),await rm(e.openDesktopSettings(),Gp)},async openSetup(n){return t(),await rm(e.openSetup(Ep(n)),qp)},async openTeamBilling(){t(),await rm(e.openTeamBilling(),Gp)},async openNavigation(n){t(),await rm(e.openNavigation(hp(n)),Gp)},async reportStatus(r){t();let i=pp(r);n.statusItems=i,await rm(e.reportStatus(i),Gp)},async reportAgentSessionSelection(n){t(),await rm(e.reportAgentSessionSelection(wp(n)),Gp)},async showToast(n){t(),await rm(e.showToast(Op(n)),Gp)}})}function qm(){return new Z(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})}function Jm(e){e({code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!0})}function Ym(e,t){for(let n of e)try{n()}catch(e){console.warn(`${t} cleanup failed`,e)}}function Xm(e){return Object.freeze(e)}function Zm(){return{code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!1}}function Qm(e,t){return e===t||e===`connected`&&t===`suspended`||e===`suspended`&&t===`connected`}function $m(e){let t=Ap(cp)(e.context),n=Ap(Dp)(e.theme),r=Ap(fp)(e.lifecycle),i=Ap(kp)(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 eh(e,t,n,r,i){throw Ym([()=>{n[Symbol.dispose]()},()=>{i&&Tm(i)},()=>{Tm(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 th=!1,nh=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):(th=!0,this.#a())}#a(){return new Promise((e,t)=>{let n=(n,a)=>{this.#o(n,a,i,r,e,t)},r=()=>{n(ih())},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:nf},`*`),this.#e.parent.postMessage({protocolVersion:2,type:rf},`*`)}catch(e){os(`connect.notify-host`,e),n(uh(e))}};this.#r=setInterval(a,200),this.#i=setTimeout(()=>{n(oh())},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(),th=!1,a(e??oh());return}i(t)}}#s(e,t,n){if(!lh(e.data))return;if(performance.mark(`fungi.app-open.agar-connect-received`),e.source!==this.#e.parent||sh(e.origin)===void 0){t(ch());return}let r=dh(e,t);if(!r)return;let i=e.ports.length===1?e.ports[0]:void 0;if(!i){t(fh(`The app host did not transfer exactly one port`));return}this.#t=i,this.#c(),this.#e.removeEventListener(`message`,n),Lm({epoch:r.epoch,protocolVersion:r.protocolVersion,isActive:()=>!this.#n,onDisposed:()=>{th=!1},port:i,window:this.#e}).then(e=>{performance.mark(`fungi.app-open.agar-root-ready`),t(void 0,e)},e=>{t(ah(e))})}#c(){clearInterval(this.#r),clearTimeout(this.#i),this.#r=void 0,this.#i=void 0}#l(){if(this.options.signal?.aborted)return ih();if(th)return new Z(`An app connection is already live`,{code:`IDENTITY`,retryable:!1});if(Ea(globalThis.window)||this.#e.parent===this.#e)return new Z(`The app host is unavailable`,{code:`DISCONNECTED`,retryable:!0})}};function rh(e){return new nh(e).start()}function ih(){return new Z(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function ah(e){return e instanceof Z?e:new Z(`Unable to connect to the app host`,{cause:e,code:`PROTOCOL`,retryable:!1})}function oh(){return new Z(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0})}function sh(e){if(!URL.canParse(e))return;let t=new URL(e).origin;return t===e?t:void 0}function ch(){return new Z(`The app connection identity is invalid`,{code:`IDENTITY`,retryable:!1})}var lh=Ke(q({type:K(af)}));function uh(e){return new Z(`Unable to notify the app host`,{cause:e,code:`DISCONNECTED`,retryable:!0})}function dh(e,t){try{return sp(e.data)}catch(e){os(`connect.decode-message`,e),t(e instanceof Z?e:new Z(`Malformed app connection`,{cause:e,code:`PROTOCOL`,retryable:!1}));return}}function fh(e){return new Z(e,{code:`PROTOCOL`,retryable:!1})}function ph(e,t,n){e.style.isolation=`isolate`;let r=(0,as.createRoot)(e),i=new AbortController,a=e.ownerDocument.documentElement,o=Vo(a),s,c,l,u=!1,d=e=>{let i=(0,X.createElement)(mh,{state:e,render:n});r.render(t.queryClient?(0,X.createElement)(nn,{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`):Bo(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`}),rh({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,Bo(e.theme.get(),a),c=e.theme.subscribe(e=>{Bo(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 mh({state:e,render:t}){return(0,X.useLayoutEffect)(()=>{performance.mark(`fungi.app-open.react-initial-commit`)},[]),(0,X.useLayoutEffect)(()=>{e.app&&performance.mark(`fungi.app-open.react-connected-commit`)},[e.app]),(0,X.createElement)(X.Fragment,null,e.status===`not-hosted`?(0,X.createElement)(`p`,{role:`alert`},`App host connection unavailable. Open this App through its host to try again.`):null,t(e))}function hh(e){let t=(0,X.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,X.useCallback)(()=>e?.get(),[e]);return(0,X.useSyncExternalStore)(t,n,n)}function gh(e){return hh(e?.context)??null}function _h(e,t,n,r){let i=(0,X.useRef)(t);i.current=t;let a=(0,X.useRef)(n);a.current=n;let o=(0,X.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,X.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,X.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,X.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function vh(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,X.useRef)(c),p=(0,X.useRef)(l),m=(0,X.useRef)(u),h=(0,X.useRef)(d);(0,X.useEffect)(()=>{f.current=c,p.current=l,m.current=u,h.current=d},[c,l,u,d]),(0,X.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(),yh(e,{canGoBack:!1,canGoForward:!1})}},[e]);let g=JSON.stringify([i,a,o,s]),_=(0,X.useRef)({crumbs:i,primary:a,menu:o,status:s});(0,X.useEffect)(()=>{_.current={crumbs:i,primary:a,menu:o,status:s}},[i,a,o,s]),(0,X.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}),yh(e,i)},[e,t,n,r,g])}function yh(e,t){e.publish(t).catch(e=>{e instanceof Z&&e.code===`DISCONNECTED`||console.warn(`App navigation report failed`,e)})}var bh=class{id;version;#e;constructor(e,t,n){this.id=e,this.version=t,this.#e=n,Object.freeze(this)}get schema(){return this.#e}};function xh(e,t,n){return new bh(e,t,n)}function Sh(e){let t=wa(e),n=Ka(Object),r=wa(Object.fromEntries(Object.keys(e).map(e=>[e,Ba().optional()])));return Ba().transform(e=>{let i=n.parse(e),a=Object.create(i),o=r.parse(a),s=Object.fromEntries(Object.entries(o).flatMap(([e,t])=>t===void 0?[]:[[e,no().parse(t).bind(i)]]));return{...t.parse(s),[Symbol.dispose](){Tm(e)}}})}function Ch(e){return Ba().transform(t=>{try{return e.parse(t)}catch(e){throw e instanceof Z?e:new Z(`The capability returned malformed data`,{cause:e,code:`PROTOCOL`,retryable:!1})}finally{Tm(t)}})}function wh(e){return no({output:Oa(Ba().transform(t=>{try{return e.parse(t)}catch(e){throw Tm(t),e instanceof Z?e:new Z(`The capability returned a malformed result`,{cause:e,code:`PROTOCOL`,retryable:!1})}}))})}var Th=wh(Ch(Ja())),Eh=Sh({fetch:wh(Ka(Response)),close:Th});To().trim().min(1).max(256).refine(e=>!/[\p{Cc}\p{Cf}]/u.test(e),{message:`An Agent name cannot contain control or invisible characters`});var Dh=G.pipe(V(y(1)),V(Y(256))),Oh=T(e=>Ue.safeParse(e).success,{expected:`an Avatar v1 descriptor`}),kh=q({agentId:Dh,name:Dh,avatar:Oh,sessionOperations:B(W([`agent.read`,`agent.send`,`agent.manage`]))});ya(()=>za({agents:wo(za({agentId:To(),name:To()}))}));var Ah=J([W([`new`,`none`]),q({computerId:Dh})]),jh=q({computerId:Dh,name:Dh,createdAt:Hi.pipe(V(Be()))}),Mh=Br(B(jh)),Nh=ot(Mh,{onExcessProperty:`error`}),Ph=q({name:Dh,requestId:Dh,computer:qt(Ah),avatar:qt(Oh)}),Fh=B(kh),Ih=ot(Fh,{onExcessProperty:`error`}),Lh=ot(Dh),Rh=ot(kr(Response)),zh=xh(`agent.list`,1,ya(()=>Sh({list:wh(Ch(Ba().transform(e=>Ih(e))))}))),Bh=xh(`agent.manage`,1,ya(()=>Sh({open:wh(Eh),computers:wh(Ch(Ba().transform(e=>Nh(e)))),create:wh(Ch(Ba().transform(e=>ot(kh)(e))))}))),Vh=q({agentId:Dh,name:Dh}),Hh=xh(`agent.rename`,1,ya(()=>Sh({rename:wh(Ch(Ba().transform(e=>ot(kh)(e))))})));async function Uh(e,t){let n=ot(Vh)(t),r=await e.require(Hh).rename(n);return ot(kh)(r)}var Wh=q({agentId:Dh,avatar:Oh}),Gh=xh(`agent.avatar`,1,ya(()=>Sh({setAvatar:wh(Ch(Ba().transform(e=>ot(kh)(e))))})));async function Kh(e,t){let n=ot(Wh)(t),r=await e.require(Gh).setAvatar(n);return ot(kh)(r)}var qh=q({agentId:Dh}),Jh=q({agentId:Dh,expectedContent:Br(G),content:G}),Yh=q({agentId:Dh,home:Br(q({name:G})),content:Br(G),bytes:Li.pipe(V(Se(0))),limit:Li.pipe(V(L(0)))}),Xh=xh(`agent.instructions`,2,ya(()=>Sh({read:wh(Ch(Ba().transform(e=>ot(Yh)(e)))),set:wh(Ch(Ba().transform(e=>ot(Yh)(e))))})));async function Zh(e,t){let n=ot(qh)({agentId:t});return ot(Yh)(await e.require(Xh).read(n))}async function Qh(e,t){let n=ot(Jh)(t);return ot(Yh)(await e.require(Xh).set(n))}var $h=ya(()=>Da([wa({status:oo(`pending`),revision:To()}),wa({status:oo(`approved`),revision:To()})])),eg=ya(()=>Da([$h,wa({error:To()})])),tg=xh(`agent.toolPolicy`,1,ya(()=>Sh({status:wh(Ch(Da([$h,So()]))),approve:wh(Ch(eg))}))),ng=xh(`agent.read`,1,ya(()=>Sh({open:wh(Eh),openInbox:wh(Eh)}))),rg=xh(`agent.send`,1,ya(()=>Sh({open:wh(Eh),openInbox:wh(Eh)})));async function ig(e,t){let n=ot(Ph)(t),r=await e.require(Bh).create(n);return ot(kh)(r)}async function ag(e){let t=Nh(await e.require(Bh).computers());return t===null?null:[...t].sort((e,t)=>t.createdAt-e.createdAt)}async function og(e,t){let n=await e(),r,i,a=()=>{if(i)throw new Z(`The Agent connection is closed`,{code:`DISCONNECTED`,retryable:!0})},o=async e=>{try{await e.close()}finally{e[Symbol.dispose]()}};return{fetch:async i=>{a(),i.signal.throwIfAborted();let o=i.method===`GET`||i.method===`HEAD`||e===t?n:await(r??=t());a(),i.signal.throwIfAborted();let s=Rh(await o.fetch(i));return s.body===null?s:new Response(s.body.pipeThrough(new TransformStream,{signal:i.signal}),s)},close:()=>(i||(i=Promise.all([o(n),...r?[r.then(o)]:[]]).then(()=>void 0),i.catch(e=>{os(`agents.close`,e)})),i)}}var sg=`https://agent-session.fungi.invalid`;async function cg(e,t){let n=Lh(t.agentId),r=`/agents/id-${encodeURIComponent(n)}`,i=`${sg}${r}`,a=e.has(ng)?e.require(ng):e.has(rg)?e.require(rg):e.require(Bh),o=()=>a.open({agentId:n}),s=await og(o,e.has(ng)?()=>(e.has(rg)?e.require(rg):e.require(Bh)).open({agentId:n}):o);return Object.freeze({baseUrl:i,fetch:async(e,t)=>{let n=new Request(e,t),i=new URL(n.url);if(i.origin!==sg||!i.pathname.startsWith(`${r}/`))throw new Z(`The Agent request target is invalid`,{code:`INVALID_ARGUMENT`,retryable:!1});return i.pathname=i.pathname.slice(r.length),s.fetch(new Request(i,n))},close:s.close})}var lg=`${sg}/member`;async function ug(e){let t=e.has(ng)?ng:rg,n=()=>e.require(t).openInbox(),r=await og(n,e.has(ng)?()=>e.require(rg).openInbox():n);return Object.freeze({baseUrl:lg,fetch:async(e,t)=>{let n=new Request(e,t),i=new URL(n.url);if(i.origin!==sg||!i.pathname.startsWith(`/member/inbox`))throw new Z(`The inbox request target is invalid`,{code:`INVALID_ARGUMENT`,retryable:!1});return i.pathname=i.pathname.slice(7),r.fetch(new Request(i,n))},close:r.close})}var dg=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(mg(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(mg(this),t)}};function fg(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function pg(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(pg).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${pg(e.cause)}`:e.message:`${e}`}function mg(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var hg=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}},gg=10,_g=13,vg=32,yg=6;function bg(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<yg&&!b(s.join(``)+e.slice(0,yg-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)===gg?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)===_g?(h=!1,g=!0,``):(h=!1,e.slice(r+(e.charCodeAt(r)===_g&&e.charCodeAt(r+1)===gg?2:1)))}function y(e){if(e){if(e.charCodeAt(e.length-1)===_g){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&&Cg(e,`data`)||t===101&&Cg(e,`event`)||t===105&&Cg(e,`id`)||t===114&&Cg(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 hg(`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(xg(e,t,r)){let r=e.charCodeAt(t+5)===vg?t+6:t+5,o=e.slice(r,n);if(f===0&&e.charCodeAt(n+1)===gg){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 Sg(e,t,r)?p=e.slice(e.charCodeAt(t+6)===vg?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)===_g&&e.charCodeAt(t)===gg&&t++}return e.slice(t)}function C(e,t,r){if(t===r){T();return}let i=e.charCodeAt(t);if(xg(e,t,i)){let n=e.charCodeAt(t+5)===vg?t+6:t+5,i=e.slice(n,r);d=f===0?i:`${d}\n${i}`,f++;return}if(Sg(e,t,i)){p=e.slice(e.charCodeAt(t+6)===vg?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)===vg?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)===vg?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)===vg?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 hg(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:n}));break;default:r?.(new hg(`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 xg(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 Sg(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 Cg(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 wg=104857600,Tg=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,Dg());else throw Error(`Invalid URL`)}catch{throw fg(`An invalid or illegal string was specified`)}this.#l=bg({maxBufferSize:t?.maxBufferSize??wg,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(pg(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&&Og(r,`origin`,t),r.lastEventId!==n&&Og(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 dg(`error`,{code:t,message:e});this.dispatchEvent(n)}#S(e,t){if(this.#e===this.CLOSED)return;this.#e=this.CONNECTING;let n=new dg(`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(Tg,"name",{value:`EventSource`}),Object.defineProperty(Tg,Symbol.for(`eventsource.supports-fetch-override`),{value:!0,writable:!1,configurable:!1,enumerable:!1});var Eg=Tg;function Dg(){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 Og(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0})}var kg=G.check(y(1),Y(256)),Ag=Hi.check(Be(),Se(0)),jg=J([q({agentId:kg,sessionId:kg,title:G.check(Y(4096)),triggerId:qt(kg),createdAt:Ag,lastActivityAt:Ag,settledAt:qt(Ag),visitedAt:qt(Ag),state:W([`needs_you`,`running`,`errored`,`done`])}),q({agentId:kg,sessionId:kg,state:K(`unavailable`)})]),Mg=q({runId:kg,nodeId:kg,iteration:kg}),Ng=q({kind:K(`workflow-review`),key:Mg,installationId:kg,workflowId:Br(kg),workflowTitle:G,reviewTitle:G,reviewers:W([`runner`,`owners`]),show:B($r),choices:qt(B(kg)),openedAt:Ag,expiresAt:Ag,state:W([`pending`,`answered`,`delivered`,`timed_out`,`closed`])}),Pg=J([jg,Ng]),Fg=J([Pg,q({agentId:kg,sessionId:kg,deleted:K(!0)})]);function Ig(e,t){return`${e}\u0000${t}`}function Lg(e){return`kind`in e?JSON.stringify([e.kind,e.installationId,e.key.runId,e.key.nodeId,e.key.iteration]):Ig(e.agentId,e.sessionId)}var Rg=G.pipe(V(y(1),Y(256))),zg=q({kind:K(`seller-closed`),dispositionId:G.pipe(V(y(1),Y(1024))),sellerAccountId:Rg,buyerAccountId:Rg,appId:Rg,releaseIds:hr([Rg]),displayName:Rg,sellerName:Rg,requestId:Rg}),Bg={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`}}}},Vg=[`dashboard`,`inbox`,`files`,`media`,`sessions`,`terminal`],Hg=`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(`,`),Ug=[`file.open`],Wg=[`team`,`member`],Gg=Object.freeze({capabilities:[],handlers:[],roles:[]}),Kg=Object.freeze([`owner`,`admin`,`member`]),qg=ya(()=>ro(Kg));function Jg(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 Yg=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`]}),Xg=S().check(Ha(1),Wa(256)),Zg=Wr(`kind`,[Ct({kind:ir(`team`),teamId:Xg}),Ct({kind:ir(`standalone`),tenant:Xg})]),Qg=la({kind:ir(`member`),memberId:Xg}),$g=la({kind:ir(`agent`),agentId:Xg}),e_=la({kind:ir(`team-key`),keyId:Xg}),t_=Wr(`kind`,[Qg,$g,e_]),n_=la({workflowId:Xg,runId:Xg,nodeId:Xg,armedBy:t_}),r_=Qn(()=>Ct({method:S().check(na(e=>l_(e))),seal:S().check(bo(/^[A-Za-z0-9_-]{43}$/u))})),i_=la({scope:Zg,computerId:gn(Xg),actor:t_,backgroundLane:kn(S().check(Ha(8),Wa(263))),backgroundOrigin:kn(r_),role:kn(qg),soleMember:kn(ir(!0)),workflow:kn(n_),idempotencyKey:kn(S().check(Ha(1),Wa(128)))}),a_=Wr(`kind`,[Ct(Qg.shape),Ct($g.shape),Ct(e_.shape)]),o_=Ct({...i_.shape,actor:a_,workflow:kn(Ct({...n_.shape,armedBy:a_}))}),s_=(e,t=!1)=>c_((t?o_:i_).parse(e));function c_(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 l_=e=>e.length<=80&&/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/.test(e)&&!Object.values(Yg).flat().some(t=>t===e),u_=65536,d_=1048576,f_=e=>new TextEncoder().encode(e).byteLength,p_=S().check(Ha(1),Wa(64)),m_=S().check(na(e=>f_(e)<=u_));Wr(`kind`,[Ct({kind:ir(`connect`),connection:p_,caller:i_}),Ct({kind:ir(`message`),connection:p_,data:m_}),Ct({kind:ir(`close`),connection:p_}),Ct({kind:ir(`alarm`)})]),Ct({send:kn(ui(Ct({connection:p_,data:m_})).check(Wa(256),na(e=>e.reduce((e,{data:t})=>e+f_(t),0)<=d_))),close:kn(ui(p_).check(Wa(256))),wakeAt:kn(gn(Ki().check(fr(),va(),Aa(2**53-1))))});var h_=G.check(z(l_));function g_(e){return typeof e==`object`&&!!e}function __(e,t=0){if(t>16)return!1;if(g_(e)){for(let n of Object.values(e))if(!__(n,t+1))return!1}return!0}var v_=Ti.pipe(V(z(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=2e4&&__(e),{message:`App API schema exceeds its byte or depth bound`}))),y_=G.check(y(1),Y(128)),b_=q({description:G.pipe(V(y(1)),V(Y(1e3))),input:v_,output:v_,pending:H(K(!0)),hidden:H(K(!0)),present:H(q({verb:G.check(y(1),Y(32))})),effect:W([`read`,`write`,`external`]),requires:B(W(Hg)).pipe(V(z(e=>new Set(e).size===e.length)))}),x_=q({methods:Wn(G,b_).pipe(V(z(e=>Object.keys(e).every(Ke(h_)),{message:`Invalid App API method name`})),V(z(e=>Object.keys(e).length<=64)),V(z(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:qt(q({name:h_.check(z(e=>!e.includes(`.`))),list:h_,call:h_})),events:qt(Wn(G,q({description:G.check(y(1),Y(1e3)),payload:v_})).check(z(e=>Object.keys(e).every(Ke(y_)),{message:`Invalid App API event name`}),z(e=>Object.keys(e).length<=64)))}).pipe(V(z(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`})),V(z(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=256e3,{message:`App API exceeds its total byte bound`}))),S_=e=>new Set(e).size===e.length;function C_(e,t){let n=Object.keys(t);for(let e of n)ot(h_)(e);return{declaration:q({name:K(e),operations:B(W(n)).pipe(V(y(1)),V(Y(n.length)),V(z(S_)))}),shard:q({name:K(e),operations:B(J(Object.entries(t).map(([e,t])=>q({name:K(e),cap:K(t.cap)})))).pipe(V(y(1)),V(Y(n.length)),V(z(e=>S_(e.map(e=>e.name)),{message:`App backend operation repeated`})))})}}var w_=Object.values(Bg).map(e=>C_(e.name,e.operations)),T_=w_.length,E_=B(J(w_.map(e=>e.declaration))).pipe(V(Y(T_)),V(z(e=>S_(e.map(e=>e.name)))));B(J(w_.map(e=>e.shard))).pipe(V(Y(T_)),V(z(e=>S_(e.map(e=>e.name)))));var D_=new Map(Object.entries(Bg).map(([e,t])=>[e,new Map(Object.entries(t.operations))]));function O_(e,t){return D_.get(e)?.get(t)}var k_=W(Vg),A_=W(Hg),j_=W(Ug),M_={message:`App declaration entries must be unique`},N_=e=>new Set(e).size===e.length,P_=new Set([`super+k`,`meta+k`,`cmd+k`,`mod+k`,`ctrl+k`,`control+k`]),F_=G.pipe(V(Y(256)),V(z(e=>e.trim().length>0,{message:`Declared command text must not be blank`}))),I_={order:H(Li)},L_=q(I_),R_=q({id:F_.pipe(V(z(e=>!e.includes(`:`),{message:`Declared command IDs are namespace-local`}))),title:F_,category:F_,description:H(G.pipe(V(Y(1024)))),sigil:H(F_.pipe(V(Y(64)))),projections:H(q({bindings:H(q({...I_,values:B(F_).pipe(V(Y(16)),V(z(e=>!e.some(e=>P_.has(e.trim().toLowerCase())),{message:`Apps cannot bind the reserved leader chord`})))})),agent:H(q({...I_,keybind:H(G)})),help:H(L_),menu:H(L_),palette:H(L_),slash:H(q({...I_,aliases:B(F_).pipe(V(Y(16)))}))}))}),z_=e=>N_(e.map(e=>e.id))&&N_(e.flatMap(e=>e.projections?.slash?.aliases??[])),B_=e=>N_(e.map(e=>e.id)),V_=G.check(Vt(/^[a-z][a-z0-9.-]{0,63}$/)),H_=q({key:V_,scopes:B(W(Wg)).check(y(1),z(N_,M_)),maxBytes:Li.check($e({minimum:1,maximum:65536}))}),U_=$i()([H_],([e])=>(t,n,r)=>Qt(e)(t,{...r,onExcessProperty:`error`}),{toCodecJson:()=>new fn(H_.ast,Kn())}),W_=q({appId:G.check(y(1),Y(128)),methods:B(h_).check(y(1),Y(16),z(N_,M_))}),G_=$i()([W_],([e])=>(t,n,r)=>Qt(e)(t,{...r,onExcessProperty:`error`}),{toCodecJson:()=>new fn(W_.ast,Kn())}),K_=B(G_).check(y(1),Y(16),z(e=>N_(e.map(e=>e.appId)),M_)),q_=e=>q({api:qt(x_),displayName:H(G.pipe(V(y(1)),V(Y(64)))),capabilities:B(A_).pipe(V(z(N_,M_))),calls:qt(K_),guidance:H(G.pipe(V(y(1)),V(Y(12e3)))),handlers:B(j_).pipe(V(z(N_,M_))),receives:qt(B(K(`git.push`)).check(Y(1),z(N_,M_))),icon:qt(G.pipe(V(y(1)),V(Y(80)))),roles:B(k_).pipe(V(z(N_,M_))),storage:qt(B(U_).check(Y(16),z(e=>N_(e.map(e=>e.key)),M_))),commands:H(B(R_).pipe(V(Y(64)),V(z(z_,{message:`Declared command IDs and slash aliases must be unique`})))),gills:H(B(e).pipe(V(Y(16)),V(z(B_,{message:`Declared Gill IDs must be unique`})))),backend:H(q({bindings:E_,sync:qt(q({method:h_}))}))}).pipe(V(z(e=>e.calls===void 0||e.capabilities.includes(`apps.call`),{message:`App calls require apps.call`})),V(z(e=>e.backend?.bindings.every(e=>e.name!==`BACKGROUND`)??!0,{message:`BACKGROUND is host-minted and cannot be declared by an App`})),V(z(e=>Jg(e.api,e.backend?.sync),{message:`Background continuation must be a declared write covering all write requirements`})),V(z(e=>!(e.receives?.includes(`git.push`)??!1)||e.capabilities.includes(`git.repository`),{message:`Git push reception requires git.repository`})),V(z(e=>e.backend?.bindings.every(t=>t.operations.every(n=>O_(t.name,n)?.requires.every(t=>e.capabilities.includes(t))===!0))??!0,{message:`Backend bindings require declared App capabilities`})),V(z(e=>!e.backend?.bindings.some(e=>e.name===`APP_STORAGE`)||(e.storage?.length??0)>0,{message:`App storage bindings require declared keys`})),V(z(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`})));q_(Xi);var J_=q_(Ot);function Y_(e){return/^app_[a-z0-9]{1,63}$/u.test(e)}function X_(e){return/^rel_[a-z0-9]{1,63}$/u.test(e)}function Z_(e){return/^ps_[a-z0-9]{1,63}$/u.test(e)}function Q_(e){return/^artifact:[a-z0-9](?:[a-z0-9._-]{0,126}[a-z0-9])?$/u.test(e)}function $_(e){return/^idem_[a-z0-9](?:[a-z0-9_-]{0,126}[a-z0-9])?$/u.test(e)}function ev(e){return/^git:[0-9a-f]{40}$/u.test(e)}function tv(e){return/^sha256:[0-9a-f]{64}$/u.test(e)}function nv(e){return/^\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(e)}var rv=F({family:`app-release`,version:1,kinds:{transition:{prefix:`app_transition`},surface:{prefix:`ps`},erasure:{prefix:`app_erasure`}}}),iv=rv.transition;rv.surface,rv.erasure;var av=G.pipe(R(Y_)),ov=G.pipe(R(X_)),sv=G.pipe(R(Z_)),cv=G.pipe(R(Q_)),lv=G.pipe(R($_)),uv=G.pipe(R(ev)),dv=G.pipe(R(tv)),fv=G.pipe(R(nv)),pv=q({byteLength:Hi,copy:kr(Function)}).pipe(R(e=>e.byteLength>=0)),mv=q({appId:av}),hv=q({sourceRevision:uv,sourceTreeDigest:dv,buildRecipeDigest:dv}),gv=q({artifactRef:cv,artifactDigest:dv,provenance:hv}),_v=q({releaseId:ov,appId:av,artifact:gv}),vv=q({publicSurfaceId:sv,appId:av,stableRoute:fv}),yv=G.pipe(V(y(1)),V(Y(256))),bv=q({...vv.fields,publisher:q({kind:W([`customer`,`platform`]),teamId:yv,userId:yv,requestKey:yv})}),xv=W([`text/html; charset=utf-8`,`application/vnd.fungi.app-backend+json`,`application/vnd.fungi.app-assets+json`,`application/vnd.fungi.app+json`]),Sv=q({artifactRef:cv,digest:dv,mediaType:W([`text/html; charset=utf-8`,`application/vnd.fungi.app-backend+json`,`application/vnd.fungi.app-assets+json`]),version:G.pipe(V(y(1))),byteLength:Hi.pipe(V(Be()),V(L(0)),V(z(Number.isSafeInteger)))}),Cv=q({runtime:q({kind:W([`durable-facet`,`region`]),stateSchema:Hi.pipe(V(Be()),V(L(0)))}),compatibilityDate:G.pipe(V(Vt(/^\d{4}-\d{2}-\d{2}$/))),exportName:G.pipe(V(y(1)))}),wv=q({format:K(`fungi-app-v1`),ui:Br(Sv),backend:Br(q({artifact:Sv,profile:Cv})),declaration:J_.pipe(Oe(ja(Gg)))}),Tv=q({kind:K(`verified`),digest:dv,mediaType:xv,bytes:pv,byteLength:Hi}),Ev=J([Tv,q({kind:K(`unavailable`)}),q({kind:K(`missing`)}),q({kind:K(`digest-mismatch`),actualDigest:dv})]),Dv=J([q({kind:K(`found`),app:mv}),q({kind:K(`absent`)})]),Ov=J([q({kind:K(`created`),app:mv}),q({kind:K(`existing`),app:mv})]),kv=J([q({kind:K(`found`),release:_v}),q({kind:K(`absent`)})]),Av=J([q({kind:K(`created`),release:_v}),q({kind:K(`existing`),release:_v})]),jv=J([q({kind:K(`found`),surface:vv}),q({kind:K(`absent`)})]),Mv=J([q({kind:K(`created`),surface:vv}),q({kind:K(`existing`),surface:vv}),q({kind:K(`conflict`)})]),Nv=J([q({kind:K(`verified`),digest:dv,mediaType:K(`application/vnd.fungi.app+json`),description:wv}),q({kind:K(`unverified`)})]),Pv=J([q({kind:K(`active`)}),q({kind:K(`revoked`)})]),Fv=J([q({kind:K(`promotion`),publicSurfaceId:sv,releaseId:ov,idempotencyKey:lv}),q({kind:K(`rollback`),publicSurfaceId:sv,releaseId:ov,idempotencyKey:lv}),q({kind:K(`revocation`),releaseId:ov,idempotencyKey:lv})]),Iv=T(e=>iv.schema.safeParse(e).success),Lv=q({transition:Fv,transitionId:Iv}),Rv=J([q({kind:K(`none`)}),q({kind:K(`selected`),releaseId:ov})]),zv=J([q({kind:K(`found`),release:_v,verification:Nv,revocation:Pv}),q({kind:K(`absent`)})]);J([q({kind:K(`found`),surface:vv,selection:Rv}),q({kind:K(`absent`)})]);var Bv=J([q({kind:K(`absent`)}),q({kind:K(`found`),receipt:Lv}),q({kind:K(`conflict`)})]),Vv=J([q({kind:K(`created`),receipt:Lv}),q({kind:K(`existing`),receipt:Lv}),q({kind:K(`conflict`)}),q({kind:K(`identity-collision`)}),q({kind:K(`lifecycle-conflict`)})]),Hv=q({kind:K(`recorded`)}),Uv=q({kind:K(`unavailable`)});function Wv(e){return J([q({kind:K(`success`),value:e}),q({kind:K(`failure`),failure:Uv})])}var Gv=Wv(Dv),Kv=Wv(Ov),qv=Wv(kv),Jv=Wv(Av),Yv=Wv(jv),Xv=Wv(Mv),Zv=Wv(zv),Qv=Wv(Hv),$v=Wv(Bv),ey=Wv(Vv);A(av,{onExcessProperty:`error`}),A(ov,{onExcessProperty:`error`}),A(sv,{onExcessProperty:`error`}),A(cv,{onExcessProperty:`error`}),A(lv,{onExcessProperty:`error`}),A(uv,{onExcessProperty:`error`}),A(dv,{onExcessProperty:`error`}),A(fv,{onExcessProperty:`error`}),A(Iv,{onExcessProperty:`error`}),jt(Ev,{onExcessProperty:`error`}),A(mv,{onExcessProperty:`error`}),A(_v,{onExcessProperty:`error`}),A(vv,{onExcessProperty:`error`}),A(bv,{onExcessProperty:`error`}),A(Gv,{onExcessProperty:`error`}),A(Kv,{onExcessProperty:`error`}),A(qv,{onExcessProperty:`error`}),A(Jv,{onExcessProperty:`error`}),A(Yv,{onExcessProperty:`error`}),A(Xv,{onExcessProperty:`error`}),A(Fv,{onExcessProperty:`error`}),A(Zv,{onExcessProperty:`error`}),A(Qv,{onExcessProperty:`error`}),A($v,{onExcessProperty:`error`}),A(ey,{onExcessProperty:`error`});var ty=G.pipe(V(y(1)),V(Y(256))),ny=G.pipe(V(Vt(/\S/u)),V(Y(1e3)));q({dispositionId:ty,requestId:ty,operatorId:ty,reason:ny,action:J([q({kind:K(`retain-detached`)}),q({kind:K(`revoke-with-notice`)})])});var ry=q({dispositionId:ty,appId:av,displayName:G.pipe(V(y(1)),V(Y(64))),releaseIds:B(ov).pipe(V(y(1)),V(Y(1e4))),reason:ny}),iy=q({disposition_id:ty,app_id:av,release_ids_json:G,artifact_roots_json:G,created_at:Hi,state:W([`pending`,`retaining`,`retained`,`revoking`,`revoked`]),request_id:Br(ty),reason:Br(ny),completed_at:Br(Hi)});q({...iy.fields,releaseIds:B(ov).pipe(V(Y(1e4)))}),p(B(ov).pipe(V(Y(1e4)))),p(B(cv).pipe(V(Y(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 ay=Hi.pipe(V(Be()),V(Se(0))),oy=q({items:B(Pg),next:Br(G),cursor:ay});za({visited:oo(!0)});var sy=ot(oy),cy=ot(p(q({kind:K(`rows`),from:ay,to:ay,items:B(Fg),more:r})));function ly(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=Lg(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,os(`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=cy(e.data)}catch(e){os(`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=sy(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;os(`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 uy=ot(q({items:B(J([q({...ry.fields,reason:H(ry.fields.reason),createdAt:ay}),q({...zg.fields,createdAt:ay})])).pipe(V(Y(100))),next:Br(G.pipe(V(Y(1024))))}),{onExcessProperty:`error`});async function dy(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 uy(await r.json())}var fy=Pa({status:La()}),py=3,my=/network ?(?:changed|error)|failed to fetch|load failed|network connection was lost/iu;function hy(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 gy(e){return hy(e).some(e=>{if(e instanceof TypeError)return!0;if(e instanceof Z)return e.code===`HOST_FAILURE`&&e.retryable;let t=fy.safeParse(e);return t.success?t.data.status>=500:e instanceof Error&&my.test(e.message)})}function _y(e,t){return e<py&&gy(t)}function vy(e){return 250*2**e}function yy(e,t){return t.status===`live`?t:{...t,data:t.data??e.data}}function by(e,t,n={}){return rs({queryKey:e,...n,retry:_y,retryDelay:vy,staleTime:1/0,refetchOnMount:`always`,queryFn:ha({initialValue:{status:`loading`},refetchMode:`append`,reducer:yy,streamFn:({signal:e})=>O(ee(n=>Xa(function*(){let r={status:`loading`},i=()=>{rt(n)};if(yield*Ta(Ua(()=>{e.addEventListener(`abort`,i,{once:!0})}),()=>Ua(()=>{e.removeEventListener(`abort`,i)})),e.aborted){i();return}yield*Ta($a({try:()=>Promise.resolve(t(e=>{r=yy(r,e),u(n,r)},e)),catch:Sy}),e=>Ua(e))}).pipe(eo(e=>Nr(n,e))),{bufferSize:1,strategy:`sliding`}))})})}async function xy(e,t,n){if(!e)throw new Z(`No App connection`,{code:`DISCONNECTED`,retryable:!0});let r=await ug(e.capabilities),i=()=>{r.close().catch(e=>{os(`inbox.query-close`,e)})};if(n.aborted)return i(),()=>void 0;let a=ly({baseUrl:r.baseUrl,fetch:r.fetch,openEvents:e=>{let t=new Eg(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:To().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 Sy(e){return e instanceof Z?e:new Z(`App operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!1})}var Cy=new WeakMap,wy={of(e,...t){return[e?.identity.surfaceId??null,e?.context.get().computerId??null,...t]}};function Ty(e){let t={};return e&&Cy.set(t,e),t}function Ey(){let e=new g({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&&Cy.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 Dy(e,t,n,r){let i=e?.context.get().computerId;return bt({queryKey:n,meta:Ty(e),enabled:e!==null,retry:_y,retryDelay:vy,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 Sy(e)}}})}function Oy(e){hh(e?.context);let t=Xt(),n=e?.context.get().computerId,r=(0,X.useMemo)(()=>wy.of(e,`member-inbox`),[e,n]),i=by(r,(0,X.useCallback)((t,r)=>{if(e?.context.get().computerId!==n)throw new Z(`The selected Computer changed`,{code:`SELECTION_CHANGED`,retryable:!1});return xy(e,t,r)},[e,n]),{enabled:e!==null,meta:Ty(e)}),a=(0,X.useCallback)(()=>{t.invalidateQueries({queryKey:r,exact:!0})},[t,r]),o=(0,X.useCallback)(async(t,n)=>{if(!e)throw new Z(`No App connection`,{code:`DISCONNECTED`,retryable:!0});let r=await ug(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 ky=J([q({kind:K(`compose`),text:G.pipe(V(y(1)),V(Y(2e3)))}),q({kind:K(`navigate`),params:B(q({key:G.pipe(V(y(1)),V(Y(64))),value:G.pipe(V(Y(1024)))})).pipe(V(Y(16)))})]);J([q({role:G.pipe(V(y(1)),V(Y(80))),intent:ky}),q({appId:G.pipe(V(y(1)),V(Y(128))),intent:ky})],{mode:`oneOf`});var Ay=za({displayName:To().min(1).max(80).nullable()}).nullable(),jy=xh(`apps.open`,1,ya(()=>Sh({open:Th,role:wh(Ch(Ay))}))),My=(e,t)=>e.require(jy).open(t);xh(`apps.call`,1,ya(()=>Sh({call:wh(Ch(Ba().transform(e=>Nn(e))))}))),$i()([],()=>(e,t,n)=>yo({try:()=>s_(e,n.onExcessProperty===`error`),catch:()=>new nr(t,e,n)}));var Ny={artifactRef:cv,digest:dv,version:G.pipe(V(y(1))),byteLength:Hi.pipe(V(Be()),V(L(0)),V(z(Number.isSafeInteger)))},Py=q({...Ny,mediaType:W([`text/html; charset=utf-8`,`application/vnd.fungi.app-assets+json`])}),Fy=q({...Ny,mediaType:K(`application/vnd.fungi.app-backend+json`)}),Iy={declaration:qt(J_)},Ly=J([q({format:K(`fungi-app-v1`),ui:Py,backend:Fy,...Iy}),q({format:K(`fungi-app-v1`),ui:Py,...Iy}),q({format:K(`fungi-app-v1`),backend:Fy,...Iy})]).pipe(V(z(e=>e.declaration?.api===void 0||`backend`in e,{message:`An App API requires a backend`})));p(Ly);var Ry=W([`invalid`,`undeclared_key`,`scope_not_declared`,`owner_required`,`too_large`,`quota_exceeded`,`conflict`,`unavailable`]),zy=class extends Error{code;constructor(e,t){super(e,t),this.code=e}},By=Li.check(L(0)),Vy=q({value:$r,revision:By}),Hy=q({value:$r,source:W([`member`,`team`,`none`]),team:Br(Vy),member:Br(Vy),canWriteTeam:r}),Uy={key:V_,scope:W(Wg),basedOn:Br(By)},Wy=q({...Uy,value:$r}),Gy=q(Uy),Ky=q({key:V_,scope:W(Wg),value:$r}),qy=q({value:$r,revision:By,claimed:r}),Jy=q({revision:By}),Yy=q({appId:G,key:V_,scope:W(Wg),revision:By}),Xy=J([q({kind:K(`accepted`),value:Hy}),q({kind:K(`rejected`),code:Ry})]),Zy=J([q({kind:K(`accepted`),value:Jy}),q({kind:K(`rejected`),code:Ry})]),Qy=J([q({kind:K(`accepted`),value:qy}),q({kind:K(`rejected`),code:Ry})]),$y=q({error:G});J([Xy,$y]),J([Zy,$y]);var eb=e=>Ch(Ba().transform(t=>ot(e,{onExcessProperty:`error`})(t))),tb=Sh({read:wh(eb(Xy)),write:wh(eb(Zy)),reset:wh(eb(Zy)),claim:wh(eb(Qy)),openEvents:wh(Eh)}),nb=e=>{if(e.kind===`rejected`)throw new zy(e.code);return e.value},rb=(e,t)=>{let n=A(e,{onExcessProperty:`error`})(t);if(n._tag===`Failure`)throw new zy(`invalid`,{cause:n.failure});return n.success},ib=e=>rb(V_,e);function ab(e){let t=async t=>nb(await e.read(ib(t)));return{read:t,write:async t=>nb(await e.write(rb(Wy,t))),reset:async t=>nb(await e.reset(rb(Gy,t))),claim:async t=>nb(await e.claim(rb(Ky,t))),async watch(n){let r=ib(n),i=await e.openEvents(r),a=!1,o=()=>a,s,c=!1,l=()=>c&&!o(),u,d=()=>void 0,f=()=>void 0,m=new Promise((e,t)=>{d=e,f=t}),h=new Eg(`https://app-storage.fungi.invalid/events`,{fetch:async(e,t)=>{let n=await i.fetch(new Request(e,t));if(!n.ok){let e=A(Xy)(await n.json()),t=new zy(e._tag===`Success`&&e.success.kind===`rejected`?e.success.code:`unavailable`);throw _(t),t}return n}}),g=()=>{a||(a=!0,h.close(),f(new zy(`unavailable`)),i.close().catch(e=>{os(`storage.watch.close`,e)}).finally(()=>{i[Symbol.dispose]()}))},_=e=>{f(e instanceof zy?e:new zy(`unavailable`,{cause:e})),!a&&u!==void 0&&os(`storage.watch`,e),g()},v=()=>{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=Sm(e);u=t,d({get:()=>t.get(),subscribe:e=>t.subscribe(e),close:g,[Symbol.dispose]:g})}else u.update(e)}})().catch(_).finally(()=>{s=void 0,c&&!a&&v()}))};return h.addEventListener(`ready`,v),h.addEventListener(`changed`,e=>{let t=A(p(Yy),{onExcessProperty:`error`})(e.data);t._tag===`Failure`?_(t.failure):t.success.key===r?v():_(new zy(`invalid`))}),h.onerror=e=>{(u===void 0||h.readyState===Eg.CLOSED)&&_(e)},m}}}var ob=xh(`app.storage`,1,ya(()=>tb.transform(ab))),sb=X.createContext(void 0);function cb(e){let t=X.useContext(sb);if(t===void 0&&!e)throw Error(rn(33));return t}var lb=X.createContext(void 0);function ub(e){let t=X.useContext(lb);if(t===void 0&&!e)throw Error(rn(36));return t}var db=X.createContext(void 0);function fb(e=!0){let t=X.useContext(db);if(t===void 0&&!e)throw Error(rn(25));return t}var pb=X.createContext(null);function mb(e=`root`){let t=X.useContext(pb),n=X.useContext(lb);return t===null||n===void 0?null:(e===`submenu-trigger`?n.virtualFocus||n.parentVirtualFocus:n.virtualFocus)?t:null}var hb={visible:!0,ref:null};function gb(){return hb}function _b(e,t,n=`root`){let r=mb(n),i=((n===`submenu-trigger`?r?.useSubmenuTrigger:r?.useItem)??gb)({label:e.label,children:e.children,render:e.render}),a=_i(t,i.ref);return{visible:i.visible,ref:a,props:i.props}}var vb=X.createContext(void 0);function yb(){let e=X.useContext(vb);if(e===void 0)throw Error(rn(30));return e}function bb(e){e.preventDefault()}function xb(e){let{closeOnClick:t,highlighted:n,id:r,nodeId:i,store:a,typingRef:o,itemRef:s,itemMetadata:c}=e,l=ub(),u=fb(!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 X.useMemo(()=>({id:r,role:`menuitem`,tabIndex:_,"aria-selected":p,onMouseDown:f?bb: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:C})},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&&!Fe&&e.button===2)return}s.current&&a.context.allowMouseUpTriggerRef.current&&(!g||e.button===2)&&c.type===`regular-item`&&ke(s.current,e,{detail:1,pointerType:`mouse`})}}),[t,_,r,m,i,a.context.allowMouseUpTriggerRef,o,s,u,g,c.type,p,f])}var Sb={type:`regular-item`};function Cb(e){let{closeOnClick:t,disabled:n,highlighted:r,id:i,store:a,typingRef:o=a.context.typingRef,nativeButton:s,itemMetadata:c,nodeId:l}=e,u=X.useRef(null),{getButtonProps:d,buttonRef:f}=bi({disabled:n,focusableWhenDisabled:!0,native:s,composite:!0}),p=xb({closeOnClick:t,highlighted:r,id:i,nodeId:l,store:a,typingRef:o,itemRef:u,itemMetadata:c}),m=X.useCallback(e=>me(p,{onMouseEnter(e){c.type===`submenu-trigger`&&c.setActive(e.nativeEvent)}},e,d),[p,d,c]),h=_i(u,f);return X.useMemo(()=>({getItemProps:m,itemRef:h}),[m,h])}var wb=X.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function Tb(){return X.useContext(wb)}function Eb(e={}){let{guess:t,label:n,metadata:r,textRef:i,index:a}=e,{register:o,unregister:s,subscribeMapChange:c,nextIndexRef:l}=Tb(),u=X.useRef(-1),[d,f]=X.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=X.useRef(null),h=X.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 pn(()=>{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 Db=`data-checked`,Ob=`data-unchecked`,kb={checked(e){return e?{[Db]:``}:{[Ob]:``}},...Re},Ab=X.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}=ub(),m=Eb({guess:!0,label:a}),h=It(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}=Cb({closeOnClick:c,disabled:b,highlighted:_,id:h,store:p,nativeButton:o,nodeId:v,itemMetadata:Sb}),w=X.useMemo(()=>({disabled:b,highlighted:_,checked:l}),[b,_,l]);function T(e){let t=Ht(C,e.nativeEvent,void 0,{preventUnmountOnClose:Me});u?.(!l,t)}let E=zt(`div`,e,{state:w,stateAttributesMapping:kb,props:[y,{role:`menuitemcheckbox`,"aria-checked":l,onClick:T},f,x],ref:[S,t,m.ref]});return(0,Q.jsx)(vb.Provider,{value:w,children:E})}),jb=X.forwardRef(function(e,t){let{checked:n,defaultChecked:r,onCheckedChange:i,...a}=e,[o,s]=ar({controlled:n,default:r??!1,name:`MenuCheckboxItem`,state:`checked`}),c=_b(e,t);function l(e,t){i?.(e,t),t.isCanceled||s(e)}return c.visible?(0,Q.jsx)(Ab,{...a,checked:o,onCheckedChange:l,ref:c.ref}):null}),Mb=X.forwardRef(function(e,t){let{render:n,className:r,style:i,keepMounted:a=!1,...o}=e,s=yb(),c=X.useRef(null),{transitionStatus:l,mounted:u,setMounted:d}=Ve(s.checked);pt({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 zt(`span`,e,{state:f,ref:[t,c],stateAttributesMapping:kb,props:{"aria-hidden":!0,...o},enabled:a||u})}),Nb=X.createContext(void 0);function Pb(){let e=X.useContext(Nb);if(e===void 0)throw Error(rn(31));return e}var Fb=X.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,s=It(a),c=Pb();return pn(()=>(c(s),()=>{c(e=>e===s?void 0:e)}),[c,s]),zt(`div`,e,{ref:t,props:{id:s,"aria-hidden":!0,...o}})}),Ib=X.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}=ub(),f=Eb({guess:!0,label:a}),p=It(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}=Cb({closeOnClick:c,disabled:v,highlighted:h,id:p,store:d,nativeButton:o,nodeId:g,itemMetadata:Sb});return zt(`div`,e,{state:{disabled:v,highlighted:h},props:[_,u,y],ref:[b,t,f.ref]})}),Lb=X.forwardRef(function(e,t){let n=_b(e,t);return n.visible?(0,Q.jsx)(Ib,{...e,ref:n.ref}):null});function Rb(e,t){return t!=null&&!st(t)?0:typeof e==`function`?e():e}function zb(e,t,n){let r=Rb(e,n);return typeof r==`number`?r:r?.[t]}function Bb(e){return typeof e==`function`?e():e}function Vb(e,t){return t||e===`click`||e===`mousedown`}function Hb(e){return e?.includes(`mouse`)&&e!==`mousedown`}var Ub=Math.min,Wb=Math.max,Gb=Math.round,Kb=Math.floor,qb=e=>({x:e,y:e}),Jb={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function Yb(e,t,n){return Wb(e,Ub(t,n))}function Xb(e,t){return typeof e==`function`?e(t):e}function Zb(e){return e.split(`-`)[0]}function Qb(e){return e.split(`-`)[1]}function $b(e){return e===`x`?`y`:`x`}function ex(e){return e===`y`?`height`:`width`}function tx(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function nx(e){return $b(tx(e))}function rx(e,t,n){n===void 0&&(n=!1);let r=Qb(e),i=nx(e),a=ex(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=fx(o)),[o,fx(o)]}function ix(e){let t=fx(e);return[ax(e),t,ax(t)]}function ax(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var ox=[`left`,`right`],sx=[`right`,`left`],cx=[`top`,`bottom`],lx=[`bottom`,`top`];function ux(e,t,n){switch(e){case`top`:case`bottom`:return n?t?sx:ox:t?ox:sx;case`left`:case`right`:return t?cx:lx;default:return[]}}function dx(e,t,n,r){let i=Qb(e),a=ux(Zb(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(ax)))),a}function fx(e){let t=Zb(e);return Jb[t]+e.slice(t.length)}function px(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function mx(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:px(e)}function hx(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 gx(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 _x(e){return e!=null&&e.clientX!=null}function vx(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=X.useRef(!1),l=X.useRef(null),[u,d]=X.useState(),[f,p]=X.useState([]),m=_t(t=>{e.set(`positionReference`,t)}),h=_t((t,n,i)=>{c.current||s.current.openEvent&&!_x(s.current.openEvent)||e.set(`positionReference`,gx(i??o,{x:t,y:n,axis:r,dataRef:s,pointerType:u}))}),g=_t(e=>{i?l.current||(h(e.clientX,e.clientY,e.currentTarget),p([])):h(e.clientX,e.clientY,e.currentTarget)}),_=st(u)?a:i;X.useEffect(()=>{if(!n){m(o);return}if(!_)return;function e(){l.current?.(),l.current=null}let t=ki(a);function r(t){let n=j(t);P(a,n)?e():h(t.clientX,t.clientY)}return!s.current.openEvent||_x(s.current.openEvent)?l.current=pi(t,`mousemove`,r):m(o),e},[_,n,a,s,o,e,h,m,f]),X.useEffect(()=>()=>{e.set(`positionReference`,null)},[e]),X.useEffect(()=>{n&&!a&&(c.current=!1)},[n,a]),X.useEffect(()=>{!n&&i&&(c.current=!0)},[n,i]);let v=X.useMemo(()=>{function e(e){d(e.pointerType)}return{onPointerDown:e,onPointerEnter:e,onMouseMove:g,onMouseEnter:g}},[g]);return X.useMemo(()=>n?{reference:v,trigger:v}:{},[n,v])}var yx=Fe&&ue;function bx(e,t={}){let{enabled:n=!0,delay:r}=t,{events:i,dataRef:a}=e.context,o=X.useRef(!1),s=X.useRef(null),c=X.useRef(!0),l=et();X.useEffect(()=>{let t=e.select(`domReferenceElement`);if(!n)return;let r=ki(t);function i(){let t=e.select(`domReferenceElement`);!e.select(`open`)&&Bi(t)&&t===ea(sn(t))&&(o.current=!0,s.current=t)}function a(){c.current=!0}function l(){c.current=!1}return tr(pi(r,`blur`,i),yx&&pi(r,`keydown`,a,!0),yx&&pi(r,`pointerdown`,l,!0))},[e,n]),X.useEffect(()=>{if(!n)return;function t(t){if(t.reason===`trigger-press`||t.reason===`escape-key`){let t=e.select(`domReferenceElement`);Rr(t)&&(s.current=t,o.current=!0)}}return i.on(`openchange`,t),()=>{i.off(`openchange`,t)}},[i,n,e]);let u=X.useMemo(()=>{function t(){o.current=!1,s.current=null}return{onMouseLeave(){t()},onFocus(n){let i=n.currentTarget;if(o.current){if(s.current===i)return;t()}let a=j(n.nativeEvent);if(Rr(a)){if(yx&&!n.relatedTarget){if(!c.current&&!Ji(a))return}else if(!fa(a))return}let u=cr(n.relatedTarget,e.context.triggerElements),{nativeEvent:f,currentTarget:p}=n;if(e.select(`open`)&&u||!r){e.setOpen(!0,Ht(d,f,p));return}l.start(r,()=>{o.current||e.setOpen(!0,Ht(d,f,p))})},onBlur(n){t();let r=n.relatedTarget,i=n.nativeEvent,o=Rr(r)&&r.hasAttribute(Xn(`focus-guard`))&&r.getAttribute(`data-type`)===`outside`;l.start(0,()=>{let t=e.select(`domReferenceElement`),n=ea(sn(t));!r&&n===t||P(a.current.floatingContext?.refs.floating.current,n)||P(t,n)||o||cr(r??n,e.context.triggerElements)||e.setOpen(!1,Ht(d,i))})}}},[a,r,e,l]);return X.useMemo(()=>n?{reference:u,trigger:u}:{},[n,u])}var xx=class e{pointerType=void 0;interactedInside=!1;handler=void 0;blockMouseMove=!0;performedPointerEventsMutation=!1;pointerEventsScopeElement=null;pointerEventsReferenceElement=null;pointerEventsFloatingElement=null;restTimeoutPending=!1;openChangeTimeout=new qe;restTimeout=new qe;handleCloseOptions=void 0;static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose},Sx=new WeakMap;function Cx(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&Sx.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),Sx.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function wx(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=Sx.get(n);a&&a!==e&&Cx(a),Cx(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,Sx.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function Tx(e){let t=e.context.dataRef.current,n=Ee(()=>t.hoverInteractionState??xx.create()).current;return t.hoverInteractionState||=n,b(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function Ex(e,t={}){let{enabled:n=!0,closeDelay:r=0,nodeId:i}=t,a=e.useState(`open`),o=e.useState(`floatingElement`),s=e.useState(`domReferenceElement`),{dataRef:c}=e.context,l=le(),u=Kt(),d=Tx(e),f=et(),p=_t(()=>Vb(c.current.openEvent?.type,d.interactedInside)),m=_t(()=>Hb(c.current.openEvent?.type)),h=_t(()=>{Cx(d)});pn(()=>{a||(d.pointerType=void 0,d.restTimeoutPending=!1,d.interactedInside=!1,h())},[a,d,h]),X.useEffect(()=>h,[h]),pn(()=>{if(n&&a&&d.handleCloseOptions?.blockPointerEvents&&m()&&Rr(s)&&o){let e=s,t=o,n=sn(o),r=l?.nodesRef.current.find(e=>e.id===u)?.context?.elements.floating;r&&(r.style.pointerEvents=``);let i=d.pointerEventsScopeElement===t?null:d.pointerEventsScopeElement,a=r===t?null:r,c=d.handleCloseOptions?.getScope?.()??i??a??Mt(e,`[data-rootownerid]`)??n.body;return wx(d,{scopeElement:c,referenceElement:e,floatingElement:t}),()=>{h()}}},[n,a,s,o,d,m,l,u,h]),X.useEffect(()=>{if(!n)return;function t(){return!!(l&&u&&Ri(l.nodesRef.current,u).length>0)}function a(t){let n=zb(r,`close`,d.pointerType),i=()=>{e.setOpen(!1,Ht(Dr,t)),l?.events.emit(`floating.closed`,t)};n?d.openChangeTimeout.start(n,i):(d.openChangeTimeout.clear(),i())}function s(e){let t=j(e);if(!gr(t)){d.interactedInside=!1;return}d.interactedInside=Mt(t,`[aria-haspopup]`)!=null}function g(){d.openChangeTimeout.clear(),f.clear(),l?.events.off(`floating.closed`,v),h()}function _(n){if(t()&&l){l.events.on(`floating.closed`,v);return}if(cr(n.relatedTarget,e.context.triggerElements))return;let r=c.current.floatingContext?.nodeId??i,o=n.relatedTarget;if(!(l&&r&&Rr(o)&&Ri(l.nodesRef.current,r,!1).some(e=>P(e.context?.elements.floating,o)))){if(d.handler){d.handler(n);return}h(),m()&&!p()&&a(n)}}function v(n){!l||!u||t()||f.start(0,()=>{l.events.off(`floating.closed`,v),e.setOpen(!1,Ht(Dr,n)),l.events.emit(`floating.closed`,n)})}let y=o;return tr(y&&pi(y,`mouseenter`,g),y&&pi(y,`mouseleave`,_),y&&pi(y,`pointerdown`,s,!0),()=>{l?.events.off(`floating.closed`,v)})},[n,o,e,c,r,i,m,p,h,d,l,u,f])}var Dx=e(Le(),1),Ox={current:null};function kx(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:i=null,mouseOnly:a=!1,restMs:o=0,move:s=!0,triggerElementRef:c=Ox,externalTree:l,isActiveTrigger:u=!0,getHandleCloseContext:d,isClosing:f,shouldOpen:p,guardStaleOpen:m=!1}=t,{dataRef:h,events:g}=e.context,_=le(l),v=Tx(e),y=X.useRef(!1),b=Gn(i),x=Gn(r),S=Gn(o),C=Gn(n),w=Gn(p),T=Gn(f),E=_t(()=>Vb(h.current.openEvent?.type,v.interactedInside)),D=_t(()=>w.current?.()!==!1),O=_t((t,n,r)=>{let i=e.context.triggerElements;if(i.hasElement(n))return!t||!P(t,n);if(!Rr(r))return!1;let a=r;return i.hasMatchingElement(e=>P(e,a))&&(!t||!P(t,a))}),k=_t(()=>{v.handler&&=(sn(e.select(`domReferenceElement`)).removeEventListener(`mousemove`,v.handler),void 0)}),A=_t(()=>{Cx(v)});return u&&(v.handleCloseOptions=i?.__options),X.useEffect(()=>k,[k]),X.useEffect(()=>{if(!n)return;function e(e){e.open?y.current=!1:(y.current=e.reason===Dr,k(),v.openChangeTimeout.clear(),v.restTimeout.clear(),v.blockMouseMove=!0,v.restTimeoutPending=!1)}return g.on(`openchange`,e),()=>{g.off(`openchange`,e)}},[n,g,v,k]),X.useEffect(()=>{if(!n)return;function t(t,n=!0){let r=zb(x.current,`close`,v.pointerType);r?v.openChangeTimeout.start(r,()=>{e.setOpen(!1,Ht(Dr,t)),_?.events.emit(`floating.closed`,t)}):n&&(v.openChangeTimeout.clear(),e.setOpen(!1,Ht(Dr,t)),_?.events.emit(`floating.closed`,t))}let r=c.current??(u?e.select(`domReferenceElement`):null);if(!Rr(r))return;function i(t){if(v.openChangeTimeout.clear(),v.blockMouseMove=!1,a&&!st(v.pointerType))return;let n=Bb(S.current),r=zb(x.current,`open`,v.pointerType),i=j(t),o=t.currentTarget??null,s=e.select(`domReferenceElement`),c=o;if(Rr(i)&&!e.context.triggerElements.hasElement(i)){for(let t of e.context.triggerElements.elements())if(P(t,i)){c=t;break}}Rr(o)&&Rr(s)&&!e.context.triggerElements.hasElement(o)&&P(o,s)&&(c=s);let l=c!=null&&O(s,c,i),u=e.select(`open`),d=T.current?.()??e.select(`transitionStatus`)===`ending`,f=!u&&d&&y.current,p=!l&&Rr(c)&&Rr(s)&&P(s,c)&&f,m=n>0&&!r,h=l&&(u||f)||p,g=!u||l;if(h){D()&&e.setOpen(!0,Ht(Dr,t,c));return}m||(r?v.openChangeTimeout.start(r,()=>{g&&D()&&e.setOpen(!0,Ht(Dr,t,c))}):g&&D()&&e.setOpen(!0,Ht(Dr,t,c)))}function o(n){if(E()){A();return}k();let r=e.select(`domReferenceElement`),i=sn(r);v.restTimeout.clear(),v.restTimeoutPending=!1;let a=h.current.floatingContext??d?.();if(!cr(n.relatedTarget,e.context.triggerElements)){if(b.current&&a){e.select(`open`)||v.openChangeTimeout.clear();let r=c.current;v.handler=b.current({...a,tree:_,x:n.clientX,y:n.clientY,onClose(){A(),k(),C.current&&!E()&&r===e.select(`domReferenceElement`)&&t(n,!0)}}),i.addEventListener(`mousemove`,v.handler),v.handler(n);return}(v.pointerType!==`touch`||!P(e.select(`floatingElement`),n.relatedTarget))&&t(n)}}function l(e){P(r,e.relatedTarget)||(v.openChangeTimeout.clear(),v.restTimeout.clear(),v.restTimeoutPending=!1)}let f=m?pi(r,`mouseout`,l):void 0;return s?tr(pi(r,`mousemove`,i,{once:!0}),pi(r,`mouseenter`,i),pi(r,`mouseleave`,o),f):tr(pi(r,`mouseenter`,i),pi(r,`mouseleave`,o),f)},[k,A,h,x,e,n,b,v,u,O,E,a,s,S,c,_,C,d,T,D,m]),X.useMemo(()=>{if(!n)return;function t(e){v.pointerType=e.pointerType}return{onPointerDown:t,onPointerEnter:t,onMouseMove(t){let{nativeEvent:n}=t,r=t.currentTarget,i=e.select(`domReferenceElement`),o=e.select(`open`),s=O(i,r,t.target);if(a&&!st(v.pointerType))return;if(o&&s&&v.handleCloseOptions?.blockPointerEvents){let t=e.select(`floatingElement`);if(t){let e=v.handleCloseOptions?.getScope?.()??r.ownerDocument.body;wx(v,{scopeElement:e,referenceElement:r,floatingElement:t})}}let c=Bb(S.current);if(o&&!s||c===0||!s&&v.restTimeoutPending&&t.movementX**2+t.movementY**2<2)return;v.restTimeout.clear();function l(){if(v.restTimeoutPending=!1,E())return;let t=e.select(`open`);!v.blockMouseMove&&(!t||s)&&D()&&e.setOpen(!0,Ht(Dr,n,r))}v.pointerType===`touch`?Dx.flushSync(()=>{l()}):s&&o?l():(v.restTimeoutPending=!0,v.restTimeout.start(c,l))}}},[n,v,E,O,a,e,S,D])}function Ax(e){return ue&&e.movementX===0&&e.movementY===0}function jx(e,t,n){switch(e){case`vertical`:return t;case`horizontal`:return n;default:return t||n}}function Mx(e,t){return jx(t,e===`ArrowUp`||e===`ArrowDown`,e===`ArrowLeft`||e===`ArrowRight`)}function Nx(e,t,n){return jx(t,e===`ArrowDown`,n?e===`ArrowLeft`:e===`ArrowRight`)||e===`Enter`||e===` `||e===``}function Px(e,t,n){return jx(t,n?e===oa:e===Et,e===Mn)}function Fx(e,t,n,r){return t===`both`||t===`horizontal`&&r?e===`Escape`:jx(t,n?e===Et:e===oa,e===E)}function Ix(e,t){let{listRef:n,activeIndex:r,onNavigate:i=()=>{},enabled:o=!0,selectedIndex:s=null,allowEscape:c=!1,loopFocus:l=!1,nested:u=!1,rtl:d=!1,virtual:f=!1,focusItemOnOpen:p=`auto`,focusItemOnHover:h=!0,openOnArrowKeyDown:g=!0,disabledIndices:_=void 0,orientation:v=`vertical`,triggerOrientation:y=v,parentOrientation:b,id:x,resetOnPointerLeave:S=!0,externalTree:C,nestedReturnFocusRef:w,grid:T}=t,E=T!=null,D=e.useState(`open`),O=e.useState(`floatingElement`),k=e.useState(`domReferenceElement`),A=e.context.dataRef,M=Jr(O),ee=bn(k),te=Gn(M),ne=Kt(),N=le(C),re=X.useRef(p),F=X.useRef(s??-1),I=X.useRef(null),ie=X.useRef(!0),L=_t(e=>{i(F.current===-1?null:F.current,e)}),ae=X.useRef(!!O),oe=X.useRef(D),se=X.useRef(!1),ce=X.useRef(!1),R=X.useRef(null),ue=Gn(_),de=Gn(D),fe=Gn(s),pe=Gn(S),me=_a(),he=_a(),z=_t(()=>{me.cancel();function e(e){f||(R.current=a(e,{sync:se.current,preventScroll:!0}))}let t=n.current[F.current],r=ce.current;t&&e(t),(se.current?e=>e():e=>me.request(e))(()=>{let i=n.current[F.current]||t;i&&(t||e(i),xe&&(r||!ie.current)&&i.scrollIntoView?.({block:`nearest`,inline:`nearest`}))})});pn(()=>{A.current.orientation=v},[A,v]),pn(()=>{D||(I.current=null),(!D||p!==`auto`)&&(re.current=p)},[D,p]),pn(()=>{o&&(D&&O?(F.current=s??-1,re.current&&s!=null&&(ce.current=!0,L())):ae.current&&(F.current=-1,L()))},[o,D,O,s,L]),pn(()=>{if(o){if(!D){se.current=!1;return}if(O){if(r==null){if(se.current=!1,fe.current!=null)return;if(ae.current&&(F.current=-1,z()),(!oe.current||!ae.current)&&re.current&&(I.current!=null||re.current===!0&&I.current==null)){let e=0,t=()=>{n.current[0]==null?(e<2&&(e?e=>he.request(e):queueMicrotask)(t),e+=1):(F.current=I.current==null||Nx(I.current,y,d)||u?En(n):Cr(n),I.current=null,L())};t()}}else Rn(n.current,r)||(F.current=r,z(),ce.current=!1)}}},[o,D,O,r,fe,u,n,y,d,L,z,he]),pn(()=>{if(!o||O||!N||f||!ae.current)return;let e=N.nodesRef.current,t=e.find(e=>e.id===ne)?.context?.elements.floating,n=ea(sn(k??t??null)),r=e.some(e=>e.context&&P(e.context.elements.floating,n));t&&!r&&ie.current&&t.focus({preventScroll:!0})},[o,O,k,N,ne,f]),pn(()=>{oe.current=D,ae.current=!!O});let ge=r!=null,_e=_t(e=>{if(!de.current)return;let t=n.current.indexOf(e.currentTarget);t!==-1&&(F.current!==t||r!==t)&&(F.current=t,L(e))}),ve=_t(()=>b??N?.nodesRef.current.find(e=>e.id===ne)?.context?.dataRef?.current.orientation),ye=_t(()=>En(n,ue.current)),be=_t(t=>{if(ie.current=!1,se.current=!0,t.which===229||!de.current&&t.currentTarget===te.current)return;if(u&&Fx(t.key,v,d,E)){Mx(t.key,ve())||Ar(t),e.setOpen(!1,Ht(kt,t.nativeEvent));let n=w?.current??k;Bi(n)&&n.focus();return}r!=null&&r!==F.current&&!Rn(n.current,r)&&(F.current=r);let i=F.current,a=En(n,_),o=Cr(n,_);if(ee||(t.key===`Home`&&(Ar(t),F.current=a,L(t)),t.key===`End`&&(Ar(t),F.current=o,L(t))),T!=null){let e=T(t,F.current,n,v,l,d,_,a,o);if(e!=null&&e!==F.current&&(F.current=e,L(t)),v===`both`)return}if(Mx(t.key,v)){Ar(t);let e=ea(t.currentTarget.ownerDocument);if(D&&!f&&P(t.currentTarget,e)&&!n.current.some(t=>t!=null&&P(t,e))){F.current=Nx(t.key,v,d)?a:o,L(t),r===F.current&&z();return}let{index:s,wrapped:u}=si(n.current,i,{decrement:!Nx(t.key,v,d),loopFocus:l,allowEscape:c,disabledIndices:_,minIndex:a,maxIndex:o});u&&(se.current=!1),F.current=s,L(t)}}),xe=X.useMemo(()=>({onFocus(e){se.current=!0,_e(e)},onClick({currentTarget:e}){f||e.focus({preventScroll:!0})},onMouseMove(e){Ax(e)||(se.current=!0,ce.current=!1,h&&_e(e))},onPointerLeave(e){if(!de.current||!ie.current||e.pointerType===`touch`)return;se.current=!0;let t=e.relatedTarget;if(!(!h||n.current.includes(t))&&pe.current&&(R.current?.(),R.current=null,F.current=-1,L(e),!f)){let e=te.current,t=ea(sn(e));e&&P(e,t)&&e.focus({preventScroll:!0})}}}),[_e,de,te,h,n,L,pe,f]),Se=X.useMemo(()=>f&&D&&ge&&{"aria-activedescendant":`${x}-${r}`},[f,D,ge,x,r]),Ce=X.useMemo(()=>({...ee?{}:Se,onKeyDown(t){if(t.key===`Tab`&&t.shiftKey&&D&&!f){let n=j(t.nativeEvent);if(n&&!P(te.current,n))return;Ar(t);let r=Ht(ra,t.nativeEvent);e.setOpen(!1,r);let i=w?.current??k;!r.isCanceled&&Bi(i)&&i.focus();return}be(t)},onPointerMove(e){Ax(e)||(ie.current=!0)}}),[Se,be,te,ee,e,D,f,k,w]),we=X.useMemo(()=>{function t(t){e.setOpen(!0,Ht(kt,t.nativeEvent,t.currentTarget))}function n(e){p===`auto`&&Ir(e.nativeEvent)&&(re.current=!f)}function r(e){re.current=p,p===`auto`&&m(e.nativeEvent)&&(re.current=!0)}return{onKeyDown(n){let r=e.select(`open`);ie.current=!1;let i=n.key.startsWith(`Arrow`),a=Px(n.key,ve(),d),o=Mx(n.key,r?v:y),s=(u?a:o)||n.key===`Enter`||n.key.trim()===``;if(f&&r&&(!u||Ji(n.currentTarget)))return be(n);if(!(!r&&!g&&i)){if(s){let e=Mx(n.key,ve());I.current=u&&e?null:n.key}if(u){a&&(Ar(n),r?(F.current=ye(),L(n),f&&te.current?.focus()):t(n));return}o&&(fe.current!=null&&(F.current=fe.current),Ar(n),!r&&g?t(n):be(n),r&&L(n))}},onFocus(t){t.target===t.currentTarget&&e.select(`open`)&&!f&&(F.current=-1,L(t))},onPointerDown:r,onPointerEnter:r,onMouseDown:n,onClick:n}},[be,p,ye,u,L,e,g,v,y,ve,d,fe,f,te]),Te=X.useMemo(()=>({...Se,...we}),[Se,we]);return X.useMemo(()=>o?{reference:Te,floating:Ce,item:xe,trigger:we}:{},[o,Te,Ce,we,xe])}function Lx(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=_t(s),f=e.useState(`open`),p=et(),m=X.useRef(``),h=X.useRef(u??i??-1),g=X.useRef(null),_=_t(e=>{function t(e){return r?.current[e]}function s(e){let n=t(e);return n&&!Mi(n)||n?.matches(`:disabled`)?!1:o==null||!Vr(Gt,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===` `&&(Ar(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!==` `&&(Ar(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=_t(t=>{let n=t.relatedTarget,r=e.select(`domReferenceElement`),i=e.select(`floatingElement`);P(r,n)||P(i,n)||(p.clear(),m.current=``,h.current=g.current,d?.(!1))});pn(()=>{!f&&u!==null||(p.clear(),g.current=null,m.current!==``&&(m.current=``,d?.(!1)))},[f,u,p,d]);let y=X.useMemo(()=>({onKeyDown:_,onBlur:v}),[_,v]);return X.useMemo(()=>c?{reference:y,floating:y}:{},[c,y])}var Rx=.1,zx=Rx*Rx,Bx=.5;function Vx(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function Hx(e,t,n,r,i,a,o,s,c,l){let u=!1;return Vx(e,t,n,r,i,a)&&(u=!u),Vx(e,t,i,a,o,s)&&(u=!u),Vx(e,t,o,s,c,l)&&(u=!u),Vx(e,t,c,l,n,r)&&(u=!u),u}function Ux(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function Wx(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 Gx(e={}){let{blockPointerEvents:t=!1}=e,n=new qe,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*zx;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=j(r),g=r.type===`mouseleave`,_=P(u,h),v=P(a,h);if(_&&(l=!0,!g))return;if(v&&(l=!1,!g)){l=!0;return}if(g&&Rr(r.relatedTarget)&&P(u,r.relatedTarget))return;function y(){return!!(s&&Ri(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 M=!1;switch(c){case`top`:M=Wx(d,f,D,x.top+1,O,S.bottom-1);break;case`bottom`:M=Wx(d,f,D,S.top+1,O,x.bottom-1);break;case`left`:M=Wx(d,f,S.right-1,A,x.left+1,k);break;case`right`:M=Wx(d,f,x.right-1,A,S.left+1,k)}if(M)return;if(l&&!Ux(d,f,x)){b();return}if(!g&&p(d,f)){b();return}let ee=!1;switch(c){case`top`:{let n=T?Bx/2:Bx*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t+Bx+1,o=C||T?S.bottom-Bx:S.top,s=C?T?S.bottom-Bx:S.top:S.bottom-Bx;ee=Hx(d,f,r,a,i,a,S.left,o,S.right,s);break}case`bottom`:{let n=T?Bx/2:Bx*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t-Bx,o=C||T?S.top+Bx:S.bottom,s=C?T?S.top+Bx:S.bottom:S.top+Bx;ee=Hx(d,f,r,a,i,a,S.left,o,S.right,s);break}case`left`:{let n=E?Bx/2:Bx*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e+Bx+1,o=w||E?S.right-Bx:S.left,s=w?E?S.right-Bx:S.left:S.right-Bx;ee=Hx(d,f,o,S.top,s,S.bottom,a,r,a,i);break}case`right`:{let n=E?Bx/2:Bx*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e-Bx,o=w||E?S.left+Bx:S.right,s=w?E?S.left+Bx:S.right:S.left+Bx;ee=Hx(d,f,a,r,a,i,o,S.top,s,S.bottom);break}}ee?l||n.start(40,b):b()}};return r.__options={...e,blockPointerEvents:t},r}function Kx(e,t,n){let{reference:r,floating:i}=e,a=tx(t),o=nx(t),s=ex(o),c=Zb(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=Qb(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function qx(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}=Xb(t,e),p=mx(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=hx(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=hx(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 Jx=50,Yx=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:qx},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=Kx(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<Jx&&(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}=Kx(l,f,c)),n=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:m}},Xx=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}=Xb(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let g=Zb(r),_=tx(o),v=Zb(o)===o,y=await(s.isRTL==null?void 0:s.isRTL(c.floating)),b=d||(v||!m?[fx(o)]:ix(o)),x=p!==`none`;!d&&x&&b.push(...dx(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=rx(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`||_===tx(t)||T.every(e=>tx(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=tx(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{}}}},Zx=new Set([`left`,`top`]);async function Qx(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=Zb(n),s=Qb(n),c=tx(n)===`y`,l=Zx.has(o)?-1:1,u=a&&c?-1:1,d=Xb(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 $x=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 Qx(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}}}}},eS=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}=Xb(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=tx(i),p=$b(f),m=u[p],h=u[f],g=(e,t)=>Yb(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}}}}}},tS=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}=Xb(e,t),u={x:n,y:r},d=tx(i),f=$b(d),p=u[f],m=u[d],h=Xb(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=Zx.has(Zb(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}}}},nS=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}=Xb(e,t),c=await i.detectOverflow(t,s),l=Zb(n),u=Qb(n),d=tx(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=Ub(p-c[m],g),y=Ub(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*Wb(c.left,c.right):S=p-2*Wb(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 rS(e){let t=s(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=Bi(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,c=Gb(n)!==a||Gb(r)!==o;return c&&(n=a,r=o),{width:n,height:r,$:c}}function iS(e){return Rr(e)?e:e.contextElement}function aS(e){let t=iS(e);if(!Bi(t))return qb(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=rS(t),o=(a?Gb(n.width):n.width)/r,s=(a?Gb(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var oS=qb(0);function sS(e){let t=ki(e);return!pr()||!t.visualViewport?oS:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function cS(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===ki(e)}function lS(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=iS(e),o=qb(1);t&&(r?Rr(r)&&(o=aS(r)):o=aS(e));let c=cS(a,n,r)?sS(a):qb(0),l=(i.left+c.x)/o.x,u=(i.top+c.y)/o.y,d=i.width/o.x,f=i.height/o.y;if(a&&r){let e=ki(a),t=Rr(r)?ki(r):r,n=e,i=Qr(n);for(;i&&t!==n;){let e=aS(i),t=i.getBoundingClientRect(),r=s(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,u*=e.y,d*=e.x,f*=e.y,l+=a,u+=o,n=ki(i),i=Qr(n)}}return hx({width:d,height:f,x:l,y:u})}function uS(e,t){let n=xr(e).scrollLeft;return t?t.left+n:lS(Ii(e)).left+n}function dS(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-uS(e,n),y:n.top+t.scrollTop}}function fS(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=Ii(r),s=t?Gr(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=qb(1),u=qb(0),d=Bi(r);if((d||!a)&&((Ci(r)!==`body`||$n(o))&&(c=xr(r)),d)){let e=lS(r);l=aS(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?dS(o,c):qb(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 pS(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function mS(e){let t=xr(e),n=e.ownerDocument.body,r=Wb(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Wb(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+uS(e),o=-t.scrollTop;return s(n).direction===`rtl`&&(a+=Wb(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var hS=25;function gS(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=ki(e),a=Ii(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!pr()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(uS(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<=hS&&(s-=o)}return{width:s,height:c,x:l,y:u}}function _S(e,t){let n=lS(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=aS(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function vS(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=gS(e,n,t);else if(t===`document`)r=mS(Ii(e));else if(Rr(t))r=_S(t,n);else{let n=sS(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return hx(r)}function yS(e,t){let n=t.get(e);if(n)return n;let r=wn(e,[],!1).filter(e=>Rr(e)&&Ci(e)!==`body`),i=null,a=s(e).position===`fixed`,o=a?ai(e):e;for(;Rr(o)&&!Hn(o);){let e=s(o),t=Fn(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=ai(o)}return t.set(e,r),r}function bS(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?Gr(t)?[]:yS(t,this._c):[].concat(n),r],o=vS(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=vS(t,a[e],i);s=Wb(n.top,s),c=Ub(n.right,c),l=Ub(n.bottom,l),u=Wb(n.left,u)}return{width:c-u,height:l-s,x:u,y:s}}function xS(e){let{width:t,height:n}=rS(e);return{width:t,height:n}}function SS(e,t,n){let r=Bi(t),i=Ii(t),a=n===`fixed`,o=lS(e,!0,a,t),s={scrollLeft:0,scrollTop:0},c=qb(0);if((r||!a)&&((Ci(t)!==`body`||$n(i))&&(s=xr(t)),r)){let e=lS(t,!0,a,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}!r&&i&&(c.x=uS(i));let l=i&&!r&&!a?dS(i,s):qb(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 CS(e){return s(e).position===`static`}function wS(e,t){if(!Bi(e)||s(e).position===`fixed`)return null;if(t)return t(e);let n=e.offsetParent;return Ii(e)===n&&(n=n.ownerDocument.body),n}function TS(e,t){let n=ki(e);if(Gr(e))return n;if(!Bi(e)){let t=ai(e);for(;t&&!Hn(t);){if(Rr(t)&&!CS(t))return t;t=ai(t)}return n}let r=wS(e,t);for(;r&&di(r)&&CS(r);)r=wS(r,t);return r&&Hn(r)&&CS(r)&&!Fn(r)?n:r||Jn(e)||n}var ES=async function(e){let t=this.getOffsetParent||TS,n=this.getDimensions,r=await n(e.floating);return{reference:SS(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function DS(e){return s(e).direction===`rtl`}var OS={convertOffsetParentRelativeRectToViewportRelativeRect:fS,getDocumentElement:Ii,getClippingRect:bS,getOffsetParent:TS,getElementRects:ES,getClientRects:pS,getDimensions:xS,getScale:aS,isElement:Rr,isRTL:DS};function kS(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function AS(e,t,n){let r=null,i,a=Ii(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=Kb(d),h=Kb(a.clientWidth-(u+f)),g=Kb(a.clientHeight-(d+p)),_=Kb(u),v={rootMargin:-m+`px `+-h+`px `+-g+`px `+-_+`px`,threshold:Wb(0,Ub(1,c))||1},y=!0;function b(t){let n=t[0].intersectionRatio;if(!kS(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=ki(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function jS(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=iS(e),u=i||a?[...l?wn(l):[],...t?wn(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?AS(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?lS(e):null;c&&g();function g(){let t=lS(e);h&&!kS(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 MS=$x,NS=eS,PS=Xx,FS=nS,IS=tS,LS=(e,t,n)=>{let r=new Map,i=n??{},a={...OS,...i.platform,_c:r};return Yx(e,t,{...i,platform:a})},RS=typeof document<`u`?X.useLayoutEffect:function(){};function zS(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(!zS(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)&&!zS(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function BS(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function VS(e,t){let n=BS(e);return Math.round(t*n)/n}function HS(e){let t=X.useRef(e);return RS(()=>{t.current=e}),t}function US(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]=X.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=X.useState(r);zS(f,r)||p(r);let[m,h]=X.useState(null),[g,_]=X.useState(null),v=X.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=X.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=X.useRef(null),C=X.useRef(null),w=X.useRef(u),T=c!=null,E=HS(c),D=HS(i),O=HS(l),k=X.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),LS(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};A.current&&!zS(w.current,t)&&(w.current=t,Dx.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);RS(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let A=X.useRef(!1);RS(()=>(A.current=!0,()=>{A.current=!1}),[]),RS(()=>{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=X.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),M=X.useMemo(()=>({reference:b,floating:x}),[b,x]),ee=X.useMemo(()=>{let e={position:n,left:0,top:0};if(!M.floating)return e;let t=VS(M.floating,u.x),r=VS(M.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...BS(M.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,M.floating,u.x,u.y]);return X.useMemo(()=>({...u,update:k,refs:j,elements:M,floatingStyles:ee}),[u,k,j,M,ee])}var WS=(e,t)=>{let n=MS(e);return{name:n.name,fn:n.fn,options:[e,t]}},GS=(e,t)=>{let n=NS(e);return{name:n.name,fn:n.fn,options:[e,t]}},KS=(e,t)=>({fn:IS(e).fn,options:[e,t]}),qS=(e,t)=>{let n=PS(e);return{name:n.name,fn:n.fn,options:[e,t]}},JS=(e,t)=>{let n=FS(e);return{name:n.name,fn:n.fn,options:[e,t]}},YS=X.createContext(void 0);function XS(e){let t=X.useContext(YS);if(t===void 0&&!e)throw Error(rn(69));return t}function ZS(e){return e===`starting`?Zt:ce}var QS=X.createContext(void 0);function $S(){return X.useContext(QS)}function eC(e,t){let n=_(e.render);if(X.isValidElement(n)){let e=n.props;if(Object.hasOwn(e,`id`))return e.id??``}return e.id??t}function tC(e,t,n){let r=eC(e,t),i=r===t?void 0:r;return[r,X.useCallback(e=>n?.(e?i:void 0),[i,n])]}function nC(e,t,n){let r=_(e.render),i=X.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 rC=X.forwardRef(function(e,t){let{render:n,className:r,style:i,finalFocus:a,id:o,initialFocus:s,...c}=e,{store:l,defaultFloatingId:u,setRenderedFloatingId:d,virtualFocus:f,orientation:p}=ub(),m=$S(),{side:h,align:g}=cb(),_=XS(!0)!=null,y=l.useState(`open`),b=l.useState(`transitionStatus`),x=l.useState(`popupProps`),S=l.useState(`mounted`),C=l.useState(`instantType`),w=l.useState(`activeTriggerElement`),T=l.useState(`parent`),E=l.useState(`lastOpenChangeReason`),D=l.useState(`rootId`),O=l.useState(`floatingRootContext`),k=l.useState(`floatingTreeRoot`),A=l.useState(`closeDelay`),j=l.useState(`hoverEnabled`),M=l.useState(`disabled`),ee=l.useState(`openMethod`),te=l.useState(`activeTriggerId`),ne=l.useState(`listElement`),[N,P]=tC(e,u,d),re=nC(e,w,te),F=T.type===`menu`?m:void 0,I=T.type===`context-menu`,ie=s??T.type!==`menu`;s===void 0&&ne&&T.type!==`menu`&&(ie=()=>l.state.activeIndex===null&&ne),pt({open:y,ref:l.context.popupRef,onComplete(){y&&l.context.onOpenChangeComplete?.(!0)}}),X.useEffect(()=>{function e(e){l.setOpen(!1,Ht(e.reason,e.domEvent))}return k.events.on(`close`,e),()=>{k.events.off(`close`,e)}},[k.events,l]),Ex(O,{enabled:j&&!M&&!I&&T.type!==`menubar`,closeDelay:A});let L=l.useStateSetter(`popupElement`),{parentVirtualFocusRef:ae,handleFocus:oe}=(X.useContext(pb)?.useParentHandoff??aC)(l,T,y,f),se={transitionStatus:b,side:h,align:g,open:y,nested:T.type===`menu`,instant:C},ce=zt(`div`,e,{state:se,ref:[t,l.context.popupRef,L,P],stateAttributesMapping:ut,props:[x,{id:N,...ne?{role:`presentation`}:{role:`menu`,"aria-orientation":p===`horizontal`?`horizontal`:void 0,"aria-labelledby":re},onKeyDown(e){F?.onPopupKeyDown?.(e),_&&or.has(e.key)&&e.stopPropagation()},onFocus:oe},ZS(b),c,{"data-rootownerid":D}]}),le=T.type===void 0||I;(w||T.type===`menubar`&&E!==`outside-press`)&&(le=!0);let R=F?.getReturnElement??ae;return(0,Q.jsx)(v,{context:O,openInteractionType:ee,modal:I,disabled:!S,returnFocus:a??R??le,explicitReturnFocus:a===void 0&&R?!1:void 0,initialFocus:ie,restoreFocus:!0,getInsideElements:T.type===void 0?()=>[l.context.beforeTriggerFocusGuardRef.current]:void 0,externalTree:T.type===`menubar`?void 0:k,previousFocusableElement:w,nextFocusableElement:T.type===void 0?l.context.triggerFocusTargetRef:void 0,beforeContentFocusGuardRef:l.context.beforeContentFocusGuardRef,children:ce})}),iC={parentVirtualFocusRef:void 0,handleFocus:void 0};function aC(){return iC}var oC=X.forwardRef(function(e,t){let n=mb()?.Popup??rC;return(0,Q.jsx)(n,{...e,ref:t})}),sC=X.createContext(void 0);function cC(){let e=X.useContext(sC);if(e===void 0)throw Error(rn(32));return e}var lC=X.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,{store:i,parent:a}=ub();if(!(i.useState(`mounted`)||n))return null;let o=a.type===`menu`||a.type===`menubar`?`group`:void 0;return(0,Q.jsx)(sC.Provider,{value:n,children:(0,Q.jsx)(vi,{ref:t,...r,portalOwnerRole:o})})});function uC(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]=X.useState(null),d=X.useRef(null),f=le(n),p=X.useMemo(()=>({reference:i,floating:a,domReference:o}),[i,a,o]),m=US({...e,elements:{...p,...l&&{reference:l}}}),h=X.useCallback(e=>{let t=Rr(e)?{getBoundingClientRect:()=>e.getBoundingClientRect(),getClientRects:()=>e.getClientRects(),contextElement:e}:e;u(t),m.refs.setReference(t)},[m.refs]),g=X.useMemo(()=>({...m.refs,setPositionReference:h,domReference:d}),[m.refs,h]),_=X.useMemo(()=>({...m.elements,domReference:o}),[m.elements,o]),v=X.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 pn(()=>{o&&(d.current=o)},[o]),pn(()=>{r.context.dataRef.current.floatingContext=v;let e=f?.nodesRef.current.find(e=>e.id===t);e&&(e.context=v)}),X.useMemo(()=>({...m,context:v,refs:g,elements:_,rootStore:r}),[m,g,_,v,r])}var dC=X.createContext(void 0);function fC(){return X.useContext(dC)?.direction??`ltr`}var pC=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}=Xb(e,t)||{};if(l==null)return{};let d=mx(u),f={x:n,y:r},p=nx(i),m=ex(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=Yb(D,k,O),j=!c.arrow&&Qb(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}}}),mC=(e,t)=>{let{name:n,fn:r}=pC(e);return{name:n,fn:r,options:[e,t]}},hC={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}}}},gC={sideX:`left`,sideY:`top`},_C=`--available-width`,vC=`--available-height`,yC=`--anchor-width`,bC=`--anchor-height`,xC=`--transform-origin`,SC=_C,CC=vC;function wC(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 TC(e,t,n){let{rects:r,placement:i}=e;return{side:wC(t,Zb(i),n),align:Qb(i)||`center`,anchor:{width:r.reference.width,height:r.reference.height},positioner:{width:r.floating.width,height:r.floating.height}}}function EC(e){return DC(e,uC)}function DC(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=_t(O),A=O?k:n,j=Gn(n),M=Gn(g),ee=fC()===`rtl`,[te,ne]=X.useState(null);!g&&te!==null&&ne(null);let N=x===`placement`,P=te?Zb(te):null,re=te&&N?Qb(te)||`center`:null,F=P||{top:`top`,right:`right`,bottom:`bottom`,left:`left`,"inline-end":ee?`left`:`right`,"inline-start":ee?`right`:`left`}[i],I=re||o,ie=I===`center`?F:`${F}-${I}`,L=l;typeof L==`number`?L={top:L,right:L,bottom:L,left:L}:L&&={top:L.top||0,right:L.right||0,bottom:L.bottom||0,left:L.left||0};let ae=+(i===`bottom`),oe=+(i===`top`),se=+(i===`right`),ce=+(i===`left`),le={boundary:c===`clipping-ancestors`?`clippingAncestors`:c,padding:L},R=X.useRef(null),ue=Gn(a),de=Gn(s),fe=typeof a==`function`?0:a,pe=typeof s==`function`?0:s,me=[];p&&me.push(p),me.push(WS(e=>{let t=TC(e,i,ee),n=typeof ue.current==`function`?ue.current(t):ue.current,r=typeof de.current==`function`?de.current(t):de.current;return{mainAxis:n,crossAxis:r,alignmentAxis:r}},[fe,pe,ee,i]));let he=w===`none`&&C!==`shift`,z=!he&&(u||E||C===`shift`),ge=C===`none`?null:qS({...le,padding:{top:L.top+1+ae,right:L.right+1+ce,bottom:L.bottom+1+oe,left:L.left+1+se},mainAxis:!E&&C===`flip`,crossAxis:w===`flip`&&`alignment`,fallbackAxisSideDirection:T}),_e=he?null:GS({...le,rootBoundary:D,mainAxis:w!==`none`,crossAxis:z,limiter:u||E?void 0:KS(e=>{if(!R.current)return{};let{width:t,height:n}=R.current.getBoundingClientRect(),r=tx(Zb(e.placement)),i=r===`y`?t:n,a=r===`y`?L.left+L.right:L.top+L.bottom;return{offset:i/2+a/2}})},[le,u,E,D,L,w]);C===`shift`||w===`shift`||I===`center`?me.push(_e,ge):me.push(ge,_e),me.push(JS({...le,apply({elements:{floating:e},availableWidth:t,availableHeight:n,rects:r}){if(!M.current)return;let i=e.style;i.setProperty(SC,`${t}px`),i.setProperty(CC,`${n}px`);let a=ki(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(yC,`${u}px`),i.setProperty(bC,`${d}px`)}}),mC(e=>({element:R.current||sn(e.elements.floating).createElement(`div`),padding:R.current?d:0}),[d]),{name:`transformOrigin`,fn(e){let{elements:{floating:t},middlewareData:n,placement:r,platform:o,rects:s,y:c}=e,l=Zb(r),u=Qb(r),d=tx(l)===`y`,f=R.current,p=typeof a==`function`?a(TC(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 z&&d&&Math.abs(n.shift?.y||0)>p&&(h=`${s.reference.y+s.reference.height/2-c}px`),t.style.setProperty(xC,d?`${m} ${h}`:`${h} ${m}`),{}}},hC,b),pn(()=>{!g&&h&&h.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[g,h]);let ve=X.useMemo(()=>({ancestorScroll:!f,elementResize:!f&&typeof ResizeObserver<`u`,layoutShift:!f&&typeof IntersectionObserver<`u`}),[f]),{refs:ye,elements:be,x:xe,y:Se,middlewareData:Ce,update:we,placement:Te,context:Ee,isPositioned:De,floatingStyles:Oe}=t({rootContext:h,open:m?g:void 0,placement:ie,middleware:me,strategy:r,whileElementsMounted:m?void 0:(...e)=>jS(...e,ve),nodeId:y,externalTree:S}),{sideX:ke,sideY:Ae}=Ce.adaptiveOrigin||gC,je=De?r:`fixed`,Me=X.useMemo(()=>{let e;return e=De?b?{position:je,[ke]:xe,[Ae]:Se}:{...Oe,position:je}:{position:je,top:0,left:0},e[SC]=`100vw`,e[CC]=`100vh`,De||(e.opacity=0),e},[b,je,ke,xe,Ae,Se,Oe,De]),Ne=X.useRef(null);pn(()=>{if(!g)return;let e=j.current,t=typeof e==`function`?e():e,n=(OC(t)?t.current:t)||null;n!==Ne.current&&(ye.setPositionReference(n),Ne.current=n)},[g,ye,A,j]),X.useEffect(()=>{if(!g)return;let e=j.current;typeof e!=`function`&&OC(e)&&e.current!==Ne.current&&(ye.setPositionReference(e.current),Ne.current=e.current)},[g,ye,A,j]),X.useEffect(()=>{if(m&&g&&be.reference&&be.floating)return jS(be.reference,be.floating,we,ve)},[m,g,be,we,ve]);let Pe=Zb(Te),Fe=wC(i,Pe,ee),Ie=Qb(Te)||`center`,Le=!!Ce.hide?.referenceHidden;pn(()=>{x&&g&&De&&(Pe!==F||N&&Ie!==I)&&ne(Te)},[x,N,g,De,Te,Pe,Ie,F,I]);let Re=X.useMemo(()=>({position:`absolute`,top:Ce.arrow?.y,left:Ce.arrow?.x}),[Ce.arrow]),ze=Ce.arrow?.centerOffset!==0;return X.useMemo(()=>({positionerStyles:Me,arrowStyles:Re,arrowRef:R,arrowUncentered:ze,side:Fe,align:Ie,physicalSide:Pe,anchorHidden:Le,refs:ye,context:Ee,isPositioned:De,update:we}),[Me,Re,R,ze,Fe,Ie,Pe,Le,ye,Ee,De,we])}function OC(e){return e!=null&&`current`in e}function kC(e){let{children:t,elementsRef:n,labelsRef:r,onMapChange:i}=e,a=_t(i),[,o]=X.useState(0),s=Ee(jC).current,c=Ee(AC).current,l=X.useRef(0),u=X.useRef(!0),d=X.useRef(null),f=X.useRef(null),p=_t(()=>{u.current||(u.current=!0,o(e=>e+1))}),m=_t((e,t)=>{c.set(e,t),p()}),h=_t(e=>{c.delete(e),p()}),g=_t(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(!PC(n))return;let r=null;for(let n of e)if(n.isConnected){if(r&&FC(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=NC(e[t-1],e[t]);r&&n.add(r)}n.forEach(e=>t.observe(e,{childList:!0}))}let v=_t(()=>{let[e,t]=MC(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))});pn(()=>(!u.current&&d.current&&g(d.current),()=>{n.current=[],r&&(r.current=[])}),[n,r,g]),pn(()=>{u.current&&v()}),pn(()=>()=>{f.current?.disconnect(),u.current=!0},[]);let y=_t(e=>(s.add(e),()=>{s.delete(e)})),b=X.useMemo(()=>({register:m,unregister:h,subscribeMapChange:y,nextIndexRef:l}),[m,h,y,l]);return(0,Q.jsx)(wb.Provider,{value:b,children:t})}function AC(){return new Map}function jC(){return new Set}function MC(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)=>FC(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 NC(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function PC(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 FC(e,t){return e.nextElementSibling===t?-1:t.nextElementSibling===e?1:e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function IC(e){let{store:t,domReference:n,positionerElement:r,open:i}=e,a=X.useRef(null),o=X.useRef(null),s=ae(r);pn(()=>{i||(o.current?.abort(),o.current=null,t.state.instantType===`trigger-change`&&t.set(`instantType`,void 0))},[i,t]),pn(()=>{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 LC(e,t,{styles:n,transitionStatus:r,props:i,refs:a,hidden:o,inert:s=!1}){let c={...n};return s&&(c.pointerEvents=`none`),zt(`div`,e,{state:t,ref:a,props:[{role:`presentation`,hidden:o,style:c},ZS(r),i],stateAttributesMapping:Ze})}var RC=20;function zC(e,t,n,r){let[i,a]=X.useState(!1);pn(()=>{if(!e||!t||n==null){a(!1);return}let r=sn(n).documentElement.clientWidth,i=n.offsetWidth;a(r>0&&i>0&&i>=r-RC)},[e,t,n]),fi(e&&(!t||i),r)}var BC=X.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=dn,style:g,..._}=e,{store:v,virtualFocus:y,syncHighlightedItem:b}=ub(),x=cC(),S=fb(!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`),k=v.useState(`openMethod`),A=v.useState(`activeTriggerElement`),j=v.useState(`transitionStatus`),M=v.useState(`positionerElement`),ee=v.useState(`instantType`),te=v.useState(`adaptiveOrigin`),ne=v.useState(`lastOpenChangeReason`),N=v.useState(`floatingNodeId`),P=v.useState(`floatingParentNodeId`),re=w.useState(`domReferenceElement`),F=n,I=c,ie=l,L=s,ae=h;C.type===`context-menu`&&(F=n??C.context?.anchor,L??=`start`,!o&&L!==`center`&&(ie=e.alignOffset??2,I=e.sideOffset??-5));let oe=o,se=L;C.type===`menu`?(oe??=`inline-end`,se??=`start`,ae=e.collisionAvoidance??ht):C.type===`menubar`&&(oe??=C.context.orientation===`vertical`?`inline-end`:`bottom`,se??=`start`);let ce=C.type===`context-menu`,le=EC({anchor:F,floatingRootContext:w,positionMethod:S?`fixed`:r,mounted:E,side:oe,sideOffset:I,align:se,alignOffset:ie,arrowPadding:ce?0:f,collisionBoundary:u,collisionPadding:d,sticky:p,nodeId:N,keepMounted:x,disableAnchorTracking:m,collisionAvoidance:ae,shift:ce?{crossAxis:!(`side`in ae&&ae.side===`flip`),rootBoundary:`layoutViewport`}:void 0,externalTree:T,adaptiveOrigin:te,lazyFlip:y?`placement`:!1});X.useEffect(()=>{function e(e){e.open&&(e.parentNodeId===N&&v.set(`hoverEnabled`,!1),e.nodeId!==N&&e.parentNodeId===v.select(`floatingParentNodeId`)&&v.setOpen(!1,Ht(Pr)))}return T.events.on(`menuopenchange`,e),()=>{T.events.off(`menuopenchange`,e)}},[v,T.events,N]),X.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,Ht(t))}return T.events.on(`menuopenchange`,e),()=>{T.events.off(`menuopenchange`,e)}},[T.events,v]);let R=et();X.useEffect(()=>{D||R.clear()},[D,R]),X.useEffect(()=>{function e(e){if(!(!D||e.nodeId!==v.select(`floatingParentNodeId`))){if(e.target&&A&&A!==e.target){let e=v.select(`closeDelay`);e>0?R.isStarted()||R.start(e,()=>{v.setOpen(!1,Ht(Pr))}):v.setOpen(!1,Ht(Pr))}else R.clear()}}return T.events.on(`itemhover`,e),()=>{T.events.off(`itemhover`,e)}},[T.events,D,A,v,R]),X.useEffect(()=>{let e={open:D,nodeId:N,parentNodeId:P,reason:v.select(`lastOpenChangeReason`)};T.events.emit(`menuopenchange`,e)},[T.events,D,v,N,P]),IC({store:v,domReference:re,positionerElement:M,open:D});let ue={open:D,side:le.side,align:le.align,anchorHidden:le.anchorHidden,nested:C.type===`menu`,instant:ee},de=C.type===`menubar`&&C.context.modal;zC(D&&(de||O&&ne!==`trigger-hover`),k===`touch`,M,A);let fe=LC(e,ue,{styles:le.positionerStyles,transitionStatus:j,props:_,refs:[t,v.useStateSetter(`positionerElement`)],hidden:!E,inert:!D}),pe=E&&C.type!==`menu`&&(C.type!==`menubar`&&O&&ne!==`trigger-hover`||C.type===`menubar`&&C.context.modal),me=null;return C.type===`menubar`?me=C.context.contentElement:C.type===void 0&&(me=A),(0,Q.jsxs)(sb.Provider,{value:le,children:[pe&&(0,Q.jsx)(Kr,{ref:C.type===`context-menu`||C.type===`nested-context-menu`?C.context.internalBackdropRef:null,inert:mr(!D),cutout:me}),(0,Q.jsx)(Bt,{id:N,children:(0,Q.jsx)(kC,{elementsRef:v.context.itemDomElements,labelsRef:v.context.itemLabels,onMapChange:b,children:fe})})]})}),VC=X.createContext(null);function HC(e){let t=X.useContext(VC);if(t===null&&!e)throw Error(rn(5));return t}function UC(e){return e==null?te:e.type.startsWith(`key`)?Zi:e.type.startsWith(`mouse`)||e.type.startsWith(`pointer`)?it:te}var WC={...da,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=da.triggerPopupId(e,t);return n?e.listElement?.id||n:void 0},filterTriggerProps:e=>e.filterTriggerProps,inputProps:e=>e.inputProps,webkitAriaSelected:(e,t)=>ue&&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`&&!da.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`)}},GC=class extends An{constructor(e,t,n=!1){let r=new Qi,i=qC(r,t,n,e);super(i,KC(r),WC),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 KC(e){return{positionerRef:X.createRef(),popupRef:X.createRef(),typingRef:{current:!1},itemDomElements:{current:[]},itemLabels:{current:[]},highlightReason:`none`,highlightEvent:void 0,reportedItem:void 0,allowMouseUpTriggerRef:{current:!1},virtualFocusRef:void 0,triggerFocusTargetRef:X.createRef(),beforeTriggerFocusGuardRef:X.createRef(),beforeContentFocusGuardRef:X.createRef(),onOpenChangeComplete:void 0,triggerElements:e}}function qC(e,t,n=!1,r){return{...qi(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:ce,inputProps:ce,inputFocused:!1,highlightedItem:void 0,hoverEnabled:!0,instantType:void 0,openChangeReason:null,floatingTreeRoot:new Ne,floatingNodeId:void 0,floatingParentNodeId:null,itemProps:ce,keyboardEventRelay:void 0,closeDelay:0,adaptiveOrigin:void 0,...r}}var JC=X.createContext(null);function YC(e,t){return(e===`trigger-press`||e===`item-press`)&&t?.detail===0}function XC(e,t){return e===`list-navigation`||YC(e,t)}var ZC=ia(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:p=!1,handle:m,triggerId:h,defaultTriggerId:g=null,highlightItemOnHover:_=!0,isSubmenu:v=!1,virtualFocus:y=!1,virtualFocusRef:b,allowEscape:x=!0,resetOnPointerLeave:S=!0}=e,C=fb(!0),w=ub(!0),T=HC(!0),E=w?.store,D=w?.virtualFocus??!1,O=X.useMemo(()=>v&&E?{type:`menu`,store:E}:T?{type:`menubar`,context:T}:C&&!E?{type:`context-menu`,context:C}:{type:void 0},[C,E,T,v]),k=It(),A=It(),[j,M]=X.useState(void 0),ee=(j??A)||void 0,N=Kt(),P=O.type===`menu`?O.store:void 0,re=(n??o)&&P?.state.transitionStatus===`starting`,F=Ee(()=>re?P?.state.instantType:void 0).current,I=Ee(()=>{let e=new GC({open:o,openProp:n,activeTriggerId:g,triggerIdProp:h,parent:O,disabled:s,highlightItemOnHover:_,modal:O.type===void 0?c:void 0,rootId:k,instantType:F},ee,N!=null);return e.context.virtualFocusRef=b,e}).current;I.useControlledProp(`openProp`,n),I.useControlledProp(`triggerIdProp`,h),I.useContextCallback(`onOpenChangeComplete`,i);let ie=I.useState(`floatingTreeRoot`),L=Ft(ie),oe=I.useState(`open`),se=I.useState(`activeTriggerElement`),le=I.useState(`positionerElement`),R=I.useState(`hoverEnabled`),ue=I.useState(`disabled`),de=I.useState(`lastOpenChangeReason`),fe=I.useState(`parent`),pe=I.useState(`activeIndex`),z=I.useState(`keyboardOpen`),_e=I.useState(`payload`),ve=I.useState(`floatingParentNodeId`),ye=X.useRef(null),be=X.useRef(fe.type!==`context-menu`),xe=et(),Se=X.useRef(!0),Ce=et(),we=ve!=null,{openMethod:Te,triggerProps:De}=Un(oe);I.useSyncedValues({disabled:s,highlightItemOnHover:_,modal:fe.type===void 0?c:void 0,openMethod:Te,rootId:k}),Or(I);let{forceUnmount:Oe,transitionStatus:ke}=Ge(oe,I,()=>{I.set(`allowMouseEnter`,!1)},re),Ae=ae(I.context.popupRef);X.useEffect(()=>{if(F===void 0)return;let e=()=>{I.state.instantType===F&&I.set(`instantType`,void 0)};if(!oe){e();return}if(ke!==void 0)return;if(I.context.popupRef.current==null){e();return}let t=new AbortController;return Ae(e,t.signal),()=>{t.abort()}},[F,oe,ke,Ae,I]),pn(()=>{C&&!w?I.update({parent:{type:`context-menu`,context:C},floatingNodeId:L,floatingParentNodeId:N}):(w||!I.select(`activeTriggerElement`))&&I.update({floatingNodeId:L,floatingParentNodeId:N})},[C,w,L,N,se,I]),X.useEffect(()=>{if(oe||(ye.current=null),fe.type===`context-menu`){if(!oe){xe.clear(),be.current=!1;return}xe.start(500,()=>{be.current=!0})}},[xe,oe,fe.type]),pn(()=>{!oe&&!R&&I.set(`hoverEnabled`,!0)},[oe,R,I]);let je=_t((e,t)=>{let n=t.reason;if(!e&&!I.select(`open`)||oe===e&&t.trigger===se&&de===n)return;let i=at(t);if(!e&&t.trigger==null&&(t.trigger=se??void 0),r?.(e,t),t.isCanceled)return;I.state.floatingRootContext.dispatchOpenChange(e,t);let a=t.event;if(e===!1&&n!==`item-press`&&a?.type===`click`&&a.pointerType===`touch`&&!Se.current)return;e&&n===`trigger-focus`?(Se.current=!1,Ce.start(300,()=>{Se.current=!0})):(Se.current=!0,Ce.clear());let o=!e&&(n===`escape-key`||n==null);ye.current=t.event;let s=f(I.state,e,t.trigger,i());s.openChangeReason=n,s.keyboardOpen=e&&XC(n,a),s.instantType=fe.type===`menubar`&&(n===`trigger-focus`||n===`focus-out`||n===`trigger-hover`||n===`list-navigation`||n===`sibling-open`)?`group`:YC(n,a)?`click`:o?`dismiss`:void 0,I.update(s)}),Me=ze({popupStore:I,floatingRootContext:I.state.floatingRootContext,floatingId:ee,nested:N!=null,onOpenChange:je}),Ne=Me.context.events;pn(()=>{let e=({open:e,eventDetails:t})=>je(e,t);return Ne.on(`setOpen`,e),()=>{Ne?.off(`setOpen`,e)}},[Ne,je]),pn(()=>I.subscribeToParentMenu(),[I]);let Pe=X.useCallback(()=>{I.setOpen(!1,Ht(wt))},[I]);X.useImperativeHandle(d,()=>({unmount:Oe,close:Pe}),[Oe,Pe]);let Fe;fe.type===`context-menu`&&(Fe=fe.context),X.useImperativeHandle(Fe?.positionerRef,()=>le,[le]),X.useImperativeHandle(Fe?.actionsRef,()=>({setOpen:je}),[je]);let Ie=xt(Me,{enabled:!ue,bubbles:{escapeKey:p&&fe.type===`menu`},outsidePress(){return fe.type!==`context-menu`||ye.current?.type===`contextmenu`||be.current},externalTree:we?ie:void 0}),Le=fC(),Re=Ix(Me,{enabled:!ue,listRef:I.context.itemDomElements,activeIndex:pe,virtual:y,nested:fe.type===`menubar`||!y&&fe.type!==void 0,parentOrientation:fe.type===`menubar`?fe.context.orientation:void 0,loopFocus:l,focusItemOnOpen:y?z:void 0,allowEscape:y&&l&&x,orientation:u,triggerOrientation:y?`vertical`:u,rtl:Le===`rtl`,disabledIndices:Gt,onNavigate(e,t){I.setActiveIndex(e,UC(t),t?.nativeEvent)},openOnArrowKeyDown:fe.type!==`context-menu`&&!(y&&v),externalTree:!y&&we?ie:void 0,nestedReturnFocusRef:P?.context.virtualFocusRef,focusItemOnHover:_,resetOnPointerLeave:S}),Be=X.useCallback(e=>{I.context.typingRef.current=e},[I]),Ve=Lx(Me,{enabled:!ue&&!y,listRef:I.context.itemLabels,elementsRef:I.context.itemDomElements,activeIndex:pe,resetMs:500,onMatch:(e,t)=>{oe&&e!==pe&&I.setActiveIndex(e,Zi,t.nativeEvent)},onTyping:Be}),He=_t(a),Ue=X.useRef(-1),We=_t(()=>{let e=I.state.activeIndex,t=e===null?void 0:I.context.itemDomElements.current[e]??void 0;if(t?.isConnected===!1)return;let n=t===void 0?-1:e;if(Ue.current===n&&I.context.reportedItem===t)return;Ue.current=n,I.context.reportedItem=t,y&&I.set(`highlightedItem`,t);let{highlightReason:r,highlightEvent:i}=I.context;I.context.highlightReason=te,I.context.highlightEvent=void 0,a&&He(t,ge(r,i,{label:t===void 0?void 0:I.context.itemLabels.current[n]??void 0}))});pn(()=>{We()},[pe,We]);let Ke=X.useMemo(()=>{if(!y)return Re.reference;if(!Re.trigger)return ce;let{onFocus:e,...t}=Re.trigger;return t},[y,Re.reference,Re.trigger]);I.useSyncedValue(`inputProps`,y?Re.reference??ce:ce);let qe=X.useMemo(()=>{let e=me(Ve.reference,Ke,Ie.reference,{onMouseMove(){I.set(`allowMouseEnter`,!0)}},De);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=oe,e},[I,Ve.reference,Ke,Ie.reference,De,oe]),Je=X.useMemo(()=>{let e=me(Re.trigger,Ie.trigger,De);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=!1,e},[Re.trigger,Ie.trigger,De]);Ee(()=>(I.update({inactiveTriggerProps:Je}),null));let Ye=X.useMemo(()=>me(At,{onMouseMove(){I.set(`allowMouseEnter`,!0),fe.type===`menu`&&I.set(`hoverEnabled`,!1)},onClick(){I.select(`hoverEnabled`)&&I.set(`hoverEnabled`,!1)},onKeyDown(e){let t=I.select(`keyboardEventRelay`);t&&!e.isPropagationStopped()&&t(e)}},Ve.floating,Re.floating,Ie.floating),[fe.type,I,Ve.floating,Re.floating,Ie.floating]),Xe=Re.item??ce;Qe(I,{floatingRootContext:Me,activeTriggerProps:qe,inactiveTriggerProps:Je,popupProps:Ye,itemProps:Xe});let Ze=X.useMemo(()=>({store:I,parent:O,orientation:u,loopFocus:l,allowEscape:x,defaultFloatingId:A,setRenderedFloatingId:M,virtualFocus:y,parentVirtualFocus:D,syncHighlightedItem:We}),[I,O,u,l,x,A,y,D,We]),$e=typeof t==`function`?t({payload:_e}):t,tt=(0,Q.jsxs)(lb.Provider,{value:Ze,children:[m&&(0,Q.jsx)(ne,{handle:m,store:I}),$e]});return(fe.type===void 0||fe.type===`context-menu`)&&(tt=(0,Q.jsx)(he,{externalTree:ie,children:tt})),tt});function QC(e){let t=X.useContext(JC);if(t===null)return(0,Q.jsx)(ZC,{...e});let n=t.Root;return(0,Q.jsx)(JC.Provider,{value:null,children:(0,Q.jsx)(n,{...t.options,...e})})}var $C=5;function ew(e,t){let n=tw(t);return e.clientX>=n.left-$C&&e.clientX<=n.right+$C&&e.clientY>=n.top-$C&&e.clientY<=n.bottom+$C}function tw(e){let t=e.getBoundingClientRect(),n=ki(e);if(Jt)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 nw(e={}){let{highlightItemOnHover:t,highlightedIndex:n,onHighlightedIndexChange:r}=$t(),{ref:i,index:a}=Eb(e),o=n===a,s=X.useRef(null),c=_i(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:c,index:a}}function rw(e){let{render:t,className:n,style:r,state:i=ce,props:a=Gt,refs:o=Gt,metadata:s,stateAttributesMapping:c,tag:l=`div`,...u}=e,{compositeProps:d,compositeRef:f}=nw({metadata:s});return zt(l,e,{state:i,ref:[f,...o],props:[d,...a,u],stateAttributesMapping:c})}function iw(e){if(Bi(e)&&e.hasAttribute(`data-rootownerid`))return e.getAttribute(`data-rootownerid`);if(!Hn(e))return iw(ai(e))}function aw(e,t){function n(n,r,i){let a=n.currentTarget;Dx.flushSync(()=>{e.setOpen(!1,Ht(ra,n.nativeEvent,a))}),ei(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&&Ei(t,r)?e.context.beforeContentFocusGuardRef.current?.focus():n(t,1,r)}return{handlePreFocusGuardFocus:r,handleFocusTargetFocus:i}}function ow(e){let{enabled:t=!0,mouseDownAction:n,open:r}=e,i=X.useRef(!1);return X.useMemo(()=>t?{onMouseDown:e=>{(n===`open`&&!r||n===`close`&&r)&&(i.current=!0,sn(e.currentTarget).addEventListener(`click`,()=>{i.current=!1},{once:!0}))},onClick:e=>{i.current&&(i.current=!1,e.preventBaseUIHandler())}}:ce,[t,n,r])}var sw=Tt(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,id:s,openOnHover:c,delay:l=100,closeDelay:u=0,handle:d,payload:f,...p}=e,m=ub(!0),h=vn(d)??m?.store;if(!h)throw Error(rn(85));let g=It(s),_=h.useState(`isTriggerActive`,g),v=h.useState(`floatingRootContext`),y=h.useState(`isOpenedByTrigger`,g),b=h.useState(`triggerControlsId`,g),x=X.useRef(null),S=lw(),C=$t(!0),w=le(),T=X.useMemo(()=>w??new Ne,[w]),E=Ft(T),D=Kt(),{registerTrigger:O,isMountedByThisTrigger:k}=xe(g,x,h,{payload:f,closeDelay:u,parent:S,floatingTreeRoot:T,floatingNodeId:E,floatingParentNodeId:D,keyboardEventRelay:C?.relayKeyboardEvent}),A=S.type===`menubar`,j=h.useState(`disabled`),M=a||j||A&&S.context.disabled,{getButtonProps:ee,buttonRef:te}=bi({disabled:M,native:o});X.useEffect(()=>{!y&&S.type===void 0&&(h.context.allowMouseUpTriggerRef.current=!1)},[h,y,S.type]);let ne=X.useRef(null),N=et(),re=_t(e=>{if(!ne.current)return;N.clear(),h.context.allowMouseUpTriggerRef.current=!1;let t=e.target;P(ne.current,t)||P(h.select(`positionerElement`),t)||t===ne.current||(t==null||iw(t)!==h.select(`rootId`))&&(ew(e,ne.current)||T.events.emit(`close`,{domEvent:e,reason:_n}))});X.useEffect(()=>{let e=sn(ne.current);if(y&&h.select(`lastOpenChangeReason`)===`trigger-hover`)return e.addEventListener(`mouseup`,re,{once:!0}),()=>{e.removeEventListener(`mouseup`,re)}},[y,re,h]);let F=A&&S.context.hasSubmenuOpen,ie=kx(v,{enabled:(c??F)&&!M&&(!A||F&&!k),handleClose:Gx({blockPointerEvents:!A}),mouseOnly:!0,move:!1,restMs:S.type===void 0?l:void 0,delay:{close:u},triggerElementRef:x,externalTree:T,isActiveTrigger:_,isClosing:()=>h.select(`transitionStatus`)===`ending`}),L=cw(y,h.select(`lastOpenChangeReason`)),ae=ga(v,{enabled:!M,event:y&&A?`click`:`mousedown`,toggle:!0,ignoreMouse:!1,stickIfOpen:S.type===void 0&&L}),oe=bx(v,{enabled:!M&&F}),se=ow({open:y,enabled:A,mouseDownAction:`open`}),R=X.useMemo(()=>me(oe.reference,ae.reference),[oe.reference,ae.reference]),ue=h.useState(`triggerProps`,k),de=h.useState(`filterTriggerProps`),{handlePreFocusGuardFocus:fe,handleFocusTargetFocus:pe}=aw(h,x),he={disabled:M,open:y},z=[ne,t,te,O,x],ge=[R,ie??ce,ue,{"aria-haspopup":`menu`,"aria-controls":b,id:g,onMouseDown:e=>{h.select(`open`)||(N.start(200,()=>{h.context.allowMouseUpTriggerRef.current=!0}),sn(e.currentTarget).addEventListener(`mouseup`,re,{once:!0}))}},de,A?{role:`menuitem`}:{},se,p,ee],_e=zt(`button`,e,{enabled:!A,stateAttributesMapping:I,state:he,ref:z,props:ge});return A?(0,Q.jsx)(rw,{tag:`button`,render:n,className:r,style:i,state:he,refs:z,props:ge,stateAttributesMapping:I}):y?(0,Q.jsxs)(X.Fragment,{children:[(0,Q.jsx)(Ui,{ref:h.context.beforeTriggerFocusGuardRef,onFocus:fe},`${g}-pre-focus-guard`),(0,Q.jsx)(X.Fragment,{children:_e},g),(0,Q.jsx)(Ui,{ref:h.context.triggerFocusTargetRef,onFocus:pe},`${g}-post-focus-guard`)]}):(0,Q.jsx)(X.Fragment,{children:_e},g)});function cw(e,t){let n=et(),[r,i]=X.useState(!1);return pn(()=>{e&&t===`trigger-hover`?(i(!0),n.start(500,()=>{i(!1)})):e||(n.clear(),i(!1))},[e,t,n]),r}function lw(){let e=HC(!0);return X.useMemo(()=>e?{type:`menubar`,context:e}:{type:void 0},[e])}var uw=X.forwardRef(function(e,t){let{className:n,render:r,orientation:i=`horizontal`,style:a,...o}=e;return zt(`div`,e,{state:{orientation:i},ref:t,props:[{role:`separator`,"aria-orientation":i},o]})}),dw=(0,X.createContext)(null);function fw({actionsRef:e,children:t,interactionOwner:n=`local`,onOpenChange:r,...i}){let a=(0,X.useRef)(null),o=e??a;return In(()=>o.current?.close()),(0,Q.jsx)(dw.Provider,{value:{actionsRef:o,interactionOwner:n},children:(0,Q.jsx)(QC,{...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 pw(){let e=(0,X.useContext)(dw);if(!e)throw Error(`DropdownMenu parts must be used inside <DropdownMenu>`);return e}var mw=(0,X.forwardRef)(function({className:e,render:t,type:n=`button`,...r},i){return(0,Q.jsx)(sw,{...r,className:t=>Pn(`btn caps-dropdown-trigger`,Lr(e,t)),ref:i,render:t,type:n})}),hw=(0,X.forwardRef)(function({container:e,...t},n){let r=zr(`popover`);return e==null&&r===null?null:(0,Q.jsx)(lC,{...t,container:e??r,ref:n})}),gw=(0,X.forwardRef)(function({collisionBoundary:e,...t},n){let r=zr(`popover`);return(0,Q.jsx)(BC,{...t,collisionBoundary:e??(r&&r!==document.body?r:void 0),ref:n})}),_w=(0,X.forwardRef)(function({className:e,finalFocus:t,...n},r){let{interactionOwner:i}=pw(),a=(0,X.useRef)(null);(0,X.useImperativeHandle)(r,()=>a.current);let o=Vi(`.caps-dropdown-item[data-highlighted]`),s=(0,X.useCallback)(e=>{a.current=e,o(e)},[o]);return(0,Q.jsx)(oC,{...n,className:t=>Pn(`caps-dropdown-popup min-w-40 rounded-box border border-base-300 bg-base-100 p-xs shadow-lg outline-none`,Lr(e,t)),finalFocus:i===`host`?!1:t??!0,ref:s})}),vw=(0,X.forwardRef)(function({align:e=`end`,alignOffset:t,children:n,container:r,keepMounted:i,side:a=`bottom`,sideOffset:o=4,...s},c){return(0,Q.jsx)(hw,{container:r,keepMounted:i,children:(0,Q.jsx)(gw,{align:e,alignOffset:t,side:a,sideOffset:o,children:(0,Q.jsx)(_w,{...s,ref:c,children:n})})})}),yw=`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`,bw=(0,X.forwardRef)(function({className:e,onClick:t,onSelect:n,variant:r=`default`,...i},a){return(0,Q.jsx)(Lb,{...i,className:t=>Pn(yw,r===`destructive`&&`text-error hover:bg-error hover:text-error-content focus-visible:bg-error focus-visible:text-error-content`,Lr(e,t)),onClick:e=>{t?.(e),e.defaultPrevented||n?.(e)},ref:a})});(0,X.forwardRef)(function({children:e,className:t,onClick:n,onSelect:r,...i},a){return(0,Q.jsxs)(jb,{...i,className:e=>Pn(yw,Lr(t,e)),onClick:e=>{n?.(e),e.defaultPrevented||r?.(e)},ref:a,children:[(0,Q.jsx)(`span`,{className:`min-w-0 flex-1`,children:e}),(0,Q.jsx)(Mb,{"aria-hidden":`true`,className:`shrink-0`,children:`✓`})]})}),(0,X.forwardRef)(function({className:e,...t},n){return(0,Q.jsx)(uw,{...t,className:t=>Pn(`my-xs h-px bg-base-300`,Lr(e,t)),ref:n})}),(0,X.forwardRef)(function({className:e,...t},n){return(0,Q.jsx)(Fb,{...t,className:t=>Pn(`px-md pb-xs pt-sm text-xs font-semibold text-base-content/60`,Lr(e,t)),ref:n})});var xw=e=>String(e).padStart(2,`0`),Sw=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime();function Cw(e,t){let n=new Date(e),r=Math.round((Sw(new Date(t))-Sw(n))/864e5);return r<=0?`${xw(n.getHours())}:${xw(n.getMinutes())}`:r===1?`Yesterday`:`${String(n.getFullYear())}-${xw(n.getMonth()+1)}-${xw(n.getDate())}`}function ww(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 Tw(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 Ew(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,source:`builtin`}))})).filter(e=>e.methods.length>0).sort((e,t)=>e.name.localeCompare(t.name)||e.id.localeCompare(t.id))}var Dw=za({providerId:To().min(1).max(200).optional(),method:ro([`api_key`,`subscription`]).optional(),option:To().min(1).max(200).optional()});Na(To(),co()).parse(structuredClone(Ma(Dw)));var Ow=za({providerId:To().min(1).max(200).optional()});Na(To(),co()).parse(structuredClone(Ma(Ow)));function kw(e,t){return e.kind===`api_key`?`Paste an API key you created`:`Sign in with your ${t.name} account`}async function Aw(e,t,n){if(t!==void 0){let n=e.methods.find(e=>e.kind===t);if(n===void 0)throw new _r(`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:kw(t,e)}))}),o=e.methods.find(e=>e.kind===a);if(o===void 0)throw new _r(`method_unavailable`,`Choose a listed method.`);return o}async function jw(e,t,n,r={}){let i=await Aw(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 Mw=on(Pe(en,{onExcessProperty:`error`})).schema;G.pipe(V(Vt(/^[^/\s]+\/[^\s]+$/u)),V(Y(513)));var Nw=`default`,Pw=new WeakMap,Fw=256;function Iw(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 Lw(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??Nw,options:[{value:Nw,label:`Model default`},...t.reasoning.map(e=>({value:e,label:e}))]});return t.reasoning.find(e=>e===r)}var Rw=255;async function zw(e,t,n,r,i){if(n===void 0){let n=[...new Map(t.map(e=>[e.providerId,e.providerName]))].slice(0,Rw),a=await e.prompt({type:`choice`,message:`Choose a provider`,summary:`Or follow the Agent's own model.`,current:i??Nw,options:[{value:Nw,label:`Use agent model`},...n.map(([e,t])=>({value:e,label:t}))]});if(a===Nw)return null;let o=(await e.run(()=>r(e.signal))).filter(e=>e.providerId===a).slice(0,Rw);if(o.length===0)throw new _r(`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=>Ew(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,source:`builtin`}))&&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??Nw,collapsedGroup:`More providers`,options:[{value:Nw,label:`Use agent model`},...Tw(c,o,a.popularProviderIds,`model`).slice(0,Rw)]});if(l===Nw)return null;let u=c.find(e=>e.id===l);if(!u)throw new _r(`provider_unavailable`,`Choose a listed provider.`);let d=t;o.some(e=>e.providerId===l)||(await jw(a,u,e),d=await e.run(()=>r(e.signal)));let f=d.filter(e=>e.providerId===l).slice(0,Rw);if(f.length===0)throw new _r(`model_unavailable`,`${u.name} has no available models. Retry /model.`);return f}function Bw(e,t){let n=Pw.get(e.modelPreference.read)??new Map;Pw.set(e.modelPreference.read,n);let r=e=>{if(e!==null&&(n.delete(e.providerId),n.set(e.providerId,e),n.size>Fw)){let e=n.keys().next().value;e!==void 0&&n.delete(e)}},i=Na(To(),co()).parse(Mw),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 zw(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=Iw(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 _r(`model_unavailable`,`Choose a listed model.`);let f=await Lw(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=mn(i.arguments)}catch{throw new _r(`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 _r(`model_unavailable`,`That model is not in the current catalog`);if(e.reasoning!==void 0&&!n.reasoning.includes(e.reasoning))throw new _r(`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 _r(`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 _r(`model_required`,`Choose a model with /model before its thinking level.`);if(a.reasoning.length===0)throw new _r(`reasoning_unavailable`,`${a.name} has no thinking levels.`);let o=await Lw(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 Vw=200,Hw=za({action:oo(`list`)}),Uw=Na(To(),co()).parse(structuredClone(Ma(Hw))),Ww=120,Gw=za({title:To()}).optional().transform(e=>e?.title.trim().replaceAll(/\s+/gu,` `)??``),Kw=4096,qw=za({instructions:To()}).optional().transform(e=>e?.instructions.trim()??``);function Jw(e,t){return e?.notify({type:`info`,message:t}),t}function Yw(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 Jw(t,`Session ${n.sessionId} is ${jr(Je(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:Uw},handler:async({arguments:t,interaction:n})=>{if(!Hw.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}`);Jw(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(`
25
- `))}},{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(jr(Je(a))!==`idle`)throw Error(`Wait for the current run to finish, then fork.`);let o=ur(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,Vw),l=Date.now(),u=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:ww(e.text,44)||`(empty message)`,description:e.at===void 0?void 0:Cw(e.at,l)}))}),d=await r.run(async()=>{try{return await e.command({type:`fork`,entryId:u})}catch(e){if(e instanceof c){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(d.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=qw.safeParse(t);if(!n.success)throw Error(`Use /compact, or /compact <what to focus on>.`);let r=n.data;if(r.length>Kw)throw Error(`Compaction instructions are at most ${String(Kw)} characters.`);return await e.command(r.length===0?{type:`compact`,requestId:ye()}:{type:`compact`,requestId:ye(),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=Gw.safeParse(n);if(!r.success)throw Error(`Use /name <title>, or /name to clear it.`);let i=r.data;if(Array.from(i).length>Ww)throw Error(`A conversation title is at most ${String(Ww)} 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 Xw=ma(`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`}]]),Zw=ma(`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`}]]),Qw=ma(`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`}]]),$w=ma(`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`}]]),eT=ma(`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`}]]),tT=ma(`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`}]]),nT=ma(`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`}]]),rT=ma(`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`}]]),iT=ma(`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`}]]),aT=ma(`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`}]]),oT=(0,X.memo)(function({avatar:e,className:t=`h-12 w-12 shrink-0`,onState:n,service:r=xi,state:i}){let a=(0,X.useMemo)(()=>e?yr(e):void 0,[e]);return(0,Q.jsx)(Sn,{"aria-hidden":`true`,className:t,service:r,...n?{onState:n}:{},src:a?.src??{local:`mushroom`},...a?{appearance:a.appearance,renderStyle:a.renderStyle}:{},...i})}),sT=3e4;function cT(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,sT)});await Promise.race([Promise.all(t),n]),clearTimeout(e)}}}function lT(e,t){let n=!1,r=async()=>{try{return await t.read()}catch(e){if(!(e instanceof c)||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`);Yr(e,t,r)}),close:()=>{n=!0,i()}}}function uT(e){return class{#e;constructor(t){this.#e=new Eg(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 dT(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:uT(s.fetch),fetch:s.fetch}),f=cT(c.session(d)),p=f.session,h=lT(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 fT={view:{kind:`none`},creating:null,awaitingRoute:void 0,route:null,nextTicket:1},pT=(e,t)=>e===t||!!e&&!!t&&e.agentId===t.agentId&&e.sessionId===t.sessionId;function mT(e,t){return e.awaitingRoute!==void 0||!pT(e.route,t)?{awaitingRoute:t,effects:[{type:`navigate`,target:t}]}:{awaitingRoute:void 0,effects:[]}}function hT(e){return e.kind===`opening`?e.target:e.kind===`open`?e.conversation:null}function gT(e){return e.kind===`open`?e.conversation:e.kind===`opening`?e.previous:null}function _T(e,t=[],n=!0,r=null){return{state:e,effects:t,accepted:n,ticket:r}}function vT(e,t,n){let r=hT(e.view),i=n===`host`;if(pT(r,t)){let n=mT(e,t);return _T({...e,creating:null,awaitingRoute:n.awaitingRoute},n.effects)}let a=gT(e.view);if(n!==`route`&&a!==null&&pT(a,t)){let n=mT(e,t);return _T({...e,view:{kind:`open`,conversation:a},creating:null,awaitingRoute:n.awaitingRoute},[{type:`open`,target:t,fromHost:i},...n.effects])}let o=n===`route`?null:mT(e,t);return _T({...e,view:{kind:`opening`,target:t,cause:n,previous:gT(e.view)},creating:null,awaitingRoute:o?o.awaitingRoute:void 0},[{type:`open`,target:t,fromHost:i},...o?o.effects:[]])}function yT(e,t){switch(t.type){case`select`:return vT(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`?_T(n):_T({...n,view:{kind:`none`},creating:null},[{type:`clear`}]):pT(hT(n.view),t.target)||n.creating?.cause===`person`?_T(n):vT(n,t.target,`route`):_T(pT(r,t.target)?{...n,awaitingRoute:void 0}:n)}case`route-confirmed`:{let n={...e,route:t.target};return _T(pT(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 _T(e,[],!1);let n=e.nextTicket;return _T({...e,creating:{ticket:n,cause:t.cause},nextTicket:n+1},[],!0,n)}case`created`:{if(e.creating?.ticket!==t.ticket)return _T(e,[],!1);let n=e.creating.cause;return n===`auto`&&e.view.kind!==`none`?_T({...e,creating:null},[],!1):vT({...e,creating:null},t.target,n)}case`create-failed`:return e.creating?.ticket===t.ticket?_T({...e,creating:null}):_T(e,[],!1);case`opened`:{let n=e.view;return n.kind!==`opening`||!pT(n.target,t.conversation)?_T(e,[],!1):_T({...e,view:{kind:`open`,conversation:t.conversation}})}case`open-failed`:{let t=e.view;if(t.kind!==`opening`)return _T(e,[],!1);let n=t.previous,r=mT(e,n);return _T({...e,view:n?{kind:`open`,conversation:n}:{kind:`none`},awaitingRoute:r.awaitingRoute},r.effects)}case`leave`:{let n=t.navigate?mT(e,null):null;return _T({...e,view:{kind:`none`},creating:null,awaitingRoute:n?n.awaitingRoute:void 0},[{type:`clear`},...n?n.effects:[]])}case`reset`:return _T({...e,view:{kind:`none`},creating:null,awaitingRoute:void 0})}}function bT(e){return gT(e.view)}function xT(e){return e.view.kind===`opening`?e.view.target:null}function ST(e){let t={state:fT,error:null},n=!1,r=new Set,i=e=>{t={...t,...e};for(let e of r)e()},a=dT({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=yT(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())}}}function CT({agent:e,message:t}){return(0,Q.jsxs)(`div`,{className:`m-auto flex flex-col items-center gap-sm text-center`,"data-head-loading":!0,role:`status`,children:[e===void 0?(0,Q.jsx)(oT,{className:`chat-gill-hero size-[72px] shrink-0`,state:{activity:`thinking`,expression:`normal`}}):(0,Q.jsx)(Xr,{activity:`thinking`,avatar:e.avatar,className:`chat-gill-hero`,name:e.name,size:72}),(0,Q.jsx)(`p`,{className:`text-sm text-dim`,children:t})]})}var wT=X.createContext(void 0);function TT(){let e=X.useContext(wT);if(e===void 0)throw Error(rn(53));return e}function ET(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 DT=`base-ui-disable-scrollbar`,OT={className:DT,getElement(e){return(0,Q.jsx)(`style`,{nonce:e,href:DT,precedence:`base-ui:low`,children:`.${DT}{scrollbar-width:none}.${DT}::-webkit-scrollbar{display:none}`})}},kT=`data-has-overflow-x`,AT=`data-has-overflow-y`,jT=`data-overflow-x-start`,MT=`data-overflow-x-end`,NT=`data-overflow-y-start`,PT=`data-overflow-y-end`,FT=e=>t=>t?{[e]:``}:null,IT={hasOverflowX:FT(kT),hasOverflowY:FT(AT),overflowXStart:FT(jT),overflowXEnd:FT(MT),overflowYStart:FT(NT),overflowYEnd:FT(PT),cornerHidden:()=>null},LT=X.createContext(void 0),RT={disableStyleElements:!1};function zT(){return X.useContext(LT)??RT}var BT=`--scroll-area-corner-height`,VT=`--scroll-area-corner-width`,HT=`data-orientation`,UT={x:0,y:0},WT={width:0,height:0},GT={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},KT={x:!0,y:!0,corner:!0},qT=X.forwardRef(function(e,t){let{render:n,className:r,overflowEdgeThreshold:i,style:a,...o}=e,{xStart:s,xEnd:c,yStart:l,yEnd:u}=JT(i),d=It(),f=et(),p=et(),{nonce:m,disableStyleElements:h}=zT(),[g,_]=X.useState(!1),[v,y]=X.useState(!1),[b,x]=X.useState(!1),[S,C]=X.useState(!1),[w,T]=X.useState(!1),[E,D]=X.useState(WT),[O,k]=X.useState(WT),[A,j]=X.useState(GT),[M,ee]=X.useState(KT),te=X.useRef(null),ne=X.useRef(null),N=X.useRef(null),re=X.useRef(null),F=X.useRef(null),I=X.useRef(null),ie=X.useRef(null),L=X.useRef(null),ae=X.useRef(0),oe=X.useRef(0),se=X.useRef(0),ce=X.useRef(0),le=X.useRef(`vertical`),R=X.useRef(UT),ue=X.useRef(null);function de(e){let t=e?x:y,n=e?f:p;t(!0),n.start(500,()=>{t(!1)})}let fe=_t(e=>{let t=e.x-R.current.x,n=e.y-R.current.y;R.current=e,n!==0&&de(!0),t!==0&&de(!1)}),pe=_t(()=>{let e=ne.current;e&&ue.current===null&&(ue.current=e.style.scrollSnapType,e.style.scrollSnapType=`none`)}),me=_t(e=>{if(e.button!==0||L.current!==null&&(le.current===`vertical`?F.current:I.current)?.hasPointerCapture(L.current))return;L.current=e.pointerId,ae.current=e.clientY,oe.current=e.clientX,le.current=e.currentTarget.getAttribute(HT);let t=ne.current;t&&(se.current=t.scrollTop,ce.current=t.scrollLeft,pe()),(le.current===`vertical`?F.current:I.current)?.setPointerCapture(e.pointerId)}),he=_t(e=>{if(e.pointerId!==L.current)return;L.current=null,(le.current===`vertical`?x:y)(!1),ue.current!==null&&(ne.current&&(ne.current.style.scrollSnapType=ue.current),ue.current=null);let t=le.current===`vertical`?F.current:I.current;t?.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId)}),z=_t(e=>{if(e.pointerId!==L.current)return;if(e.buttons%2==0){he(e);return}let t=ne.current;if(!t)return;let n=le.current===`vertical`,r=n?F.current:I.current,i=n?N.current:re.current;if(!r||!i)return;let a=n?`y`:`x`,o=ET(i,`padding`,a),s=ET(r,`margin`,a),c=n?r.offsetHeight:r.offsetWidth,l=(n?i.offsetHeight:i.offsetWidth)-c-o-s,u=n?e.clientY-ae.current:e.clientX-oe.current,d=l<=0?0:u/l,f=n?t.scrollHeight:t.scrollWidth,p=n?t.clientHeight:t.clientWidth,m=(n?se.current:ce.current)+d*(f-p);n?t.scrollTop=m:t.scrollLeft=m,e.preventDefault(),de(n)});function ge(e){C(e.pointerType===`touch`)}function _e(e){if(ge(e),e.pointerType!==`touch`){let t=P(te.current,e.target);_(t)}}let ve=X.useMemo(()=>({scrolling:v||b,hasOverflowX:!M.x,hasOverflowY:!M.y,overflowXStart:A.xStart,overflowXEnd:A.xEnd,overflowYStart:A.yStart,overflowYEnd:A.yEnd,cornerHidden:M.corner}),[v,b,M.x,M.y,M.corner,A]),ye={role:`presentation`,onPointerEnter:_e,onPointerMove:_e,onPointerDown:ge,onPointerLeave(){_(!1)},style:{position:`relative`,[BT]:`${E.height}px`,[VT]:`${E.width}px`}},be=zt(`div`,e,{state:ve,ref:[t,te],props:[ye,o],stateAttributesMapping:IT}),xe=X.useMemo(()=>({handlePointerDown:me,handlePointerMove:z,handlePointerUp:he,handleScroll:fe,disableViewportSnap:pe,cornerSize:E,setCornerSize:D,thumbSize:O,setThumbSize:k,hasMeasuredScrollbar:w,setHasMeasuredScrollbar:T,touchModality:S,cornerRef:ie,scrollingX:v,scrollingY:b,hovering:g,setHovering:_,viewportRef:ne,scrollbarYRef:N,scrollbarXRef:re,thumbYRef:F,thumbXRef:I,rootId:d,hiddenState:M,setHiddenState:ee,overflowEdges:A,setOverflowEdges:j,viewportState:ve,overflowEdgeThreshold:{xStart:s,xEnd:c,yStart:l,yEnd:u}}),[me,z,he,fe,pe,E,O,w,S,v,b,g,d,M,A,ve,s,c,l,u]);return(0,Q.jsxs)(wT.Provider,{value:xe,children:[!h&&OT.getElement(m),be]})});function JT(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 YT(e,t=-(2**53-1),n=2**53-1){return Math.max(t,Math.min(e,n))}var XT=X.createContext(void 0);function ZT(){let e=X.useContext(XT);if(e===void 0)throw Error(rn(55));return e}function QT(e,t){if(t<=0)return 0;let n=YT(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 $T=`--scroll-area-overflow-x-start`,eE=`--scroll-area-overflow-x-end`,tE=`--scroll-area-overflow-y-start`,nE=`--scroll-area-overflow-y-end`,rE=`--scroll-area-thumb-height`,iE=`--scroll-area-thumb-width`,aE=[$T,eE,tE,nE],oE=!1;function sE(){oE||ue||(typeof CSS<`u`&&`registerProperty`in CSS&&aE.forEach(e=>{try{CSS.registerProperty({name:e,syntax:`<length>`,inherits:!1,initialValue:`0px`})}catch{}}),oE=!0)}var cE=X.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}=TT(),T=fC(),E=X.useRef(!0),D=X.useRef([NaN,NaN,NaN,NaN]),O=et(),k=et(),A=_t(()=>{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=lE(e),A=k.y,j=k.x,M=b/_,ee=y/h,te=Math.max(0,_-b),ne=Math.max(0,h-y),N=0,P=0;j||(N=QT(T===`rtl`?-w:w,te),P=te-N);let re=A?0:QT(x,ne),F=A?0:ne-re,I=j?0:b,ie=A?0:y,L=0,ae=0;!j&&!A&&(L=t?.offsetWidth||0,ae=n?.offsetHeight||0);let oe=f.width===0&&f.height===0,se=oe?L:0,ce=oe?ae:0,le=ET(n,`padding`,`x`),R=ET(t,`padding`,`y`),ue=ET(i,`margin`,`x`),de=ET(r,`margin`,`y`),fe=I-le-ue,pe=ie-R-de,me=n?Math.min(n.offsetWidth-se,fe):fe,he=t?Math.min(t.offsetHeight-ce,pe):pe,z=Math.max(16,me*M),ge=Math.max(16,he*ee);if(m(e=>uE(e,{width:z,height:ge})),t&&r){let e=dE(r,rE,x,ne,h,ge,t.offsetHeight-ge-R-de);r.style.transform=`translate3d(0,${e}px,0)`}if(n&&i){let e=n.offsetWidth-z-le-ue,t=dE(i,iE,T===`rtl`?-w:w,te,_,z,e);i.style.transform=`translate3d(${T===`rtl`?-t:t}px,0,0)`}let _e=[N,P,re,F];aE.forEach((t,n)=>{e.style.setProperty(t,`${_e[n]}px`)}),a&&p(e=>uE(e,{width:L,height:ae})),g(e=>uE(e,k));let ve={xStart:!j&&N>C.xStart,xEnd:!j&&P>C.xEnd,yStart:!A&&re>C.yStart,yEnd:!A&&F>C.yEnd};S(e=>uE(e,ve))});pn(()=>{sE()},[]),pn(()=>{queueMicrotask(A)},[A,_,T,C.xStart,C.xEnd,C.yStart,C.yEnd]),pn(()=>{o.current?.matches(`:hover`)&&x(!0)},[o,x]),pn(()=>{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}A()});return n.observe(e),k.start(0,()=>{let t=Ce(e,{subtree:!0});t.length!==0&&Promise.allSettled(t.map(e=>e.finished.then(Me))).then(A).catch(()=>{})}),()=>{n.disconnect(),k.clear()}},[A,o,k]);function j(){E.current=!1}let M={...h&&{"data-id":`${h}-viewport`},tabIndex:_.x&&_.y?-1:0,className:OT.className,style:{overflow:`scroll`},onScroll(){o.current&&(A(),(b||!E.current)&&y({x:o.current.scrollLeft,y:o.current.scrollTop}),O.start(100,()=>{E.current=!0}))},onWheel:j,onPointerMove:j,onPointerEnter:j,onKeyDown:j},ee=zt(`div`,e,{ref:[t,o],state:w,props:[M,a],stateAttributesMapping:IT}),te=X.useMemo(()=>({computeThumbPosition:A}),[A]);return(0,Q.jsx)(XT.Provider,{value:te,children:ee})});function lE(e){let t=e.clientHeight>=e.scrollHeight,n=e.clientWidth>=e.scrollWidth;return{y:t,x:n,corner:t||n}}function uE(e,t){for(let n in t)if(e[n]!==t[n])return t;return e}function dE(e,t,n,r,i,a,o){let s=YT(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 fE=X.createContext(void 0);function pE(){let e=X.useContext(fE);if(e===void 0)throw Error(rn(54));return e}var mE=X.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}=TT(),T=i===`vertical`,E={...w,hovering:c,scrolling:T?u:l,orientation:i},D=fC(),O=!C&&!a,k=T?d.y:d.x,A=a||!k;X.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 pi(t,`wheel`,n,{passive:!1})},[D,y,T,p,f,A,m]);let M={...x&&{"data-id":`${x}-scrollbar`},"aria-hidden":!0,onPointerDown(e){if(e.button!==0)return;let t=j(e.nativeEvent),n=T?h.current:g.current;if(n&&P(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=ET(n,`margin`,a),s=ET(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(${BT})`,insetInlineEnd:0,[rE]:`${S.height}px`}:{insetInlineStart:0,insetInlineEnd:`var(${VT})`,bottom:0,[iE]:`${S.width}px`}}},ee=zt(`div`,e,{ref:[t,T?f:p],state:E,props:[M,s],stateAttributesMapping:IT});return A?(0,Q.jsx)(fE.Provider,{value:i,children:ee}):null}),hE=X.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{computeThumbPosition:o}=ZT(),{hasMeasuredScrollbar:s,viewportState:c}=TT(),l=X.useRef(null),u=X.useRef(s);return pn(()=>{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]),zt(`div`,e,{ref:[t,l],state:c,stateAttributesMapping:IT,props:[{role:`presentation`,style:{minWidth:`fit-content`}},a]})}),gE=X.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}=TT(),m=pE(),h=m===`vertical`;return zt(`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 _E(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 vE(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 yE=(0,X.forwardRef)(function({children:e,className:t,surface:n=!1,surfaceSize:r,surfaceDepth:i,screen:a=!1,...o},s){let c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=Oi();(0,X.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=Cn(t),i=oi(r,{ease:`outQuad`,duration:45}),a=Ai(r,{bounce:.18,duration:180});n=io(t,{scaleY:[{to:e.scaleY,...i},{to:1,...a}],scaleX:[{to:e.scaleX,...i},{to:1,...a}]})},d=(e,t)=>{let n=_E(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=vE(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,Q.jsx)(cE,{render:a?(0,Q.jsx)(li,{}):(0,Q.jsx)(`div`,{}),...o,ref:s,className:`caps-scroll-viewport`,children:(0,Q.jsx)(hE,{style:{minWidth:0},children:e})});return(0,Q.jsxs)(qT,{render:n?(0,Q.jsx)(Ur,{size:r??`md`,depth:i??`shallow`}):(0,Q.jsx)(`div`,{}),ref:c,className:Pn(`caps-scroll-area`,t),children:[a?(0,Q.jsx)(`div`,{className:`caps-display-gasket caps-scroll-display`,children:d}):d,(0,Q.jsx)(Ur,{size:`sm`,depth:`deep`,placement:`embedded`,className:`caps-scroll-track-surface`,children:(0,Q.jsx)(mE,{className:`caps-scroll-track`,children:(0,Q.jsx)(gE,{className:`caps-scroll-thumb`,children:(0,Q.jsx)(`span`,{className:`caps-scroll-thumb-surface`,ref:l})})})})]})}),bE=X.createContext(void 0);function xE(e){let t=X.useContext(bE);if(t===void 0&&!e)throw Error(rn(72));return t}var SE={...da,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},CE=class extends An{constructor(e,t,n){let r=new Qi;super(wE(e,r,t,n),TE(r),SE)}setOpen=(e,t)=>{k(this,e,t,{extraState:{openChangeReason:t.reason}})};cancelPendingOpen(e){this.state.floatingRootContext.dispatchOpenChange(!1,Ht(We,e))}};function wE(e,t,n,r=!1){return{...qi(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 TE(e){return{popupRef:X.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}var EE=ia(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 CE({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}),Or(p,{closeOnActiveTriggerUnmount:!0});let{forceUnmount:y,transitionStatus:b}=Ge(h,p),x=p.useState(`isInstantPhase`),S=p.useState(`instantType`),C=p.useState(`lastOpenChangeReason`),w=X.useRef(null);pn(()=>{m&&t&&p.setOpen(!1,Ht(ua))},[m,t,p]),pn(()=>{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]),pn(()=>{h&&(g??p.set(`payload`,void 0))},[p,g,h]),X.useImperativeHandle(o,()=>({unmount:y,close:()=>p.setOpen(!1,Ht(wt))}),[y,p]);let T=h||_||!t&&a!==`none`;return(0,Q.jsxs)(bE.Provider,{value:p,children:[l&&(0,Q.jsx)(ne,{handle:l,store:p}),T&&(0,Q.jsx)(DE,{store:p,disabled:t,trackCursorAxis:a}),typeof f==`function`?f({payload:v}):f]})});function DE({store:e,disabled:t,trackCursorAxis:n}){let r=e.useState(`floatingRootContext`),i=xt(r,{enabled:!t,referencePress:()=>e.select(`closeOnClick`)}),a=vx(r,{enabled:!t&&n!==`none`,axis:n===`none`?void 0:n}),o=X.useMemo(()=>me(a.reference,i.reference),[a.reference,i.reference]);return Qe(e,{activeTriggerProps:o,inactiveTriggerProps:o,popupProps:i.floating??ce}),null}var OE=X.createContext(void 0);function kE(){let e=X.useContext(OE);if(e===void 0)throw Error(rn(70));return e}var AE=X.forwardRef(function(e,t){let{children:n,container:r,className:i,render:a,style:o,...s}=e,{node:c,subtree:l}=De({container:r,ref:t,componentProps:e,elementProps:s});return!l&&!c?null:(0,Q.jsxs)(X.Fragment,{children:[l,c&&Dx.createPortal(n,c)]})}),jE=X.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return xE().useState(`mounted`)||n?(0,Q.jsx)(OE.Provider,{value:n,children:(0,Q.jsx)(AE,{ref:t,...r})}):null}),ME=X.createContext(void 0);function NE(){let e=X.useContext(ME);if(e===void 0)throw Error(rn(71));return e}var PE=X.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=ht,style:g,..._}=e,v=xE(),y=kE(),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=EC({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=LC(e,X.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,Q.jsx)(ME.Provider,{value:D,children:O})}),FE=X.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,o=xE(),{side:s,align:c}=NE(),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`);pt({open:l,ref:o.context.popupRef,onComplete(){l&&o.context.onOpenChangeComplete?.(!0)}}),Ex(p,{enabled:!m,closeDelay:h});let g=o.useStateSetter(`popupElement`);return zt(`div`,e,{state:{open:l,side:s,align:c,instant:u,transitionStatus:d},ref:[t,o.context.popupRef,g],props:[At,f,ZS(d),a],stateAttributesMapping:ut})}),IE={open:0,warm:!1,cooling:void 0},LE=600,RE=(0,X.createContext)(null);function zE(){let e=(0,X.useContext)(RE);if(!e)throw Error(`Tooltip parts must be used inside <Tooltip>`);return e}var BE=(0,X.forwardRef)(function({children:e,className:t,defaultOpen:n=!1,delayDuration:r=300,onOpenChange:i,open:a,side:o=`top`,...s},c){let l=(0,X.useRef)(null),[u,d]=(0,X.useState)(n),[f,p]=(0,X.useState)(!1),m=a??u;(0,X.useEffect)(()=>{if(m)return IE.open+=1,IE.warm=!0,clearTimeout(IE.cooling),()=>{--IE.open,!(IE.open>0)&&(IE.cooling=setTimeout(()=>{IE.warm=!1},LE))}},[m]);let h=`${(0,X.useId)()}-content`,g=(0,X.useRef)(null),_=()=>{g.current!==null&&(clearTimeout(g.current),g.current=null)},v=e=>{_(),a===void 0&&d(e),i?.(e)};return In(()=>{v(!1)}),(0,X.useEffect)(()=>_,[]),(0,Q.jsx)(RE.Provider,{value:{arrivedWarm:f,cancelClose:_,contentId:h,open:m,scheduleClose:()=>{_(),m&&(g.current=setTimeout(()=>{v(!1)},0))},scheduleOpen:()=>{if(_(),m)return;let e=IE.warm;g.current=setTimeout(()=>{p(e),v(!0)},e?0:Math.max(0,r))},side:o,trigger:l},children:(0,Q.jsx)(EE,{open:m,onOpenChange:v,children:(0,Q.jsx)(`span`,{...s,className:Pn(`relative inline-flex`,t),ref:c,children:e})})})}),VE=(0,X.forwardRef)(function({asChild:e=!1,children:t,className:n,onBlur:r,onFocus:i,onPointerEnter:a,onPointerLeave:o,...s},c){let l=zE(),u=(0,X.useCallback)(e=>{l.trigger.current=e},[l.trigger]);(0,X.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,Q.jsx)(Vn,{...p,className:Pn(n),ref:u,children:t}):(0,Q.jsx)(`button`,{...p,className:Pn(`btn`,n),ref:u,type:s.type??`button`,children:t})}),HE=(0,X.forwardRef)(function({children:e,className:t,onPointerEnter:n,onPointerLeave:r,...i},a){let o=zE(),s=zr(`tooltip`),[c,l]=(0,X.useState)(null);return(0,X.useImperativeHandle)(a,()=>c,[c]),(0,X.useLayoutEffect)(()=>{let e=c;if(!o.open||!e||!Si(e))return;let t=Cn(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:br(t,t.ease),composite:`add`});return()=>{i.cancel()}},[c,o.open,o.arrivedWarm,o.side]),!o.open||!s?null:(0,Q.jsx)(jE,{container:s,children:(0,Q.jsx)(PE,{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,Q.jsx)(FE,{...i,"aria-live":`polite`,className:Pn(`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})})})}),UE={needs_you:`Waiting for you`,running:`Working`,errored:`Failed`,done:`Done`},WE={needs_you:0,errored_unseen:1,running:2,recent:3};function GE(e){return e===`running`||e===`needs_you`}function KE(e,t){return e!==void 0&&(t===void 0||e>t)}function qE(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 JE(e,t){return WE[e.tier]-WE[t.tier]||(t.settledAt??t.createdAt)-(e.settledAt??e.createdAt)||e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId)}var YE=[`Needs you`,`Working`,`Ready`,`Finished`];function XE(e){return e.tier===`running`?`Working`:e.shelf===`active`?`Needs you`:e.ready?`Ready`:`Finished`}function ZE(e){return{key:rD(e.agentId,e.sessionId),shelf:XE(e),attention:e.tier===`needs_you`||e.tier===`errored_unseen`?`${e.tier}:${String(e.settledAt??e.createdAt)}`:null}}function QE(e,t,n){let r=new Map(t.map(e=>[rD(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(ZE).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=YE.flatMap(t=>{let a;a=e===null||n.reorder?i.map(ZE).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:ZE(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:ZE(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 $E(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 eD(e,t,n=null,r){let i=new Set(e.map(e=>e.agentId));return tD(t.filter(e=>!(`kind`in e)&&i.has(e.agentId)&&(n===null||e.agentId===n)),r)}function tD(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=KE(i.settledAt,i.visitedAt),a=t?.agentId===i.agentId&&t.sessionId===i.sessionId?t.state:void 0,o=a?$E(a,i.state):i.state,s=a?a.kind===`idle`:o===`done`&&i.settledAt===void 0,c=qE(o,e);n.push({...i,state:o,ready:s,unseen:e,tier:c,shelf:c===`recent`?`settled`:`active`})}return n.sort(JE),{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 nD(e){return[...e.active,...e.settled].filter(e=>!(e.title===``&&e.ready))}function rD(e,t){return`${e}\u0000${t}`}function iD(e){return e.name}var aD=`Connect a model first`;function oD({children:e}){return(0,Q.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:e})}function sD({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,X.useState)(null),h=`grove-rail-cell relative size-12 rounded-field p-0`,g=r===null&&!(i&&a);return(0,Q.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,Q.jsx)(U,{variant:`ghost`,"aria-label":`All Agents`,"aria-pressed":g,className:`${h} text-xs ${g?`bg-base-300`:``}`,onClick:l,children:(0,Q.jsx)(oD,{children:`All`})}),a?(0,Q.jsx)(U,{variant:`ghost`,"aria-label":`Websites`,"aria-pressed":i,className:`${h} ${i?`bg-base-300`:``}`,onClick:u,children:(0,Q.jsx)(oD,{children:(0,Q.jsx)(ri,{name:`internet`,size:28})})}):null,(0,Q.jsx)(yE,{className:`w-full flex-1`,style:{width:`100%`},children:(0,Q.jsx)(`div`,{className:`flex flex-col items-center gap-1 py-1`,children:t.map(e=>(0,Q.jsx)(U,{variant:`ghost`,"aria-label":iD(e),title:iD(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,Q.jsx)(oD,{children:(0,Q.jsx)(Xr,{activity:n.get(e.agentId)??(p===e.agentId?`thinking`:`idle`),avatar:e.avatar,name:iD(e),size:32})})},e.agentId))})}),o?(0,Q.jsxs)(BE,{side:`right`,children:[(0,Q.jsx)(VE,{asChild:!0,children:(0,Q.jsx)(U,{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,Q.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:(0,Q.jsx)(ve,{size:20})})})}),s?(0,Q.jsx)(HE,{children:aD}):null]}):null]})}function cD({app:e}){let[t,n]=(0,X.useState)(null),r=rs({queryKey:wy.of(e,`team-inbox-notices`,t),enabled:e!==null&&(e.capabilities.has(ng)||e.capabilities.has(rg)),queryFn:async()=>{if(!e)throw Error(`No App connection`);let n=await ug(e.capabilities);try{return await dy(n,t)}finally{await n.close()}}});return!r.isError&&!r.data?.items.length?null:(0,Q.jsx)(`section`,{"aria-label":`Team notices`,className:`min-h-0 shrink-0`,children:(0,Q.jsxs)(yE,{className:`max-h-52 border-b border-base-300`,children:[r.isError?(0,Q.jsx)(`p`,{role:`alert`,className:`text-sm`,children:`Team notices unavailable.`}):(0,Q.jsx)(Dt,{density:`compact`,className:`px-3 py-2`,children:r.data.items.map(e=>(0,Q.jsx)(D,{children:(0,Q.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-[var(--spacing-xs)]`,children:[(0,Q.jsx)(Tn,{className:`col-span-2 grid grid-cols-subgrid`,size:`compact`,tone:`warning`,label:`kind`in e?`Seller closed`:`Installed App safety notice`}),(0,Q.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,Q.jsx)(U,{variant:`ghost`,size:`sm`,onClick:()=>{n(r.data.next)},children:`Older notices`}):null,t===null?null:(0,Q.jsx)(U,{variant:`ghost`,size:`sm`,onClick:()=>{n(null)},children:`Newest notices`})]})})}var lD=900;function uD(e){let[t,n]=(0,X.useState)(null);return(0,X.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let r=e=>{n(e===0||e>=lD)};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 dD({open:e,onOpenChange:t,returnFocus:n,desktop:r,children:i}){let[a,o]=(0,X.useState)(null);return(0,Q.jsxs)(h,{open:r||e,modal:!r,disablePointerDismissal:r,onOpenChange:e=>{r||t(e)},children:[(0,Q.jsx)(`div`,{ref:o,className:`contents`}),(0,Q.jsxs)(we,{container:a,keepMounted:!0,className:`contents`,children:[r?null:(0,Q.jsx)(Lt,{className:`grove-nav-scrim z-30 bg-base-200`}),(0,Q.jsx)(hi,{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 fD({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 pD(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 mD=[],hD=0,{link:gD,unlink:_D,propagate:vD,checkDirty:yD,shallowPropagate:bD}=fD({update(e){return e._update()},notify(e){mD[SD++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,ED(e))}}),xD=0,SD=0,CD,wD=0;function TD(e){try{++wD,e()}finally{--wD||DD()}}function ED(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=_D(n,e)}function DD(){if(!(wD>0)){for(;xD<SD;){let e=mD[xD];mD[xD++]=void 0,e.notify()}xD=0,SD=0}}function OD(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 CD!==void 0&&gD(i,CD,hD),i._snapshot},subscribe(e){let t=pD(e),n={current:!1},r=kD(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=CD,o=t?.compare??Object.is;if(n)CD=i,++hD,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{CD=a,n&&(i.flags&=-5),ED(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&yD(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&bD(e)}}else e&32&&(i.flags=e&-33);return CD!==void 0&&gD(i,CD,hD),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(vD(e),bD(e),DD())}},i}function kD(e){let t=()=>{let t=CD;CD=n,++hD,n.depsTail=void 0,n.flags=6;try{return e()}finally{CD=t,n.flags&=-5,ED(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&&yD(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,ED(this)}};return t(),n}var AD=class{constructor(e,t){this.atom=OD(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(pD(e))}},jD=class{constructor(e){this.atom=OD(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(pD(e))}};function MD(e,t){return typeof e==`function`?new jD(e):t?new AD(e,t):new AD(e)}var ND=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 PD(e,t){return new ND(e,t).maybeExecute}var FD=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)}},ID=new class extends FD{constructor(){super({pluginId:`form-devtools`,reconnectEveryMs:1e3})}};function LD(e,t){return typeof e==`function`?e(t):e}function RD(e,t){return KD(t).reduce((e,t)=>{if(e===null)return null;if(e!==void 0)return e[t]},e)}function zD(e,t,n){let r=KD(t);function i(e){if(!r.length)return LD(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 BD(e,t){let n=KD(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 VD=46,HD=91,UD=93,WD=48,GD=57;function KD(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)===HD),i=!0,a=-1;for(let o=r;o<=t;o++){let s=o<t?e.charCodeAt(o):-1;if(o===t||s===VD||s===HD||s===UD){let t=o-r;if(t>0){let a=i&&(t===1||e.charCodeAt(r)!==WD),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!==UD&&(a!==-1||s!==UD)&&(a!==s||s!==VD&&s!==HD)&&n.push(``);r=o+1,i=!0}else(s<WD||s>GD)&&(i=!1);a=s}return n.length||n.push(``),n}function qD(e){return!(Array.isArray(e)&&e.length===0)}function JD(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 YD(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 XD=e=>!!e&&typeof e==`object`&&`fields`in e;function ZD(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)||!ZD(e[i],t[i]))return!1;return!0}var QD=({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},$D=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:`field`}:e?{newErrorValue:e,newSource:`form`}:{newErrorValue:void 0,newSource:void 0};function eO(e,t){return e==null?t:{...e,...t}}for(var tO=256,nO=[],rO;tO--;)nO[tO]=(tO+256).toString(16).substring(1);function iO(){let e=0,t,n=``;if(!rO||tO+16>256){for(rO=Array(256),e=256;e--;)rO[e]=256*Math.random()|0;e=0,tO=0}for(;e<16;e++)t=rO[tO+e],n+=e===6?nO[t&15|64]:e===8?nO[t&63|128]:nO[t],e&1&&e>1&&e<11&&(n+=`-`);return tO++,n}var aO=PD(e=>ID.emit(`form-state`,{id:e.formId,state:e.store.state}),{wait:300});function oO(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]=oO(e[n]);return t}if(e instanceof Map){let t=new Map;return e.forEach((e,n)=>{t.set(n,oO(e))}),t}if(e instanceof Set){let t=new Set;return e.forEach(e=>{t.add(oO(e))}),t}let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=oO(e[n]));return t}function sO(e,t){return t===e||t.startsWith(`${e}.`)||t.startsWith(`${e}[`)}var cO=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 lO(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 uO=(e,t)=>{let n=lO(e,t);return{form:n,fields:n}},dO={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:uO(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:uO(r.issues,e)}},fO=e=>!!e&&`~standard`in e,pO={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{},_arrayVersion:0,_pendingValidationsCount:0};function mO(e){function t(t){let n=e.getFieldMeta(t)??pO;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=()=>pO;return{bumpArrayVersion:t,handleArrayMove:n,handleArrayRemove:r,handleArraySwap:i,handleArrayInsert:a}}function hO(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 gO=class{constructor(e){this.options={},this.fieldInfo={},this.formGroupApis=new Set,this.mount=()=>{let e=this.store.subscribe(()=>{aO(this)}),t=ID.on(`request-form-state`,e=>{e.payload.id===this._formId&&ID.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}),n=ID.on(`request-form-reset`,e=>{e.payload.id===this._formId&&this.reset()}),r=ID.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(),ID.emit(`form-unmounted`,{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});let{onMount:a}=this.options.validators||{};return ID.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&&!ZD(e.defaultValues,t.defaultValues)&&!this.state.isTouched,r=!ZD(e.defaultState,t.defaultState)&&!this.state.isTouched;if(!(!n&&!r)){if(TD(()=>{this.baseStore.setState(()=>hO(Object.assign({},this.state,r?e.defaultState:{},n?{values:e.defaultValues}:{})))}),n){let e=mO(this);for(let t of Object.keys(this.fieldInfo))Array.isArray(this.getFieldValue(t))&&e.bumpArrayVersion(t)}ID.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=zD(t,e.instance.name,e.instance.options.defaultValue))}),hO({...this.options.defaultState,values:t,fieldMetaBase:r})})},this.validateAllFields=async e=>{let t=[];return TD(()=>{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 TD(()=>{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=JD(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||cO}),r=!1,i={};return TD(()=>{for(let e of n){if(!e.validate)continue;let{formError:n,fieldErrors:a}=_O(this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`},type:`validate`})),o=vO(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)??pO,r=a?.[e],{newErrorValue:s,newSource:c}=QD({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[o]===`form`,previousErrorValue:t?.[o]});c===`form`&&(i[e]={...i[e],[o]:r}),t?.[o]!==s&&this.setFieldMeta(e,(e=pO)=>({...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=vO(`submit`);this.state.errorMap?.[a]&&e!==`submit`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[a]:void 0}}));let o=vO(`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=YD(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||cO});this.state.isFormValidating||this.baseStore.setState(e=>({...e,isFormValidating:!0}));let r=[],i;for(let e of n){if(!e.validate)continue;let n=vO(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}=_O(r);s&&(i=i?{...i,...s}:s);let c=vO(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)??pO,r=i?.[e],{newErrorValue:a,newSource:o}=QD({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[c]===`form`,previousErrorValue:t?.[c]});t?.[c]!==a&&this.setFieldMeta(e,(e=pO)=>({...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})),TD(()=>{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}),ID.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}),ID.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validate`,errors:this.state.errors});return}TD(()=>{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}),TD(()=>{this.baseStore.setState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),ID.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),n()})}catch(e){throw this.baseStore.setState(e=>({...e,isSubmitSuccessful:!1})),ID.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`inflight`,onError:e}),n(),e}},this.getFieldValue=e=>RD(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]:LD(t,n.fieldMetaBase[e])}}))},this.resetFieldMeta=e=>Object.keys(e).reduce((e,t)=>{let n=t;return e[n]=pO,e},{}),this.setFieldValue=(e,t,n)=>{let r=n?.dontUpdateMeta??!1,i=n?.dontRunListeners??!1,a=n?.dontValidate??!1;TD(()=>{r||this.setFieldMeta(e,e=>({...e,isTouched:!0,isDirty:!0,errorMap:{...e?.errorMap,onMount:void 0}})),this.baseStore.setState(n=>({...n,values:zD(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=BD(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),mO(this).bumpArrayVersion(e)},this.insertFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>[...e.slice(0,t),n,...e.slice(t)],eO(r,{dontValidate:!0}));let i=r?.dontValidate??!1;i||await this.validateField(e,`change`),mO(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),eO(r,{dontValidate:!0})),mO(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),eO(n,{dontValidate:!0})),mO(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 zD(zD(e,`${t}`,i),`${n}`,r)},eO(r,{dontValidate:!0})),mO(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},eO(r,{dontValidate:!0})),mO(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,[],eO(t,{dontValidate:!0})),mO(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=RD(this.options.defaultValues,e),i=n??r;return{...t,fieldMetaBase:{...t.fieldMetaBase,[e]:pO},values:i===void 0?t.values:zD(t.values,e,i)}})},this.setErrorMap=e=>{TD(()=>{Object.entries(e).forEach(([e,t])=>{let n=e;if(XD(t)){let{formError:e,fieldErrors:r}=_O(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=>dO.validate({value:this.state.values,validationSource:`form`},e),this.parseValuesWithSchemaAsync=e=>dO.validateAsync({value:this.state.values,validationSource:`form`},e),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=e?.formId??iO(),this._devtoolsSubmissionOverride=!1;let t=hO({...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||!XD(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=MD(t);let n;this.fieldMetaDerived=MD(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=RD(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=!qD(u),f=!o.isDirty,p=ZD(l,this.getFieldInfo(a)?.instance?.options.defaultValue??RD(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=MD(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||!sO(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&&sO(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=MD(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&&XD(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&&ZD(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 fO(e.validate)?dO[e.type](e.value,e.validate):e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function _O(e){return e?XD(e)?{formError:_O(e.form).formError,fieldErrors:e.fields}:{formError:e}:{formError:void 0}}function vO(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 yO=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]:{...pO,isTouched:e.fieldMetaBase[this.name]?.isTouched??pO.isTouched,isBlurred:e.fieldMetaBase[this.name]?.isBlurred??pO.isBlurred,isDirty:e.fieldMetaBase[this.name]?.isDirty??pO.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&&(ZD(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,eO(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,eO(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(e,t,n)=>{this.form.insertFieldValue(this.name,e,t,eO(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(e,t,n)=>{this.form.replaceFieldValue(this.name,e,t,eO(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(e,t)=>{this.form.removeFieldValue(this.name,e,eO(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(e,t,n)=>{this.form.swapFieldValues(this.name,e,t,eO(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(e,t,n)=>{this.form.moveFieldValues(this.name,e,t,eO(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=e=>{this.form.clearFieldValues(this.name,eO(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=JD(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||cO}),r=this.getLinkedFields(e).reduce((t,n)=>{let r=JD(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||cO});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),i=!1;TD(()=>{let e=(e,n)=>{let r=xO(n.cause),a=n.validate?bO(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}=$D({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=xO(`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=YD(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||cO}),r=await t,i=this.getLinkedFields(e).reduce((t,n)=>{let r=YD(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||cO});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)));TD(()=>{s&&this.startValidation();for(let e of c)e.startValidation()});let l=(e,t,n)=>{let i=xO(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=bO(a),c=r[e.name]?.[i],{newErrorValue:l,newSource:u}=$D({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)),TD(()=>{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=>sO(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[xO(e)]?.lastAbortController.abort();let t=[];for(let r of n)r.getInfo().validationMetaMap[xO(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=>dO.validate({value:this.state.value,validationSource:`field`},e),this.parseValueWithSchemaAsync=e=>dO.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)sO(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=MD(e=>{this.form.store.get();let n=this.form.getFieldMeta(this.name)??{...pO,...t.defaultMeta},r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!ZD(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 fO(e.validate)?dO[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 bO(e){if(e)return e}function xO(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 SO(e){return{isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1}}function CO(e){return{...pO,...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 wO=class e{constructor(t){this.options={},this.setFormGroupState=e=>{this.form.baseStore.setState(t=>{let n=t.formGroupStateBase[this.name]??SO({});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&&(ZD(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,{...pO,...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]??SO({...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;EO(t)&&(n=t.group,r=t.fields);let i=TO(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]:SO({})}})),this.fieldInfo.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,groupApi:this})}}},this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,eO(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 yO&&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&&sO(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}=QD({newFormValidatorError:i,isPreviousErrorFromFormValidator:o?.errorSourceMap[e]===`form`,previousErrorValue:s});c&&(a=!0),(s!==c||o?.errorSourceMap[e]!==l)&&this.form.setFieldMeta(n,(t=pO)=>({...t,errorMap:{...t.errorMap,[e]:c},errorSourceMap:{...t.errorSourceMap,[e]:l}}))}return this._lastDistributedFieldNames[e]=r,a},this.validateSync=(t,n,r={})=>{let i=JD(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||cO}),a=(r.skipRelatedFieldValidation?[]:this.getRelatedFields()).reduce((e,n)=>{let r=JD(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||cO});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),o=!1;TD(()=>{let t=(t,r)=>{let i=OO(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&&EO(s)&&(c=s.group,l=s.fields);let u=TO(c),d=n[i],{newErrorValue:f,newSource:p}=$D({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=OO(`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=YD(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||cO}),a=await n,o=r.skipRelatedFieldValidation?[]:this.getRelatedFields(),s=o.reduce((e,n)=>{let r=YD(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||cO});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=OO(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&&EO(o)&&(l=o.group,u=o.fields);let d=TO(l),f=a[t.name]?.[i],{newErrorValue:p,newSource:m}=$D({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 TD(()=>{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=>sO(this.name,e)}),{hasErrored:r}=this.validateSync(e,n[this.name]??{},{skipRelatedFieldValidation:t?.skipRelatedFieldValidation});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[OO(e)]?.lastAbortController.abort(),this.state.meta.errors;let i=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>sO(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})),TD(()=>{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}TD(()=>{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}),TD(()=>{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=MD(e=>{this.form.formGroupMetaDerived.get(),this.form.baseStore.get();let n=this.form.getFormGroupMeta(this.name)??CO(t.defaultMeta),r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!ZD(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(fO(e.validate)){let t=dO[e.type](e.value,e.validate);return e.type===`validate`?DO(t):t.then(DO)}return e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function TO(e){if(e)return e}function EO(e){return!!e&&typeof e==`object`&&`fields`in e}function DO(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 OO(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 kO(e,t){if(!t)return;let n=Object.assign({},e,{state:oO(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 TD(()=>{Object.keys(r).length&&e.baseStore.setState(e=>({...e,...r})),n.state.errorMap!==e.state.errorMap&&e.setErrorMap(n.state.errorMap)}),n}var AO=w();function jO(e,t){return e===t}function MO(e,t=e=>e,n){let r=n?.compare??jO,i=(0,X.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,X.useCallback)(()=>e.get(),[e]);return(0,AO.useSyncExternalStoreWithSelector)(i,a,a,t,r)}var NO=typeof window<`u`?X.useLayoutEffect:X.useEffect;function PO(e){let[t,n]=(0,X.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,X.useState)(()=>new yO({...e})),a=r;(t.form!==e.form||t.name!==e.name)&&(a=new yO({...e}),i(a),n({form:e.form,name:e.name}));let o=MO(a.store,e.mode===`array`?e=>e.meta._arrayVersion||0:e=>e.value),s=MO(a.store,e=>e.meta.isTouched),c=MO(a.store,e=>e.meta.isBlurred),l=MO(a.store,e=>e.meta.isDirty),u=MO(a.store,e=>e.meta.errorMap),d=MO(a.store,e=>e.meta.errorSourceMap),f=MO(a.store,e=>e.meta.isValidating),p=(0,X.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 NO(a.mount,[a]),NO(()=>{a.update(e)}),p}var FO=(({children:e,...t})=>{let n=PO(t),r=(0,X.useMemo)(()=>LD(e,n),[e,n]);return(0,Q.jsx)(Q.Fragment,{children:r})});function IO(){return(0,X.useState)(()=>iO())[0]}var LO=X,RO=`18.3.1`.split(`.`)[0]===`17`?IO:LO.useId;function zO(e){let[t,n]=(0,X.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,X.useState)(()=>new wO({...e}));(t.form!==e.form||t.name!==e.name)&&(i(new wO({...e})),n({form:e.form,name:e.name}));let a=MO(r.store,e=>e.value),o=MO(r.store,e=>e.meta.isTouched),s=MO(r.store,e=>e.meta.isBlurred),c=MO(r.store,e=>e.meta.isDirty),l=MO(r.store,e=>e.meta.errorMap),u=MO(r.store,e=>e.meta.errorSourceMap),d=MO(r.store,e=>e.meta.isValidating),f=MO(r.store,e=>e.meta.isSubmitting),p=MO(r.store,e=>e.meta.isSubmitted),m=MO(r.store,e=>e.meta.submissionAttempts),h=MO(r.store,e=>e.meta.isSubmitSuccessful),g=MO(r.store,e=>e.meta.canSubmit),_=MO(r.store,e=>e.meta.isValid),v=MO(r.store,e=>e.meta.isFieldsValid),y=MO(r.store,e=>e.meta.isFieldsValidating),b=MO(r.store,e=>e.meta.isGroupValid),x=(0,X.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 NO(r.mount,[r]),NO(()=>{r.update(e)}),x}var BO=(({children:e,...t})=>{let n=zO(t),r=(0,X.useMemo)(()=>LD(e,n),[e,n]);return(0,Q.jsx)(Q.Fragment,{children:r})});function VO({form:e,selector:t=e=>e,children:n}){let r=MO(e.store,t);return(0,Q.jsx)(Q.Fragment,{children:LD(n,r)})}function HO(e){let t=RO(),[n,r]=(0,X.useState)(e?.formId),[i,a]=(0,X.useState)(()=>new gO({...e,formId:e?.formId??t}));if(n!==e?.formId){let n=e?.formId??t;a(new gO({...e,formId:n})),r(n)}let o=(0,X.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,Q.jsx)(FO,{...e,form:i})},e.FormGroup=function(e){return(0,Q.jsx)(BO,{...e,form:i})},e.Subscribe=function(e){return(0,Q.jsx)(VO,{form:i,selector:e.selector,children:e.children})},e},[i]);NO(i.mount,[]),NO(()=>{i.update(e)});let s=(0,X.useRef)(!1);return NO(()=>{s.current&&e?.transform&&kO(i,e.transform)},[i,e?.transform]),NO(()=>{s.current=!0}),o}var UO=N(G),WO=N(q({message:G}));function GO(e){for(let t of e.errors){let e=xa(Ra(so(WO(t),e=>e.message),()=>UO(t)));if(e!==void 0&&e.length>0)return e}}var KO={neutral:`progress-neutral`,primary:`progress-primary`,secondary:`progress-secondary`,accent:`progress-accent`,success:`progress-success`,info:`progress-info`,warning:`progress-warning`,error:`progress-error`},qO=(0,X.forwardRef)(function({className:e,tone:t=`primary`,...n},r){return(0,Q.jsx)(`progress`,{...n,"data-complete":n.value!==void 0&&Number(n.value)>=Number(n.max??1)?`true`:void 0,className:Pn(`progress caps-gooey-motion caps-gooey-progress w-full`,KO[t],e),ref:r})});(0,X.forwardRef)(function({label:e,value:t,max:n,tone:r=`info`,className:i,...a},o){return(0,Q.jsxs)(`div`,{...a,ref:o,className:Pn(`caps-game-meter`,i),children:[(0,Q.jsxs)(`div`,{className:`caps-game-meter-readout`,children:[(0,Q.jsx)(`span`,{children:e}),(0,Q.jsxs)(`span`,{className:`caps-game-meter-value`,children:[t,` / `,n]})]}),(0,Q.jsx)(qO,{"aria-label":e,value:t,max:n,tone:r})]})});function JO({className:e,items:t,onCancel:n,onRemove:r,onRetry:i,rowClassName:a}){return t.length?(0,Q.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,Q.jsx)(ZO,{item:e,onCancel:n,onRemove:r,onRetry:i,...a===void 0?{}:{rowClassName:a}},e.id))}):null}function YO({action:e,id:t,onAction:n,retry:r=!1}){return e?(0,Q.jsx)(wi,{"aria-label":e.accessibleLabel,title:e.label,variant:`ghost`,size:`xs`,className:`motion-reduce:transition-none`,icon:r?(0,Q.jsx)(rT,{}):(0,Q.jsx)(re,{}),onClick:()=>void n(t),type:`button`}):null}function XO({item:e}){return(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`span`,{className:`block min-w-0 truncate`,title:e.name,children:e.name}),(0,Q.jsx)(`div`,{className:`caps-upload-details`,children:(0,Q.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 ZO({item:e,onCancel:t,onRemove:n,onRetry:r,rowClassName:i}){return(0,Q.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,Q.jsx)(`img`,{alt:``,className:`caps-upload-preview mask mask-squircle size-8 shrink-0 object-cover`,src:e.preview.url}):(0,Q.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,Q.jsx)($w,{className:`size-4`})}),(0,Q.jsx)(XO,{item:e}),(0,Q.jsx)(QO,{actions:e.actions,id:e.id,onCancel:t,onRemove:n,onRetry:r}),(0,Q.jsx)(qO,{"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 QO({actions:e,id:t,onCancel:n,onRemove:r,onRetry:i}){return(0,Q.jsxs)(`div`,{className:`caps-upload-actions flex min-w-0 flex-wrap justify-end gap-xs`,children:[(0,Q.jsx)(YO,{action:e.retry,id:t,onAction:i,retry:!0}),(0,Q.jsx)(YO,{action:e.cancel,id:t,onAction:n}),(0,Q.jsx)(YO,{action:e.remove,id:t,onAction:r})]})}var $O=X.createContext(void 0);function ek(e){let t=X.useContext($O);if(t===void 0&&!e)throw Error(rn(47));return t}var tk={...da,disabled:e=>e.disabled,instantType:e=>e.instantType===`trigger-change`&&!da.open(e)?void 0:e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,isPressOpenedByTrigger:(e,t)=>e.openChangeReason===`trigger-press`&&da.isOpenedByTrigger(e,t),isTouchPressOpen:(e,t)=>t&&e.openMethod===`touch`&&e.openChangeReason===`trigger-press`,hasTriggerFocusGuards:(e,t)=>da.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},nk=class extends An{constructor(e,t,n){let r=new Qi;super(rk(e,r,t,n),ik(r),tk)}setOpen=(e,t)=>{let n=t.reason===Dr,r=t.reason===`trigger-press`&&t.event.detail===0,i=!e&&(t.reason===`escape-key`||t.reason==null),a=at(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=f(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}),Dx.flushSync(s)):s();let c;r?c=`click`:i?c=`dismiss`:t.reason===`focus-out`&&(c=`focus`),this.set(`instantType`,c)}};function rk(e,t,n,r=!1){let i={...qi(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 ik(e){return{popupRef:X.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:X.createRef(),beforeTriggerFocusGuardRef:X.createRef(),beforeContentFocusGuardRef:X.createRef(),stickIfOpenTimeout:new qe,stickIfOpen:!0,triggerElements:e}}var ak=ia(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=sk(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),ie(u,d),Or(u);let{forceUnmount:m}=Ge(d,u,()=>{u.context.stickIfOpen=!0,u.set(`openChangeReason`,null)});u.useSyncedValues({modal:o}),X.useEffect(()=>{d||u.context.stickIfOpenTimeout.clear()},[u,d]),X.useImperativeHandle(e.actionsRef,()=>({unmount:m,close:()=>u.setOpen(!1,Ht(wt))}),[m,u]);let h=d||f||s!=null;return(0,Q.jsxs)($O.Provider,{value:u,children:[s&&(0,Q.jsx)(ne,{handle:s,store:u}),h&&(0,Q.jsx)(ck,{store:u,modal:o}),typeof t==`function`?t({payload:p}):t]})});function ok(e){return ek(!0)?(0,Q.jsx)(ak,{props:e}):(0,Q.jsx)(he,{children:(0,Q.jsx)(ak,{props:e})})}function sk(e,t){let n=dt((e,n)=>new nk(t,e,n));return X.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function ck({store:e,modal:t}){let n=e.useState(`floatingRootContext`),r=xt(n,{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}}),i=r.reference,a=r.floating;return Qe(e,{activeTriggerProps:i,inactiveTriggerProps:i,popupProps:a}),null}var lk=Tt(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,handle:s,payload:c,openOnHover:l=!1,delay:u=300,closeDelay:d=0,id:f,...p}=e,m=ek(!0),h=vn(s)??m;if(!h)throw Error(rn(74));let g=It(f),_=h.useState(`isTriggerActive`,g),v=h.useState(`floatingRootContext`),y=h.useState(`isOpenedByTrigger`,g),b=h.useState(`triggerPopupId`,g),x=X.useRef(null),{registerTrigger:S,isMountedByThisTrigger:C}=xe(g,x,h,{payload:c,disabled:a,openOnHover:l,closeDelay:d}),w=h.useState(`isPressOpenedByTrigger`,g),T=h.useState(`isTouchPressOpen`,l),E=h.useState(`hasTriggerFocusGuards`,g),D=kx(v,{enabled:!a&&l&&!T,mouseOnly:!0,move:!1,handleClose:Gx(),restMs:u,delay:{close:d},triggerElementRef:x,isActiveTrigger:_,isClosing:()=>h.select(`transitionStatus`)===`ending`}),O=_t(()=>h.context.stickIfOpen),k=ga(v,{stickIfOpen:O}),A=er(()=>h.select(`open`),e=>{h.set(`openMethod`,e)}),j=h.useState(`triggerProps`,C),{getButtonProps:M,buttonRef:ee}=bi({disabled:a,native:o}),te={open(e){return w?I.open(e):be.open(e)}},{handlePreFocusGuardFocus:ne,handleFocusTargetFocus:N}=aw(h,x),P=zt(`button`,e,{state:{disabled:a,open:y},ref:[ee,t,S,x],props:[k.reference,D,j,A,{[an]:``,id:g,"aria-haspopup":`dialog`,"aria-expanded":y,"aria-controls":b},p,M],stateAttributesMapping:te}),re=(0,Q.jsx)(X.Fragment,{children:P},g);return E?(0,Q.jsxs)(X.Fragment,{children:[(0,Q.jsx)(Ui,{ref:h.context.beforeTriggerFocusGuardRef,onFocus:ne}),re,(0,Q.jsx)(Ui,{ref:h.context.triggerFocusTargetRef,onFocus:N})]}):re}),uk=X.createContext(void 0);function dk(){let e=X.useContext(uk);if(e===void 0)throw Error(rn(45));return e}var fk=X.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return ek().useState(`mounted`)||n?(0,Q.jsx)(uk.Provider,{value:n,children:(0,Q.jsx)(vi,{ref:t,...r})}):null}),pk=X.createContext(void 0);function mk(){let e=X.useContext(pk);if(!e)throw Error(rn(46));return e}var hk=X.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=ht,..._}=e,v=ek(),y=dk(),b=Ft(),x=v.useState(`floatingRootContext`),S=v.useState(`mounted`),C=v.useState(`open`),w=v.useState(`openChangeReason`),T=v.useState(`activeTriggerElement`),E=v.useState(`modal`),D=v.useState(`openMethod`),O=v.useState(`positionerElement`),k=v.useState(`instantType`),A=v.useState(`transitionStatus`),j=EC({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`)});IC({store:v,domReference:x.useState(`domReferenceElement`),positionerElement:O,open:C});let M=E===!0&&w!==`trigger-hover`;zC(C&&M,D===`touch`,O,T);let ee=v.useStateSetter(`positionerElement`),te=LC(e,{open:C,side:j.side,align:j.align,anchorHidden:j.anchorHidden,instant:k},{styles:j.positionerStyles,transitionStatus:A,props:_,refs:[t,ee],hidden:!S,inert:!C});return(0,Q.jsxs)(pk.Provider,{value:j,children:[S&&M&&(0,Q.jsx)(Kr,{inert:mr(!C),cutout:T}),(0,Q.jsx)(Bt,{id:b,children:te})]})}),gk=X.createContext(void 0);function _k(){let[e,t]=X.useState(0),n=_t(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:X.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}var vk=X.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:o,...s}=e,c=ek(),l=mk(),u=XS(!0)!=null,{context:d,hasClosePart:f}=_k(),p=c.useState(`open`),m=c.useState(`openMethod`),h=c.useState(`instantType`),g=c.useState(`transitionStatus`),_=c.useState(`popupProps`),y=c.useState(`titleElementId`),b=c.useState(`descriptionElementId`),x=c.useState(`modal`),S=c.useState(`mounted`),C=c.useState(`openChangeReason`),w=c.useState(`activeTriggerElement`),T=c.useState(`floatingRootContext`),E=T.useState(`floatingId`),D=c.useState(`disabled`),O=c.useState(`openOnHover`),k=c.useState(`closeDelay`);pt({open:p,ref:c.context.popupRef,onComplete(){p&&c.context.onOpenChangeComplete?.(!0)}}),Ex(T,{enabled:O&&!D,closeDelay:k});let A=a===void 0?Fr(c.context.popupRef):a,j=x!==!1&&f;c.useSyncedValue(`focusManagerModal`,j);let M=c.useStateSetter(`popupElement`),ee={open:p,side:l.side,align:l.align,instant:h,transitionStatus:g},te=zt(`div`,e,{state:ee,ref:[t,c.context.popupRef,M],props:[_,{id:E,role:`dialog`,...At,"aria-labelledby":y,"aria-describedby":b,onKeyDown(e){u&&or.has(e.key)&&e.stopPropagation()}},ZS(g),s],stateAttributesMapping:ut});return(0,Q.jsx)(v,{context:T,openInteractionType:m,modal:j,disabled:!S||C===`trigger-hover`,initialFocus:A,returnFocus:o,restoreFocus:`popup`,getInsideElements:()=>[c.context.beforeTriggerFocusGuardRef.current],previousFocusableElement:Bi(w)?w:void 0,nextFocusableElement:c.context.triggerFocusTargetRef,beforeContentFocusGuardRef:c.context.beforeContentFocusGuardRef,children:(0,Q.jsx)(gk.Provider,{value:d,children:te})})}),yk=(0,X.forwardRef)(function({children:e,className:t,type:n=`button`,...r},i){return(0,Q.jsxs)(`button`,{...r,ref:i,type:n,className:Pn(`select caps-select caps-combobox-trigger w-full`,t),children:[(0,Q.jsx)(`span`,{children:e}),(0,Q.jsx)(Ie,{className:`caps-select-chevron`,"aria-hidden":`true`})]})});function bk({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,X.useState)(e),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(n),[S,C]=(0,X.useState)(t),w=p??(b===null?[]:[b]),T=m?f??S:!0,E=(0,X.useMemo)(()=>{let e=g.trim().toLowerCase();return e?c.filter(t=>i(t).toLowerCase().includes(e)):c},[i,c,g]),D=nt({getKey:r,isDisabled:s,items:E});(0,X.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(He(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))},ee=(0,X.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:ee,inputValue:g,listboxId:h,onInputChange:j,onInputKeyDown:M,optionId:k,open:T,commit:A,selectedKeys:w,setOpen:O}}function xk(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 ne=(0,X.useId)(),N=k?.props??v,P=_??N?.id??ne,re={id:P,"aria-describedby":[t,N?.[`aria-describedby`]].filter(Boolean).join(` `)||void 0,"aria-invalid":n??N?.[`aria-invalid`],"aria-label":N?.[`aria-label`]??r,"aria-labelledby":N?.[`aria-labelledby`]??i,"aria-required":a??N?.[`aria-required`]},{keyboardNavigation:F,onPointerMove:I,activeItem:ie,activeKey:L,commit:ae,groups:oe,inputValue:se,listboxId:ce,onInputChange:le,onInputKeyDown:R,open:ue,optionId:de,selectedKeys:fe,setOpen:pe}=bk({defaultInputValue:l,defaultOpen:u,defaultValue:d,getKey:p,getSearchText:h,groupBy:g,id:P,isDisabled:b,items:x,onOpenChange:S,onCommit:ee,multiple:w??!1,controlledOpen:T,controlledKeys:te,trigger:k});In(()=>{k&&pe(!1)});let me=zr(`popover`),he=s===void 0?me:s,z=Vi(`.caps-combobox-option[data-active="true"]:not(:disabled), [data-navigation="pointer"] .caps-combobox-option:hover:not(:disabled)`),ge=(0,Q.jsx)(Mr,{...v,...k?{}:re,"aria-activedescendant":ie?de(p(ie)):void 0,"aria-autocomplete":`list`,"aria-controls":ce,"aria-expanded":!0,className:Pn(`input-sm`,v?.className),id:k?v?.id??`${P}-input`:P,onChange:e=>{v?.onChange?.(e),le(e)},onKeyDown:e=>{v?.onKeyDown?.(e),e.defaultPrevented||R(e)},placeholder:v?.placeholder??E,ref:y,role:`combobox`,value:se}),_e=(0,Q.jsx)(`div`,{id:ce,ref:z,className:`caps-combobox-list`,"data-navigation":F?`keyboard`:`pointer`,onPointerMove:I,role:`listbox`,"aria-multiselectable":w??void 0,children:oe.every(e=>e.items.length===0)?(0,Q.jsx)(`div`,{className:`px-md py-md text-sm text-base-content`,children:f}):oe.map(e=>(0,Q.jsxs)(`div`,{"aria-label":e.label||void 0,role:e.label?`group`:void 0,children:[e.label?(0,Q.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=L===t,i={active:r,disabled:n,selected:fe.includes(t)};return(0,Q.jsxs)(`button`,{"aria-disabled":n||void 0,"aria-selected":i.selected,className:`caps-combobox-option`,"data-active":r&&F,disabled:n,id:de(t),onClick:()=>{ae(e)},onMouseDown:e=>{e.preventDefault()},role:`option`,tabIndex:-1,type:`button`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`caps-combobox-check`,children:i.selected?(0,Q.jsx)(yt,{}):null}),D?.(e,r,i)??m(e)]},t)})]},e.label))});return k?(0,Q.jsx)(`div`,{...M,className:Pn(M.className),ref:O,children:(0,Q.jsxs)(ok,{modal:!0,onOpenChange:pe,open:ue,children:[(0,Q.jsx)(lk,{...re,"aria-haspopup":`dialog`,className:`btn`,ref:A,render:k}),he===null?null:(0,Q.jsx)(fk,{container:he,children:(0,Q.jsx)(hk,{align:`start`,side:`bottom`,sideOffset:4,children:(0,Q.jsxs)(vk,{"data-active-tone":o,className:Pn(`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,Q.jsx)(`div`,{className:`caps-combobox-search`,children:ge}),_e]})})})]})}):(0,Q.jsx)(`div`,{...M,className:Pn(M.className),ref:O,children:(0,Q.jsxs)(`div`,{className:Pn(`caps-combobox-panel`,c),"data-active-tone":o,children:[(0,Q.jsx)(`div`,{className:`caps-combobox-search`,children:ge}),_e]})})}function Sk({icon:e,caption:t}){return(0,Q.jsxs)(`span`,{className:`caps-icon-choice-mark`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`caps-icon-choice-art`,children:e}),t?(0,Q.jsx)(`span`,{className:`caps-icon-choice-caption`,children:t}):null,(0,Q.jsx)(`span`,{className:`caps-icon-choice-lamp`})]})}var Ck=(0,X.forwardRef)(function({label:e,icon:t,caption:n,appearance:r,className:i,...a},o){return(0,Q.jsx)(`label`,{className:`caps-icon-choice`,"data-appearance":r===`compact`?r:void 0,children:(0,Q.jsx)(l,{...a,appearance:r??`default`,"aria-label":e,className:Pn(`caps-icon-choice-input`,i),indicator:(0,Q.jsx)(Sk,{icon:t,caption:n}),ref:o})})}),wk=(0,X.forwardRef)(function({label:e,icon:t,hint:n,className:r,...i},a){let o=(0,X.useId)(),s=[i[`aria-describedby`],n?o:null].filter(Boolean).join(` `)||void 0;return(0,Q.jsx)(`label`,{className:`caps-check-key`,children:(0,Q.jsx)(l,{...i,"aria-label":e,"aria-describedby":s,className:Pn(`caps-check-key-input`,r),indicator:(0,Q.jsxs)(`span`,{className:`caps-check-key-face`,"aria-hidden":`true`,children:[t?(0,Q.jsx)(`span`,{className:`caps-check-key-icon`,children:t}):null,(0,Q.jsxs)(`span`,{className:`caps-check-key-copy`,children:[(0,Q.jsx)(`span`,{className:`caps-check-key-label`,children:e}),n?(0,Q.jsx)(`span`,{className:`caps-check-key-hint`,id:o,children:n}):null]}),(0,Q.jsx)(`span`,{className:`caps-check-key-lamp`})]}),ref:a})})});function Tk({className:e,...t}){return(0,Q.jsx)(`div`,{...t,className:Pn(`caps-check-keys`,e)})}function Ek({checked:e}){let t=`caps-radio-${(0,X.useId)().replaceAll(`:`,``)}`,n=(0,X.useRef)(null),r=(0,X.useRef)(e).current,a=(0,X.useRef)(e),o=(0,X.useRef)(null),s=ii(o),{reduced:c}=s;return(0,X.useLayoutEffect)(()=>{if(!n.current)return;let t=c||a.current===e;a.current=e;let r=e?4:0,i=oi(s,{ease:`outCubic`,duration:75}),o=e?Ai(s,{bounce:.65,duration:300}):oi(s,{ease:`inCubic`,duration:100}),l=io(n.current,t?{rx:r,ry:r,cy:6,duration:0}:{rx:[{to:e?3.5:4.15,...i},{to:r,...o}],ry:[{to:e?4.5:3.85,...i},{to:r,...o}],cy:[{to:e?5.85:6.1,...i},{to:6,...o}]});return()=>{l.cancel()}},[e,c,s]),(0,Q.jsxs)(`svg`,{ref:o,className:`caps-radio-visual`,width:`24`,height:`24`,viewBox:`0 0 12 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Q.jsxs)(`defs`,{children:[(0,Q.jsx)(Fi,{id:`${t}-surface`,transform:`matrix(1 0 0 1 6 6)`}),(0,Q.jsx)(qn,{id:`${t}-shadow`}),(0,Q.jsx)(i,{id:`${t}-inset`}),(0,Q.jsx)(`clipPath`,{id:`${t}-well`,children:(0,Q.jsx)(`circle`,{cx:`6`,cy:`6`,r:`5`})})]}),(0,Q.jsx)(`circle`,{className:`caps-radio-track`,cx:`6`,cy:`6`,r:`5.5`,filter:`url(#${t}-inset)`}),(0,Q.jsx)(`g`,{clipPath:`url(#${t}-well)`,children:(0,Q.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 Dk=(0,X.createContext)(null),Ok=(0,X.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,X.useId)(),d=(0,X.useRef)(null);(0,X.useImperativeHandle)(l,()=>{if(!d.current)throw Error(`RadioGroup is not mounted`);return d.current},[]);let f=i??`radio-group-${u}`,[p,m]=(0,X.useState)(n),h=s??p;return(0,X.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,Q.jsx)(Dk.Provider,{value:{disabled:r,name:f,onValueChange:e=>{s===void 0&&m(e),a?.(e)},value:h},children:(0,Q.jsx)(`fieldset`,{...c,className:Pn(`flex gap-md`,o===`horizontal`?`flex-row flex-wrap`:`flex-col`,t),disabled:r,role:c.role??`radiogroup`,ref:d,children:e})})}),kk=(0,X.forwardRef)(function({className:e,indicator:t,onChange:n,onClick:r,value:i,...a},o){let s=(0,X.useContext)(Dk);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,Q.jsxs)(`span`,{className:`caps-radio`,"data-checked":c,"data-custom-indicator":t!==void 0||void 0,children:[(0,Q.jsx)(`input`,{...a,"aria-checked":c,checked:c,className:Pn(`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,Q.jsx)(Ek,{checked:c}):t]})}),Ak=(0,X.forwardRef)(function({description:e,id:t,meta:n,title:r,...i},a){let o=(0,X.useContext)(Dk),s=(0,X.useId)(),c=t??s,l=o?.value===i.value,u=o?.disabled===!0||i.disabled===!0;return(0,Q.jsxs)(`label`,{className:`caps-choice-card`,"data-checked":l,"data-disabled":u||void 0,htmlFor:c,children:[(0,Q.jsx)(kk,{...i,"aria-describedby":e?`${c}-description`:void 0,"aria-labelledby":`${c}-title`,id:c,ref:a}),(0,Q.jsxs)(`span`,{className:`caps-choice-card-copy`,children:[(0,Q.jsx)(`span`,{className:`caps-choice-card-title`,id:`${c}-title`,children:r}),e?(0,Q.jsx)(`span`,{className:`caps-choice-card-description`,id:`${c}-description`,children:e}):null]}),n?(0,Q.jsx)(`span`,{className:`caps-choice-card-meta`,children:n}):null]})}),jk=(0,X.forwardRef)(function({label:e,icon:t,caption:n,art:r=`dim`,className:i,...a},o){return(0,Q.jsx)(`label`,{className:`caps-icon-choice`,"data-art":r===`color`?r:void 0,children:(0,Q.jsx)(kk,{...a,"aria-label":e,className:Pn(`caps-icon-choice-input`,i),indicator:(0,Q.jsx)(Sk,{icon:t,caption:n}),ref:o})})}),Mk=(0,X.forwardRef)(function({label:e,color:t,className:n,...r},i){return(0,Q.jsx)(`label`,{className:`caps-icon-choice`,"data-art":`color`,"data-swatch":``,title:e,children:(0,Q.jsx)(kk,{...r,"aria-label":e,className:Pn(`caps-icon-choice-input`,n),indicator:(0,Q.jsx)(Sk,{icon:(0,Q.jsx)(`span`,{className:`caps-swatch-dot`,style:{backgroundColor:t}})}),ref:i})})}),Nk=(0,X.forwardRef)(function({className:e,invalid:t,...n},r){return(0,Q.jsxs)(`span`,{className:`caps-select-shell`,children:[(0,Q.jsx)(`select`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:Pn(`select select-bordered caps-select w-full`,t&&`select-error`,e),ref:r}),!n.multiple&&(!n.size||n.size<=1)?(0,Q.jsx)(Ie,{className:`caps-select-chevron`,"aria-hidden":`true`}):null]})});function Pk({checked:e}){let t=`caps-switch-${(0,X.useId)().replaceAll(`:`,``)}`,n=(0,X.useRef)(null),r=(0,X.useRef)(null),a=(0,X.useRef)(e).current,o=(0,X.useRef)(e),s=Oi();return(0,X.useLayoutEffect)(()=>{if(!n.current||!r.current)return;let t=s||o.current===e;o.current=e;let i=e?16:8,a=Cn(n.current),c=Ai(a,{bounce:.25,duration:440}),l=oi(a,{ease:`inOutSine`,duration:100}),u=io(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=io(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,s]),(0,Q.jsxs)(`svg`,{className:`caps-switch-visual`,width:`40`,height:`24`,viewBox:`0 0 20 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Q.jsxs)(`defs`,{children:[(0,Q.jsx)(Fi,{ref:r,id:`${t}-surface`,transform:a?`matrix(2 0 0 1 10 6)`:`matrix(1 0 0 1 6 6)`}),(0,Q.jsx)(qn,{id:`${t}-shadow`}),(0,Q.jsx)(i,{id:`${t}-inset`}),(0,Q.jsx)(`clipPath`,{id:`${t}-track`,children:(0,Q.jsx)(`rect`,{x:`1`,y:`1`,width:`18`,height:`10`,rx:`5`})})]}),(0,Q.jsx)(`rect`,{className:`caps-switch-track`,filter:`url(#${t}-inset)`,x:`0.5`,y:`0.5`,width:`19`,height:`11`,rx:`5.5`}),(0,Q.jsx)(`g`,{clipPath:`url(#${t}-track)`,children:(0,Q.jsx)(`rect`,{ref:n,x:`2`,y:`2`,width:a?16:8,height:`8`,rx:`4`,fill:`url(#${t}-surface)`,filter:`url(#${t}-shadow)`})})]})}var Fk=(0,X.forwardRef)(function({className:e,checked:t,defaultChecked:n=!1,onChange:r,onCheckedChange:i,...a},o){let s=(0,X.useRef)(null),[c,l]=(0,X.useState)(n),u=t??c;return(0,X.useImperativeHandle)(o,()=>{if(!s.current)throw Error(`Switch input is not mounted`);return s.current},[]),(0,X.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,Q.jsxs)(`span`,{className:`caps-switch`,"data-checked":u,children:[(0,Q.jsx)(`input`,{...a,checked:u,className:Pn(`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,Q.jsx)(Pk,{checked:u})]})}),Ik=N(G),Lk=N(r),Rk=N(Br(Yn)),zk=N(B(G)),Bk=B(kr(File)),Vk=N(Bk),Hk=J([G,Yn,r,Ln,yn,B(G),Bk]),Uk=N(Hk),Wk=e=>Ca(Ik(e.state.value),()=>``),Gk=e=>Ca(Lk(e.state.value),()=>!1),Kk=e=>Ca(Rk(e.state.value),()=>null),qk=e=>Ca(zk(e.state.value),()=>[]),Jk=e=>Ca(Vk(e.state.value),()=>[]),Yk=e=>Ca(Uk(e.state.value),()=>null);function Xk({field:e,spec:t,locked:n,...r}){let[i,a]=(0,X.useState)(!1);return(0,Q.jsxs)(St,{children:[(0,Q.jsx)(Mr,{...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:Wk(e),onBlur:e.handleBlur,onChange:t=>{e.handleChange(t.currentTarget.value)}}),(0,Q.jsx)(U,{type:`button`,variant:`outline`,size:`icon`,"aria-label":i?`Hide`:`Show`,"aria-pressed":i,disabled:n,onClick:()=>{a(e=>!e)},children:i?(0,Q.jsx)(Zw,{"aria-hidden":`true`}):(0,Q.jsx)(Qw,{"aria-hidden":`true`})})]})}var Zk={text:`text`,email:`email`,url:`url`,tel:`tel`};function Qk({spec:e,field:t,locked:n,...r}){let i=Jk(t),a=n||e.readOnly===!0,o=(0,X.useRef)(null);return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-sm`,children:[(0,Q.jsx)(Zr,{asChild:!0,children:(0,Q.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,Q.jsx)(U,{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,Q.jsx)(JO,{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 $k({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,Q.jsx)(Mr,{...a,type:Zk[e.kind],inputMode:e.kind===`text`?void 0:e.kind,autoComplete:e.autoComplete,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:Wk(t),onChange:e=>{i(e.currentTarget.value)}});case`textarea`:return(0,Q.jsx)(Tr,{...a,rows:e.rows??3,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:Wk(t),onChange:e=>{i(e.currentTarget.value)}});case`secret`:return(0,Q.jsx)(Xk,{...r,field:t,spec:e,locked:n});case`money`:return(0,Q.jsxs)(St,{children:[(0,Q.jsx)(x,{className:`caps-field-currency`,children:e.currency??`USD`}),(0,Q.jsx)(Mr,{...a,inputMode:`decimal`,autoComplete:`off`,className:`caps-field-amount`,placeholder:e.placeholder??`0.00`,readOnly:e.readOnly,value:Wk(t),onChange:e=>{i(e.currentTarget.value)}})]});case`date`:return(0,Q.jsx)(Mr,{...a,type:`date`,readOnly:e.readOnly,value:Wk(t),onChange:e=>{i(e.currentTarget.value)}});case`number`:return(0,Q.jsx)(ta,{...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:Kk(t),onValueChange:e=>{t.handleChange(e)}});case`select`:return(0,Q.jsxs)(Nk,{...a,value:Wk(t),onChange:e=>{i(e.currentTarget.value)},children:[e.placeholder===void 0?null:(0,Q.jsx)(`option`,{value:``,disabled:!0,children:e.placeholder}),e.options.map(e=>(0,Q.jsx)(`option`,{value:e.value,disabled:e.disabled,children:e.label},e.value))]});case`combobox`:return(0,Q.jsx)(xk,{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:Wk(t),...e.placeholder===void 0?{}:{placeholder:e.placeholder},trigger:(0,Q.jsx)(yk,{name:e.name,disabled:n||e.readOnly===!0,onBlur:t.handleBlur,children:e.options.find(e=>e.value===Wk(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,Q.jsx)(Qk,{...r,spec:e,field:t,locked:n});case`checkbox`:return(0,Q.jsx)(l,{...a,disabled:n||e.readOnly===!0,checked:Gk(t),onChange:e=>{t.handleChange(e.currentTarget.checked)}});case`switch`:return(0,Q.jsx)(Fk,{...a,disabled:n||e.readOnly===!0,checked:Gk(t),onCheckedChange:e=>{t.handleChange(e)}});case`radio`:case`icon-radio`:case`checkboxes`:case`icon-checkboxes`:return null}}var eA=new Set([`radio`,`icon-radio`,`checkboxes`,`icon-checkboxes`]);function tA({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=qk(t),s=(e,r)=>{t.handleChange(r?[...n,e]:n.filter(t=>t!==e))};return(0,Q.jsx)(hn,{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,Q.jsx)(`div`,{className:`caps-field-icon-choices`,children:e.options.map(r=>(0,Q.jsx)(Ck,{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,Q.jsx)(Tk,{children:e.options.map(r=>(0,Q.jsx)(wk,{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,Q.jsx)(hn,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:(0,Q.jsx)(Ok,{name:e.name,"aria-label":o,value:Wk(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,Q.jsx)(jk,{value:t.value,label:t.label,...t.caption===void 0?{}:{caption:t.caption},icon:t.icon,disabled:t.disabled},t.value):s?(0,Q.jsx)(Ak,{value:t.value,title:t.label,description:t.description,meta:t.meta,disabled:t.disabled},t.value):(0,Q.jsx)(dr,{label:t.label,orientation:`inline`,children:(0,Q.jsx)(kk,{value:t.value,disabled:t.disabled})},t.value))})})}function nA({spec:e,field:t,locked:n,error:r,render:i,...a}){return i({name:e.name,label:e.label,help:e.help,value:Yk(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 rA({form:e,spec:t,locked:n,layout:r}){let i=PO({form:e,name:t.name}),a=MO(e.store,e=>e.submissionAttempts>0),o=i.state.meta.isBlurred||a?GO(i.state.meta):void 0;if(t.render===void 0&&eA.has(t.kind))return(0,Q.jsx)(tA,{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,Q.jsx)(dr,{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,Q.jsx)($k,{spec:t,field:i,locked:n}):(0,Q.jsx)(nA,{spec:t,field:i,locked:n,error:o,render:t.render})})}var iA=N(Wn(G,Hk));function aA({form:e,spec:t,locked:n,layout:r}){let i=t.when;return MO(e.store,e=>i===void 0||i(Ca(iA(e.values),()=>({}))))?(0,Q.jsx)(rA,{form:e,spec:t,locked:n,layout:r}):null}function oA({form:e,section:t,locked:n,layout:r}){let i=t.fields.map(t=>(0,Q.jsx)(aA,{form:e,spec:t,locked:n,layout:r},t.name));return t.title===void 0?i:(0,Q.jsx)(On,{title:t.title,description:t.description,layout:r,children:i})}function sA({model:e,names:t,disabled:n=!1,layout:r}){let i=e.form;return t===void 0?e.description.sections.map(e=>(0,Q.jsx)(oA,{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,Q.jsx)(aA,{form:i,spec:a,locked:n,layout:r},t)})}var cA=class{annotation;constructor(e){this.annotation=e}},lA=class{sections;constructor(e){this.sections=e}},uA=`caps/form`,dA=0;function fA(e){dA+=1;let t={[`${uA}:${String(dA)}`]:new cA(e)};return e.label!==void 0&&(t.title=e.label),e.help!==void 0&&(t.description=e.help),t}G.annotate(fA({kind:`secret`})).pipe(aa(`Secret`));var pA=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 mA(e){return Object.values(e??{}).reduce((e,t)=>t instanceof cA?{...e,...t.annotation}:e,{})}function hA(e){return e.reduce((e,t)=>({...e,...mA(t)}),{})}function gA(e){let t=e?.[uA];return t instanceof lA?t.sections:{}}var _A=N(G);function vA(e){if(Zn(e))return Fa(_A(e.literal),{onNone:()=>null,onSome:e=>[e]});if(!ci(e))return null;let t=[];for(let n of e.types){if(Dn(n))continue;let e=vA(n);if(e===null)return null;t.push(...e)}return t}function yA(e){if(wr(e))return{type:`string`,literals:[]};if(ti(e))return{type:`number`,nullable:!1};if(o(e))return{type:`boolean`};let t=vA(e);if(t!==null)return{type:`string`,literals:t};if(gt(e)){let[t]=e.rest;if(t===void 0)return null;if(wr(t))return{type:`strings`,literals:[]};let n=vA(t);return n===null?null:{type:`strings`,literals:n}}if(ci(e)){let t=e.types.filter(e=>!Dn(e)&&!zi(e)),n=e.types.some(e=>zi(e)),[r]=t;if(t.length!==1||r===void 0)return null;let i=yA(r);return i?.type===`number`?{type:`number`,nullable:n}:n?null:i}return null}function bA(e){let t=e.ast;if(!Di(t))throw Error(`A schema form needs a Schema.Struct.`);return{fields:t.propertySignatures.map(e=>{let t=String(e.name),n=Wi(e.type),r=hA([e.type.annotations,...(e.type.checks??[]).map(e=>e.annotations)]),i=r.kind===`file`?{type:`files`}:yA(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:Hr(e.type),description:zn(e.type)}}),sections:gA(Ni(t))}}function xA(e){let t=e,n=!1,r=!1;for(;;)if(t instanceof xo)n=!0,t=t.unwrap();else if(t instanceof vo)r=!0,t=t.unwrap();else if(t instanceof ao)t=t.unwrap();else if(t instanceof Qa)t=t.in;else return{node:t,optional:n,nullable:r}}function SA(e){if(e instanceof fo){let t=e.options.map(e=>SA(e));return t.some(e=>e===null)?null:t.flatMap(e=>e??[])}let t=e instanceof qa?e.options:e instanceof mo?[...e.values]:null;if(t===null)return null;let n=t.map(e=>_A(e));return n.every(lo)?n.map(e=>e.value):null}function CA(e){let{node:t,nullable:n}=xA(e);if(t instanceof to)return{type:`string`,literals:[]};if(t instanceof Za)return{type:`number`,nullable:n};if(t instanceof go)return{type:`boolean`};let r=SA(t);if(r!==null)return{type:`string`,literals:r};if(t instanceof po){let e=xA(t.element).node;if(e instanceof to)return{type:`strings`,literals:[]};let n=SA(e);return n===null?null:{type:`strings`,literals:n}}return null}function wA(e){let t=[e];for(;;){let e=t[t.length-1];if(e===void 0)break;let n=e instanceof xo||e instanceof vo||e instanceof ao?e.unwrap():e instanceof Qa?e.in:e;if(n===e)break;t.push(n)}return t.reverse().map(e=>_o.get(e))}function TA(e){return wA(e).reduce((e,t)=>({...e,...t}),{})}function EA(e){return Object.entries(e.shape)}function DA(e){let t=xA(e).node;if(!(t instanceof uo))throw Error(`A schema form needs a z.object.`);return{fields:EA(t).map(([e,t])=>{let n=hA(wA(t)),r=n.kind===`file`?{type:`files`}:CA(t);if(r===null)throw Error(`Schema field "${e}" has no form control. Annotate it with field({ render }) or a kind.`);let i=TA(t);return{name:e,valueType:r,optional:xA(t).optional,annotation:n,title:i.title,description:i.description}}),sections:gA(TA(e))}}function OA(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??pA(e),description:r.description,meta:r.meta,icon:r.icon,caption:r.caption,disabled:r.disabled===!0}})}function kA(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 AA(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 jA(e){let t=e instanceof ho?DA(e):bA(e),n=t.fields.map((e,t)=>{let{kind:n,...r}=e.annotation,i=OA(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??pA(e.name),help:a,kind:n??kA(e.valueType,i),options:i,optionalInSchema:e.optional,index:t}}),r={};t.fields.forEach((e,t)=>{let i=n[t];i&&(r[e.name]=AA(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 MA(e){let t=e instanceof ho?e:yi(e);return{"~standard":{...t[`~standard`],validate:e=>{let n=t[`~standard`].validate(e);return n instanceof Promise?n.then(e=>NA(e)):NA(n)}}}}function NA(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 PA=`onServer`;function FA(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 IA(e){if(FA(e))return()=>void 0;let t=new MutationObserver(()=>{FA(e)&&t.disconnect()});return t.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[`aria-invalid`]}),()=>{t.disconnect()}}function LA(e){return e.state.meta.errorMap.onServer!==void 0}function RA(e){e.setMeta(e=>({...e,errorMap:{...e.errorMap,[PA]:void 0}}))}function zA(e,t,n){e.setFieldMeta(t,e=>({...e,isBlurred:!0,errorMap:{...e.errorMap,[PA]:n}}))}function BA(e){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(e.defaultValues),[s,c]=(0,X.useState)(null);ZD(a,e.defaultValues)||(o(e.defaultValues),c(null));let{schema:l}=e,u=(0,X.useMemo)(()=>jA(l),[l]),d=(0,X.useMemo)(()=>MA(l),[l]),f=HO({defaultValues:s??a,validators:{onChange:d,onSubmit:d},listeners:{onChange:({fieldApi:e})=>{n(null),i(null),LA(e)&&RA(e)}},onSubmit:async({value:t,formApi:r})=>{n(null),i(null);let a=await MA(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&&zA(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 VA(e){return{dirty:MO(e.form.store,e=>!e.isDefaultValue),submitting:MO(e.form.store,e=>e.isSubmitting),canSubmit:MO(e.form.store,e=>e.canSubmit)}}function HA({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}=VA(e),f=(0,X.useRef)(null),p=(0,X.useRef)(()=>void 0);return(0,X.useEffect)(()=>()=>{p.current()},[]),(0,Q.jsxs)(Gi,{...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=IA(t))})},children:[c??(0,Q.jsx)(sA,{model:e,disabled:l,layout:o}),s===void 0?(0,Q.jsx)(GA,{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 UA({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i,...a}){let o=BA({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i});return(0,Q.jsx)(HA,{...a,model:o})}function WA(e){return`model`in e?(0,Q.jsx)(HA,{...e}):(0,Q.jsx)(UA,{...e})}function GA({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}=VA(e),d=u?null:e.saved&&!l?(0,Q.jsx)(Tn,{tone:`success`,size:`compact`,label:e.saved}):l?(0,Q.jsx)(Tn,{tone:`neutral`,size:`compact`,label:o}):null;return(0,Q.jsxs)(ca,{...c,error:e.error,status:d,children:[r?(0,Q.jsx)(U,{type:`button`,variant:`ghost`,disabled:u,onClick:r,children:i}):n&&l?(0,Q.jsx)(U,{type:`button`,variant:`ghost`,disabled:u,onClick:e.discard,children:n}):null,(0,Q.jsx)(U,{...s,type:`submit`,loading:u,disabled:u||!l&&!a,title:!l&&!a?`No changes to save`:void 0,children:t})]})}var KA=e=>e,qA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing burger path: ${t}`);return n},JA={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=Ao(e,t,a,{blushMode:`medium-alias`,hideMouth:!0}),s=e.group({parent:r,name:`burger.mouth`,translate:{y:1,z:10}}),c=KA({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=KA({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:qA(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:qA(l,n),stroke:1.5,translate:a}),u[n]=r}return{root:n,variants:{eyes:o.eyes,mouth:u,blush:o.blush}}},expressions:ko,activities:jo,defaultPresentation:{activity:`idle`,expression:`normal`}},YA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing cat face node: ${t}`);return n},XA=e=>e,ZA={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=Ao(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=XA({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:YA(c,`normal`),happy:c.happy,sad:YA(c,`sad`),angry:YA(c,`angry`),surprised:c.surprised,dead:c.dead,small:YA(c,`small`),worried:YA(c,`worried`),pout:c.pout,open:c.open};return{root:n,variants:{eyes:a.eyes,mouth:f,blush:a.blush}}},expressions:ko,activities:{...jo,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`}},QA={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=Ao(e,t,a,{blushMode:`none`});return{root:n,variants:{eyes:o.eyes,mouth:o.mouth,blush:o.blush}}},expressions:ko,activities:{...jo,error:{geometry:{eyes:`dead`,mouth:`dead`},motion:{target:`root`,rotate:{x:.9},durationMs:600,repeat:`none`},mouseInfluence:.1}},defaultPresentation:{activity:`idle`,expression:`sleepy`}},$A={mushroom:[`cap`,`capSpot`],cat:[`body`,`stripes`],burger:[`topBun`,`bottomBun`]},ej={mushroom:QA,cat:ZA,burger:JA};function tj(e){let t=Do(Oo(ej[e])),n=Eo.parse(t.data);return{controls:t.controls,expressions:Object.keys(n.expressions),identitySlots:$A[e]}}var nj=new Map;function rj(e){let t=nj.get(e);return t||(t=tj(e),nj.set(e,t)),t}var ij=Object.freeze({get mushroom(){return rj(`mushroom`)},get cat(){return rj(`cat`)},get burger(){return rj(`burger`)}}),aj={mushroom:`Shiitake`,cat:`Cat`,burger:`Burger`},oj=[[`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 sj(e,t){if(t===e.character)return e;let n=ij[e.character].identitySlots,r=ij[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 cj(e,[,t,n]){let r=ij[e.character].identitySlots;return{...e,appearance:{...e.appearance,...Object.fromEntries(r.map((e,r)=>[e,r===0?t:n]))}}}function lj(e,t){let n=0;for(let e of t)n+=e.codePointAt(0)??0;return cj(e,oj[n%oj.length]??oj[0])}function uj({value:e,disabled:t=!1,onChange:n}){let r=ij[e.character].identitySlots,i=oj.find(([,t,n])=>r.every((r,i)=>e.appearance[r]===(i===0?t:n)))?.[0]??``;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(hn,{legend:`Avatar`,icon:(0,Q.jsx)(ri,{name:`agent`}),layout:`columns`,disabled:t,children:(0,Q.jsx)(Ok,{"aria-label":`Character`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:e.character,onValueChange:t=>{n(sj(e,Ue.shape.character.parse(t)))},children:Er.map(t=>(0,Q.jsx)(jk,{value:t,label:aj[t],caption:aj[t],art:`color`,icon:(0,Q.jsx)(Xr,{avatar:sj(e,t),name:aj[t],size:32})},t))})}),(0,Q.jsx)(hn,{legend:`Colour`,icon:(0,Q.jsx)(ri,{name:`prints`}),layout:`columns`,disabled:t,children:(0,Q.jsx)(Ok,{"aria-label":`Colour`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:i,onValueChange:t=>{let r=oj.find(([e])=>e===t);r&&n(cj(e,r))},children:oj.map(([e,t])=>(0,Q.jsx)(Mk,{value:e,label:e,color:t},e))})})]})}var dj=qr.check(y(1,{message:`Give your Agent a name.`}),Y(256,{message:`Use at most 256 characters.`})),fj=N(dj),pj=e=>e===`new`||e===`none`?e:e.computerId,mj=e=>e===`new`||e===`none`?e:{computerId:e},hj=e=>e?.[0]?.computerId??`none`;function gj(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,Q.jsx)(ri,{name:`computer`}),options:n};return G.check(z(e=>Object.hasOwn(n,e)||`Choose a Computer.`)).annotate(fA(t===null?r:{...r,help:t}))}var _j=F({family:`grove-agent-create-request`,version:1,kinds:{request:{prefix:`request`}}});function vj({create:e,computers:t,computersUnavailable:n,inputRef:r,error:i,addCredit:a,onCancel:o}){let s=(0,X.useRef)(null),[c,l]=(0,X.useState)(()=>{let e=_j.request.generate();return lj(Xe(e),e)}),u=(0,X.useMemo)(()=>q({name:dj.annotate(fA({label:`Name`,icon:(0,Q.jsx)(ri,{name:`write`}),render:e=>(0,Q.jsx)(Mr,{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:gj(t??[],n)}),[r,t,n]),d=t!==null,[f,p]=(0,X.useState)(!1),m={name:``,computer:hj(t)},h=BA({schema:u,defaultValues:m,onSubmit:async({name:t,computer:n})=>{let r=d?mj(n):void 0,i=s.current;if(i?.name!==t||(i.computer===void 0?void 0:pj(i.computer))!==(r===void 0?void 0:pj(r))||i.avatar!==c){let e={name:t,requestId:_j.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}=VA(h);return(0,Q.jsxs)(WA,{model:h,layout:`columns`,"aria-label":`Create Agent`,footer:(0,Q.jsxs)(ca,{divider:!1,error:a===null?i:null,children:[(0,Q.jsx)(U,{type:`button`,variant:`ghost`,"aria-expanded":f,onClick:()=>{p(e=>!e)},children:f?`Fewer options`:`More options`}),(0,Q.jsx)(U,{type:`button`,variant:`ghost`,disabled:g,onClick:o,children:`Cancel`}),(0,Q.jsx)(U,{type:`submit`,className:`shrink-0 disabled:-outline-offset-1`,variant:`primary`,loading:g,disabled:g||!_||!v,children:`Create Agent`})]}),onSubmitCapture:e=>{Ia(fj(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!==pj(s.current.computer))&&(s.current=null)},children:[a===null?null:(0,Q.jsx)(yj,{openBilling:a}),(0,Q.jsx)(sA,{model:h,names:d&&f?[`name`,`computer`]:[`name`]}),f?(0,Q.jsx)(uj,{value:c,disabled:g,onChange:e=>{l(e),s.current=null}}):null]})}function yj({openBilling:e}){let t=is({mutationFn:e});return(0,Q.jsx)(cn,{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 bj({open:e,pending:t,error:n,addCredit:r,computers:i,create:a,onClose:o,returnFocus:s}){let c=(0,X.useRef)(null);return(0,Q.jsx)(h,{open:e,onOpenChange:e=>{!e&&!t&&o()},children:(0,Q.jsxs)(Nt,{className:`flex flex-col gap-lg`,initialFocus:c,finalFocus:s,keepMounted:!1,children:[(0,Q.jsxs)(Ae,{children:[(0,Q.jsx)(tn,{children:`New Agent`}),(0,Q.jsx)(Ut,{children:`Agents chat, write and work with you.`})]}),i.status===`loading`?(0,Q.jsx)(`p`,{role:`status`,children:`Loading your Computers…`}):(0,Q.jsx)(vj,{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 xj({open:e,agents:t,defaultAgentId:n,start:r,pending:i,onClose:a,onNewAgent:o,returnFocus:s}){let c=BA({schema:(0,X.useMemo)(()=>q({agentId:G.check(z(e=>t.some(t=>t.agentId===e)||`Choose an Agent.`)).annotate(fA({label:`Agent`,kind:`select`,options:Object.fromEntries(t.map(e=>[e.agentId,iD(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}=VA(c);return(0,Q.jsx)(h,{open:e,onOpenChange:e=>{!e&&!i&&!c.form.state.isSubmitting&&a()},children:(0,Q.jsxs)(Nt,{className:`flex flex-col gap-lg`,keepMounted:!1,finalFocus:s,children:[(0,Q.jsxs)(Ae,{children:[(0,Q.jsx)(tn,{children:`New conversation`}),(0,Q.jsx)(Ut,{children:`Choose who to talk with.`})]}),t.length===0?(0,Q.jsxs)(`div`,{className:`grid gap-sm`,children:[(0,Q.jsx)(`p`,{children:`No Agent has conversation access yet.`}),o?(0,Q.jsx)(U,{onClick:o,children:`New Agent`}):null,(0,Q.jsx)(U,{variant:`ghost`,onClick:a,children:`Cancel`})]}):(0,Q.jsx)(WA,{model:c,"aria-label":`New conversation`,footer:(0,Q.jsxs)(ca,{divider:!1,error:c.error,children:[(0,Q.jsx)(U,{type:`button`,variant:`ghost`,disabled:l||i,onClick:a,children:`Cancel`}),(0,Q.jsx)(U,{type:`submit`,loading:l||i,disabled:!u||l||i,children:`Start`})]})})]})})}var Sj=X.useLayoutEffect;function Cj(e,t,n){X.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 wj(e){let t=X.useRef(null);return X.useImperativeHandle(e,()=>t.current,[]),t}function Tj(e){return e[e.length-1]}function Ej(e){return typeof e==`function`}function Dj(e,t){return Ej(e)?e(t):e}var Oj=Object.prototype.hasOwnProperty,kj=Object.prototype.propertyIsEnumerable;function Aj(e){for(let t in e)if(Oj.call(e,t))return!0;return!1}var jj=()=>Object.create(null),Mj=(e,t)=>Nj(e,t,jj);function Nj(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=Lj(e)&&Lj(i);if(!a&&!(Fj(e)&&Fj(i)))return i;let o=a?e:Pj(e);if(!o)return i;let s=a?i:Pj(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:Oj.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=Nj(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function Pj(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(!kj.call(e,r))return!1;t.push(r)}return t}function Fj(e){if(!Ij(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Ij(n)||!n.hasOwnProperty(`isPrototypeOf`))}function Ij(e){return Object.prototype.toString.call(e)===`[object Object]`}function Lj(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Rj(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(!Rj(e[r],t[r],n))return!1;return!0}if(Fj(e)&&Fj(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!Rj(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||!Rj(e[o],t[o],n)))return!1;return i===a}return!1}var zj=/[\x00-\x1f\x7f"<>`{}]/g;function Bj(e){return e.replace(zj,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function Vj(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 Bj(t)}var Hj=[`http:`,`https:`,`mailto:`,`tel:`];function Uj(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function Wj(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+=Vj(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=Vj(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function Gj(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function Kj(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 qj(){throw Error(`Invariant failed`)}function Jj(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 Yj=4,Xj=5;function Zj(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 Qj(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=Zj(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 $j(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=Qj(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=tM(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=nM(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=tM(r);e.kind=Xj,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=tM(r);e.kind=Yj,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)$j(e,t,r,c,i,a,o,s)}function eM(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 tM(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 nM(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 rM(e,t){let n=tM(`/`),r=new Uint16Array(6),i=[];for(let t of e)$j(!1,r,t,1,n,0,i);for(let e of i)e.sort(eM);t.masksTree=n,t.flatCache=Jj(1e3)}function iM(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=lM(e,t.masksTree);return t.flatCache.set(e,r),r}function aM(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=tM(`/`),$j(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),lM(r,o,n)}function oM(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=lM(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=dM(a.route)),t.matchCache.set(r,a),a}function sM(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function cM(e,t=!1,n){let r=tM(e.fullPath),i=new Uint16Array(6),a=[],o={},s={},c=0;$j(t,i,e,1,r,0,a,e=>{if(n?.(e,c),e.id in o&&qj(),o[e.id]=e,c!==0&&e.path){let t=sM(e.fullPath);(!s[t]||e.fullPath.endsWith(`/`))&&(s[t]=e)}c++});for(let e of a)e.sort(eM);return{processedTree:{segmentTree:r,singleCache:Jj(1e3),matchCache:Jj(1e3),flatCache:null,masksTree:null},routesById:o,routesByPath:s}}function lM(e,t,n=!1){let r=e.split(`/`),i=pM(e,r,t,n);if(!i)return null;let[a]=uM(e,r,i);return{route:i.node.route,rawParams:a}}function uM(e,t,n){let r=fM(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===Yj)break;if(u.kind===Xj){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 dM(e){let t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function fM(e){let t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function pM(e,t,n,r){if(e===`/`&&n.index)return{node:n.index,skipped:0};let i=!Tj(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&&!_M(l,n))continue;if(i.parse){if(!gM(e,t,n))continue;g=n.rawParams,h=n.extract}r&&i.route&&i.kind!==Yj&&_M(c,n)&&(c=n);let _=u===o;if(_&&(i.route&&(!a||i.kind===Yj||i.kind===2)&&_M(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&&(gM(e,t,n)||(r=!1)),r){if(!p&&!m&&!d&&hM(f,o))return n;_M(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+mM(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+mM(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+mM(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+mM(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 mM(e,t){return 2**(e-t-1)}function hM(e,t){return e===2**(t-1)-1}function gM(e,t,n){let r,i;try{[r,i]=uM(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 _M(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===Yj)>(e.node.kind===Yj)||t.node.kind===Yj==(e.node.kind===Yj)&&t.node.depth>e.node.depth)))}function vM(e){return yM(e.filter(e=>e!==void 0).join(`/`))}function yM(e){return e.replace(/\/{2,}/g,`/`)}function bM(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function xM(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function SM(e){return xM(bM(e))}function CM(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function wM(e,t,n){return CM(e,n)===CM(t,n)}function TM({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&&Tj(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&&(Tj(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c=yM(s.join(`/`))||`/`;return o&&r&&r.set(o,c),c}function EM(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 DM(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>kM(e,n)).join(`/`):kM(r,n):r}function OM({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=Qj(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=DM(`_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=DM(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=DM(i,t,n)??``;l+=`/`+u+f+d;continue}}return e.endsWith(`/`)&&(l+=`/`),{usedParams:a,interpolatedPath:l||`/`,isMissingParams:i}}function kM(e,t){let n=encodeURIComponent(e);return t?.(n)??n}function AM(e){return e?.isNotFound===!0}function jM(){try{return sessionStorage}catch{return}}var MM=`tsr-scroll-restoration-v1_3`,NM=jM();function PM(){try{return JSON.parse(NM?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function FM(){try{NM?.setItem(MM,JSON.stringify(IM))}catch{}}var IM=PM(),LM=`data-scroll-restoration-id`,RM=e=>e.state.__TSR_key||e.href;function zM(e){let t=e.getAttribute(LM);if(t)return`[${LM}="${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 BM=!1,VM=`window`;function HM(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function UM(e){let t=new Set;for(let n of e){if(n===VM)continue;let e=HM(n);e&&t.add(e)}return t}function WM(e,t){let n=t??e.options.scrollRestoration,r=e._scroll;n&&(r.restoring=!0);let i=e.options.getScrollRestorationKey||RM,a=new Set,o=e=>{let t=IM[e]||={};for(let e of a)e===document?t[VM]={scrollX,scrollY}:e.isConnected&&(t[zM(e)]={scrollX:e.scrollLeft,scrollY:e.scrollTop})};n&&!r.restoration&&(r.restoration=!0,BM=!1,history.scrollRestoration=`manual`,document.addEventListener(`scroll`,e=>{BM||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())),FM()})),!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=IM[d];if(e){let t=IM[u];for(let n in e){if(n===VM){if(s)continue}else{let e=HM(n);if(!e||s&&o&&(l??=UM(o),l.has(e)))continue}t||=IM[u]={},t[n]??=e[n]}}}BM=!0;try{let e=t.toLocation.hash,i=t.toLocation.state.__hashScrollIntoViewOptions??!0,a=!1;if(s){!e&&o&&(l??=UM(o));let t=e&&i&&c,s=r.restoring?IM[u]:void 0;if(s)for(let e in s){let{scrollX:r,scrollY:i}=s[e];if(e===VM){if(t)continue;scrollTo({top:i,left:r,behavior:n}),a=!0}else{let t=HM(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{BM=!1}}))}function GM(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 KM(e){return e?e===`false`?!1:e===`true`?!0:e*0==0&&+e+``===e?+e:e:``}function qM(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]=KM(r):Array.isArray(t)?t.push(KM(r)):n[e]=[t,KM(r)]}return n}var JM=/^(?:\s|["[{\d-]|fa|nu|tr)/,YM=ZM(JSON.parse),XM=QM(JSON.stringify,JSON.parse);function ZM(e){return t=>{t[0]===`?`&&(t=t.substring(1));let n=qM(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function QM(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&&!JM.test(r))return r;try{return t(r),e(r)}catch{}}return r}return e=>{let t=GM(e,r);return t?`?${t}`:``}}var $M=`__root__`;function eN(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 tN(e){return e instanceof Response&&!!e.options}function nN(e){return{input:({url:t})=>{for(let n of e)t=iN(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=aN(e[n],t);return t}}}function rN(e){let t=SM(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=vM([`/`,t,e.pathname]),e)}}function iN(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 aN(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 oN(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(()=>{Kj(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 sN=`__TSR_index`,cN=`popstate`,lN=`beforeunload`;function uN(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=hN(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[sN];i=dN(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[sN];i=dN(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[sN]!==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 dN(e,t){t||={};let n=gN();return{...t,key:n,__TSR_key:n,[sN]:e}}function fN(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??(()=>hN(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=gN();t.history.replaceState({[sN]: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=hN(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[sN]-l.state[sN],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=uN({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(lN,x,{capture:!0}),t.removeEventListener(cN,b)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(lN,x,{capture:!0}),t.addEventListener(cN,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 pN(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)=>dN(t,void 0)),i=()=>hN(t[n],r[n]),a=[];return uN({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 mN(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function hN(e,t){let n=mN(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=gN();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||{[sN]:0,key:a,__TSR_key:a}}}function gN(){return(Math.random()+1).toString(36).substring(7)}function _N(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function vN(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function yN({key:e,__TSR_key:t,__TSR_index:n,__hashScrollIntoViewOptions:r,...i}){return i}function bN(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 xN=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=EM(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.history=this.options.history?this.options.history:fN()),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=Jj(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=oN(this.latestLocation,e),WM(this)}let a=this.options.basepath??`/`,o=this.options.rewrite;if(r||n!==a||i!==o){this.basepath=a;let e=[],t=SM(a);t&&t!==`/`&&e.push(rN({basepath:a})),o&&e.push(o),this.rewrite=e.length===0?void 0:e.length===1?e[0]:nN(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=cM(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&rM(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:Wj(e).path,external:!1,searchStr:o,search:Mj(t?.search,i),hash:Wj(r.slice(1)).path,state:Nj(t?.state,a)}}let o=new URL(i,this.origin),s=iN(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:Wj(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:Mj(t?.search,c),hash:Wj(s.hash.slice(1)).path,state:Nj(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)=>TM({base:e,to:t.includes(`//`)?yM(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=oM(xM(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=DN(t.params,s),d=this.routesByPath[xM(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&&Aj(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:Wj(OM({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,wN(t.options.validateSearch,{...e,...m}))}catch{}}),m=e}m=TN(m,t,f,e._includeValidateSearch),m=Mj(o,m);let h=this.options.stringifySearch(m),g=t.hash===!0?n.hash:t.hash?Dj(t.hash,n.hash):void 0,_=g?`#${g}`:``,v=t.state===!0?n.state:t.state?Dj(t.state,n.state):{};v=Nj(n.state,v);let y=`${p}${h}${_}`,b,x,S=!1;if(this.rewrite){let e=new URL(y,this.origin),t=aN(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=Gj(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=iM(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=DN(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=xM(this.latestLocation.href)===xM(n.href)&&Rj(yN(n.state),yN(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=hN(o,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);s.to=iN(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(Uj(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 yP(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(vN(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`)&&_N(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&&Uj(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=jN,this.preloadRoute=e=>bP(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=aM(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,a.pathname,this.processedTree);return!o||e.params&&!Rj(o.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?Rj(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??XM,parseSearch:e.parseSearch??YM,protocolAllowlist:e.protocolAllowlist??Hj}),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=dM(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[`**`]:xM(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?EN(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=wN(i.options.validateSearch,{...n})??void 0;l={...n,...e},f={...r,...e}}catch(e){let r=e;if(e instanceof SN||(r=new SN(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:_}=OM({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{ON(i,d)}catch(e){if(x=AM(e)||tN(e)?e:new CN(e.message,{cause:e}),t?.throwOnError)throw x}let S=y?`stay`:`enter`,C;if(b)C={...b,cause:S,search:Mj(y?y.search:b.search,l),_strictSearch:f,searchError:p};else{let e=_N(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?Mj(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?Nj(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`?Mj(n.params,d):d,t?._controller&&(n.context={})}return c}matchRoutesLightweight(e){let t=Tj(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=Tj(a),c={...e.search};for(let e of a)try{Object.assign(c,wN(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{ON(t,e)}catch{}u=e}let d=[a,s.fullPath,c,u];return this.lightweightCache.set(e,[r,d]),d}},SN=class extends Error{},CN=class extends Error{};function wN(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new SN(`Async validation not supported`);if(n.issues)throw new SN(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 TN(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=wN(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=Dj(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 EN(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 $M}function DN(e,t){return e===!1||e===null?Object.create(null):(e??!0)===!0?t:Object.assign(t,Dj(e,t))}function ON(e,t){let n=e.options.params?.parse??e.options.parseParams;n&&Object.assign(t,n(t))}function kN(e,t){return e.options[t]?.preload?.()}function AN(e,t){let n=kN(e,`component`),r=kN(e,`pendingComponent`),i=t&&r?r.then(t):r;return t&&!r&&t(),n&&i?Promise.all([n,i]).then(()=>{}):n??i}function jN(e,t,n){let r=()=>t===!1?void 0:t?kN(e,t):AN(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 MN(e){let t=e.findIndex(e=>e.status!==`success`||e._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var NN=0,PN=1,FN=2,IN=3,LN=4;function RN(e){return typeof e[0]==`number`}function zN(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 BN(e,t){return e.routesById[t.routeId]}function VN(e,t,n){return tN(e)?[IN,e]:AM(e)?(e.routeId||=n,[FN,e]):(t&&typeof e?.then==`function`&&(e=Error(`A Promise was thrown`,{cause:e})),t?[PN,e]:[NN,e])}function HN(e,t){let n=VN(t,!0,e.id);if(n[0]!==PN)return n;try{e.options.onError?.(n[1])}catch(t){n=VN(t,!0,e.id)}return n}function UN(e,t,n){return n[0].signal.aborted||!n[2]()?(n[0].abort(),[LN]):HN(e,t)}function WN(e,t){return n=>e.navigate({...n,_fromLocation:t})}async function GN(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=BN(e,r);r.abortController=n[0];let u=s[t-1]?.context??e.options.context??{},d={params:r.params,location:o,navigate:WN(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 qN(e,r),[t,UN(i,a,n)]}if(c.aborted||!n[2]())return n[0].abort(),[t,[LN]];let p=r.paramsError??r.searchError;if(p!==void 0)return qN(e,r),[t,UN(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{XN(e,r,`beforeLoad`,n[0]);let a=await zN(m(h),c);if(!n[2]())return n[0].abort(),[t,[LN]];let o=VN(a,!1,i.id);if(o[0]!==NN)return qN(e,r),[t,o];r.context={...f,...a}}catch(a){return qN(e,r),[t,UN(i,a,n)]}finally{g===`success`&&r.status===`pending`&&(r.status=`success`),XN(e,r,!1,n[0])}}i()}function KN(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 qN(e,t){let n=t._flight;t._flight=void 0,KN(e,t,n)?.abort()}function JN(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=KN(e,a,t);n&&i.push(n)}}for(let e of i)e.abort()}function YN(e){for(let t of e){let e=t._flight;e&&e[2]++}}function XN(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 ZN(e,t,n,r,i,a,o){let s=t[0];return{params:n.params,location:s,navigate:WN(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 QN(e,t,n,r,i,a,o,s){let c=s.signal;if(c.aborted)return[LN];if(!i)return[NN,void 0];let l=n._flight;XN(e,n,`loader`,s);try{if(!l){let s=new AbortController;l=[Promise.resolve().then(()=>i(ZN(e,t,n,r,s,a,o))).then(e=>VN(e,!1,r.id),e=>VN(e,!0,r.id)).then(t=>(t[0]!==NN&&e._flights?.get(n.id)===l&&(e._flights.delete(n.id),l[2]||s.abort()),t[0]===PN&&l[2]?HN(r,t[1]):t)),s,1],(e._flights??=new Map).set(n.id,l)}return n._flight=l,n.abortController=l[1],await zN(l[0],c)}catch(t){if(t!==c)throw t;return qN(e,n),[LN]}finally{XN(e,n,!1,s)}}function $N(e,t,n){t[0]===NN?(e.loaderData=t[1],e.error=void 0,e.status=`success`,e.invalid=!1,e.updatedAt=Date.now(),e.preload=n):t[0]!==IN&&(e.status=`success`,e.error=void 0,e.invalid=!0)}function eP(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&&qN(e,r)}function tP(e,t){return t[0]===PN||t[0]===FN?{...e,status:t[0]===PN?`error`:`notFound`,error:t[1],_flight:void 0}:e}function nP(e,t,n,r,i,a,o){let s=t[1][n],c=BN(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(ZN(e,t,s,c,a[0],i,l))),a[2]()||(a[0].abort(),p=[LN])),!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,qN(e,s),p=UN(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,KN(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?QN(e,t,s,c,h,i,l,a[0]):Promise.resolve([NN,s.loaderData])).then(t=>(y&&($N(s,t,l),t[0]===NN&&(m&&!a[0].signal.aborted&&eP(e,s,u),s.status=`pending`)),t)),S=zN(Promise.resolve().then(()=>jN(c,void 0,b)),a[0].signal).then(()=>void 0,e=>[n,UN(c,e,a)]).then(e=>x.then(t=>(y&&!e&&t[0]===NN&&s.status===`pending`&&a[2]()&&(s.status=`success`,a[8]?.()),e)));if(r.push([n,x,S]),!_)return x.then(e=>tP(s,e));let C={...s,status:`pending`,preload:!1,_flight:g};s.invalid=!1,s.isFetching=`loader`;let w=QN(e,t,C,c,h,i,!1,a[0]).then(e=>(s.isFetching=!1,$N(C,e,!1),e));return(t[2]??=[]).push([n,w,S,C]),w.then(e=>tP(C,e))}async function rP(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=BN(e,t[n]),a=jN(i,!1);if(a)try{await zN(a,r)}catch(e){if(e===r)throw e}if(i.options.notFoundComponent)return n}return a?.routeId?o:i}function iP(e,t){t[2]&&=(JN(e,t[2].map(e=>e[3])),void 0)}async function aP(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]>=IN)throw[a,t];!i&&t[0]!==NN&&(i=[a,t],await Promise.all((n??[]).map(e=>{if(!(e[0]<=a))return e[1].then(t=>{if(t[0]===IN)throw[e[0],t]})})))}})))}catch(e){return e}return t??i}async function oP(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]===FN?rP(e,s,t,r.signal):t[0],f=u<0?s.length:u;if((c?.[1][0]??0)>=IN)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]!==NN&&t[0]<IN&&!(`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)>=IN){let n=c[1];if(n[0]!==IN||n[1].options.reloadDocument||i<20)return iP(e,t),n;l=!0,c=[0,[PN,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===PN?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=BN(e,u);try{await zN(i?Promise.resolve().then(()=>jN(m,a===PN?`errorComponent`:`notFoundComponent`)):Promise.all([jN(m),jN(m,`notFoundComponent`)]),r.signal)}catch(n){if(n===r.signal)return iP(e,t),[LN]}i?l&&(r.abort(),await Promise.all([...n.map(e=>e[1]),...n.map(e=>e[2]),...(t[2]??[]).map(e=>e[1])]),iP(e,t),JN(e,s),f()):(u.status=`success`,o?.())}return t}async function sP(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=BN(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 zN(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 cP(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 rP(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=nP(e,i,t,l,d,r,c)},p=await GN(e,i,r,s,f,c);if(p&&(r[5]=!0,s=p[0],p[1][0]===FN?(p[2]=await rP(e,i[1],p,r[0].signal),s=Math.min(s,p[2]+1)):p[1][0]>=IN&&(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=oP(e,i,l,r[0],r[1],aP(l,p,i[2]),r[8]);i[2]?.length&&(i[3]=aP(i[2],void 0,void 0,t.then(e=>RN(e)?0:MN(e[1]).length,()=>0))),m=await t}catch(t){throw iP(e,i),t}return RN(m)?m:sP(e,m,r[0].signal,r[7]===m[1].length?r[7]:0)}function lP(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=BN(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(()=>lP(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 uP(e,t){let n=e._pending;n?.[0]===t&&(clearTimeout(n[3]),e._pending=void 0)}function dP(e,t){e._committed=t,e.stores.setMatches(t)}function fP(e,t){JN(e,t[1]),iP(e,t)}function pP(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=MN(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=BN(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,dP(e,n),JN(e,[...a.values(),...i],[...n,...s.values()]),bN(e,i,n,()=>e._tx===t)}async function mP(e,t){let n=e._tx;for(;n&&n!==t;){if(await n[5],e._tx===n)return;n=e._tx}}async function hP(e,t,n){await e.navigate({...n.options,replace:!0,ignoreBlocker:!0,_redirects:t[1]+1})}function gP(e,t){uP(e,t),t[0].abort(),JN(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 _P(e,t,n,r,i){let a=n.map(e=>({...e}));YN(a);for(let t of r)qN(e,a[t[0]]),a[t[0]]=t[3];let o=[t[2],a],s;try{s=await oP(e,o,r,t[0],t[1],i)}catch(t){throw JN(e,a),t}if(RN(s)){JN(e,a),s[0]===IN&&e._tx===t&&e._committed===n&&await hP(e,t,s[1]);return}let c=await sP(e,s,t[0].signal);if(e._tx!==t||e._committed!==n){JN(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),qN(e,n))}dP(e,c[1]),JN(e,n,c[1])}async function vP(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 cP(e,t[2],t[3],o);if(RN(s)){s[0]===IN&&e._tx===t?(uP(e,t),JN(e,t[3]),t[3]=[],e._tx===t&&await hP(e,t,s[1])):gP(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 zN(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 zN(new Promise(t=>{c[3]=setTimeout(t,e)}),n)}catch{}clearTimeout(c[3])}}}if(e._tx!==t){uP(e,t),fP(e,s);return}let l=t[2],u=vN(l,e.stores.resolvedLocation.get()),d=s[2];await e.startViewTransition(async()=>{if(e._tx!==t){fP(e,s);return}let n=await e.startTransition(()=>{uP(e,t),pP(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){iP(e,s);return}d?.length&&_P(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 yP(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 mP(e,n);return}let f=vN(a,r);if(e.emit({type:`onBeforeNavigate`,...f}),u.signal.aborted||e.emit({type:`onBeforeLoad`,...f}),u.signal.aborted){await mP(e,n);return}let p=i.href===a.href,m,h=u;try{m=e.matchRoutes(a,{_controller:u}),YN(m)}catch(t){if(u.abort(),!tN(t)){await mP(e),e._commitPromise?.resolve(),e._commitPromise=void 0;return}await e.navigate({...t.options,replace:!0,ignoreBlocker:!0}),await mP(e,n);return}let g=l?c[1](m):void 0;if(g?h=l:l?.abort(),u.signal.aborted){JN(e,m),await mP(e,n);return}e._preflight=void 0;let _=[h,s,a,m,Date.now(),Promise.resolve().then(()=>vP(e,_,p,()=>lP(e,_),t?.sync,g)).catch(()=>{e._tx===_&&gP(e,_)})];if(e._tx=_,n){for(let t of e.stores.matches.get()){if(e._tx!==_)break;t.isFetching&&XN(e,t,!1)}n[0].abort(),JN(e,n[3],_[3],!0)}if(e._tx!==_){JN(e,_[3]),_[3]=[],await mP(e,_);return}e.batch(()=>{e.stores.status.set(`pending`),e.stores.location.set(a)}),!r&&!m.some(e=>e._notFound)&&lP(e,_);try{await _[5]}finally{await mP(e,_)}}async function bP(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}),YN(o)}catch(e){a.abort(),AM(e)||console.error(e);return}(e._preloads??=new Map).set(a,o);let s;try{let t;try{t=await cP(e,r,o,[a,n,()=>!0,i,!0])}finally{s=e._preloads.delete(a),JN(e,o),a.abort()}if(!RN(t))return t[1];if(s&&t[0]===IN&&!t[1].options.reloadDocument)return bP(e,{...t[1].options,_fromLocation:r},n+1)}catch(e){AM(e)||console.error(e)}}var xP=`Error preloading route! ☝️`,SP=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=$M:this.parentRoute||qj();let r=n?$M:t?.path;r&&r!==`/`&&(r=bM(r));let i=t?.id||r,a=n?$M:vM([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=vM([`/`,a]));let o=a===`__root__`?`/`:vM([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=xM(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=>eN({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.`)}},CP=class extends SP{constructor(e){super(e)}};function wP(e){return(0,Q.jsx)(TP,{...e})}var TP=class extends X.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?X.createElement(this.props.errorComponent??EP,{error:e,reset:this.reset}):this.props.children}};function EP({error:e}){let[t,n]=X.useState(!1);return(0,Q.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,Q.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,Q.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,Q.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,Q.jsx)(`code`,{children:e.message}):null})}):null]})}function DP({children:e,fallback:t=null}){return(0,Q.jsx)(X.Fragment,{children:OP()?e:t})}function OP(){return X.useSyncExternalStore(kP,()=>!0,()=>!1)}function kP(){return()=>{}}var AP=X.createContext(null);function jP(e){return X.useContext(AP)}var MP=X.createContext(void 0),NP=X.createContext(void 0),PP=(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))(PP||{});function FP({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 IP(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 LP=[],RP=0,{link:zP,unlink:BP,propagate:VP,checkDirty:HP,shallowPropagate:UP}=FP({update(e){return e._update()},notify(e){LP[GP++]=e,e.flags&=~PP.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=PP.Mutable|PP.Dirty,YP(e))}}),WP=0,GP=0,KP,qP=0;function JP(e){try{++qP,e()}finally{--qP||XP()}}function YP(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=BP(n,e)}function XP(){if(!(qP>0)){for(;WP<GP;){let e=LP[WP];LP[WP++]=void 0,e.notify()}WP=0,GP=0}}function ZP(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?PP.None:PP.Mutable,get(){return KP!==void 0&&zP(i,KP,RP),i._snapshot},subscribe(e){let t=IP(e),n={current:!1},r=QP(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=KP,o=t?.compare??Object.is;if(n)KP=i,++RP,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=PP.Mutable|PP.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{KP=a,n&&(i.flags&=~PP.RecursedCheck),YP(i)}}};return n?(i.flags=PP.Mutable|PP.Dirty,i.get=function(){let e=i.flags;if(e&PP.Dirty||e&PP.Pending&&HP(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&UP(e)}}else e&PP.Pending&&(i.flags=e&~PP.Pending);return KP!==void 0&&zP(i,KP,RP),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(VP(e),UP(e),XP())}},i}function QP(e){let t=()=>{let t=KP;KP=n,++RP,n.depsTail=void 0,n.flags=PP.Watching|PP.RecursedCheck;try{return e()}finally{KP=t,n.flags&=~PP.RecursedCheck,YP(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:PP.Watching|PP.RecursedCheck,notify(){let e=this.flags;e&PP.Dirty||e&PP.Pending&&HP(this.deps,this)?t():this.flags=PP.Watching},stop(){this.flags=PP.None,this.depsTail=void 0,YP(this)}};return t(),n}var $P=t((e=>{var t=sa();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})),eF=t(((e,t)=>{t.exports=$P()})),tF=t((e=>{var t=sa(),n=eF();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}})),nF=t(((e,t)=>{t.exports=tF()}))();function rF(e,t){return e===t}function iF(e,t,n=rF){let r=(0,X.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,X.useCallback)(()=>e?.get(),[e]);return(0,nF.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var aF={};function oF(e,t){let n=X.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=Nj(n.current,i):i}}function sF(e){let t=jP(),n=X.useContext(e.from?NP:MP),r=e.from??n,i=t.stores.getMatchStore(r),a=oF(e,t),o=iF(i,e=>e?a(e):aF);if(o!==aF)return o;(e.shouldThrow??!0)&&qj()}function cF(e){return sF({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function lF(e){let{select:t,...n}=e;return sF({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function uF(e){return sF({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 dF(e){return sF({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function fF(e){let t=jP();return X.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function pF(e){return sF({...e,select:t=>e.select?e.select(t.context):t.context})}function mF(e){let t=X.useRef(e);return Rj(t.current,e,{ignoreUndefined:!1})||(t.current=e),t.current}function hF(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function gF(e,t,n){if(e?.external)return Uj(e.href,n)?void 0:e.href;if(!DF(t)&&typeof t==`string`&&t.indexOf(`:`)!==-1)try{return new URL(t),Uj(t,n)?void 0:t}catch{}}function _F(e,t,n,r,i,a){if(a)return!1;if(n?.exact){if(!wM(e.pathname,t.pathname,r))return!1}else{let n=CM(e.pathname,r),i=CM(t.pathname,r);if(!(n.startsWith(i)&&(n.length===i.length||n[i.length]===`/`)))return!1}return(n?.includeSearch??!0)&&!Rj(e.search,t.search,{partial:!n?.exact,ignoreUndefined:!n?.explicitUndefined})?!1:!n?.includeHash||i&&e.hash===t.hash}function vF(e,t){let n=jP(),r=wj(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:ee,unsafeRelative:te,from:ne,_fromLocation:N,...P}=e,re=OP(),F=mF(e.search),I=mF(e.params),ie=mF(o),L=X.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,F,I,e.state,e.mask,e.unsafeRelative]),ae=X.useCallback(e=>{let t=n.buildLocation({_fromLocation:e,...L}),r=EF(t.maskedLocation?t.maskedLocation.publicHref:t.publicHref,t.maskedLocation?t.maskedLocation.external:t.external,n.history,v),i=gF(r,s,n.protocolAllowlist);return[r?.href,i,_F(e,t,ie,n.basepath,re,i!==void 0)]},[ie,v,re,L,n,s]),[oe,se,ce]=iF(n.stores.location,ae,hF),le=ce?Dj(i,{})??bF:yF,R=ce?yF:Dj(a,{})??yF,ue=[b,le.className,R.className].filter(Boolean).join(` `),de=(y||le.style||R.style)&&{...y,...le.style,...R.style},fe=X.useRef(!1),pe=e.reloadDocument||se||v?!1:c??n.options.defaultPreload,me=l??n.options.defaultPreloadDelay??0,he=X.useCallback(()=>{n.preloadRoute(L).catch(e=>{console.warn(e),console.warn(xP)})},[n,L]),z=X.useCallback(e=>{if(!e){wF(r);return}if(!(e.isIntersecting??pe===`intent`)){e.isIntersecting===!1&&wF(r);return}if(!me){he();return}CF.has(r)||CF.set(r,setTimeout(()=>{CF.delete(r),he()},me))},[he,r,pe,me]);Cj(r,z,pe!==`viewport`),X.useEffect(()=>{fe.current||pe===`render`&&(he(),fe.current=!0)},[he,pe]);let ge=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;!v&&!kF(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0&&(e.preventDefault(),n.navigate({...L,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:D}))};if(se)return{...P,ref:r,href:se,...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 _e=()=>{pe===`intent`&&he()},ve=()=>{pe===`intent`&&wF(r)};return{...P,...le,...R,href:oe,ref:r,onClick:TF([x,ge]),onBlur:TF([S,ve]),onFocus:TF([C,z]),onMouseEnter:TF([w,z]),onMouseLeave:TF([T,ve]),onTouchStart:TF([E,_e]),disabled:!!v,target:_,...de&&{style:de},...ue&&{className:ue},...v&&xF,...ce&&SF}}var yF={},bF={className:`active`},xF={role:`link`,"aria-disabled":!0},SF={"data-status":`active`,"aria-current":`page`},CF=new WeakMap,wF=e=>{clearTimeout(CF.get(e)),CF.delete(e)},TF=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function EF(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function DF(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var OF=X.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=vF(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return X.createElement(`a`,t,o)}return X.createElement(n,a,o)});function kF(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var AF=class extends SP{constructor(e){super(e),this.useMatch=e=>sF({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>pF({...e,from:this.id}),this.useSearch=e=>dF({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>uF({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>lF({...e,from:this.id}),this.useLoaderData=e=>cF({...e,from:this.id}),this.useNavigate=()=>fF({from:this.fullPath}),this.Link=X.forwardRef((e,t)=>(0,Q.jsx)(OF,{ref:t,from:this.fullPath,...e}))}};function jF(e){return new AF(e)}var MF=class extends CP{constructor(e){super(e),this.useMatch=e=>sF({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>pF({...e,from:this.id}),this.useSearch=e=>dF({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>uF({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>lF({...e,from:this.id}),this.useLoaderData=e=>cF({...e,from:this.id}),this.useNavigate=()=>fF({from:this.fullPath}),this.Link=X.forwardRef((e,t)=>(0,Q.jsx)(OF,{ref:t,from:this.fullPath,...e}))}};function NF(e){return new MF(e)}function PF(e){let t=jP(),n=`not-found-${iF(t.stores.location,e=>e.pathname)}-${iF(t.stores.status,e=>e)}`;return(0,Q.jsx)(wP,{getResetKey:()=>n,onCatch:(t,n)=>{if(AM(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(AM(t))return e.fallback?.(t);throw t},children:e.children})}function FF(){return(0,Q.jsx)(`p`,{children:`Not Found`})}function IF(e){return(0,Q.jsx)(Q.Fragment,{children:e.children})}function LF(e,t,n){return t.options.notFoundComponent?(0,Q.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,Q.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,Q.jsx)(FF,{})}function RF(e,t){let n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,Q.jsx)(n,{}):null}var zF=(e,t)=>e[0]===t[0]&&e[1]===t[1],BF=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n===`data-only`||!e.ssr,VF=X.memo(function({routeId:e}){let t=jP();return(0,Q.jsx)(HF,{router:t,match:iF(t.stores.getMatchStore(e),e=>e)})});function HF({router:e,match:t}){let n=e.routesById[t.routeId],r=RF(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=BF(e,n,t.ssr)&&(n.options.wrapInSuspense??r??(n.options.errorComponent?.preload||s))?X.Suspense:IF,l=i?wP:IF,u=o?PF:IF;return(0,Q.jsxs)(n.isRoot?n.options.shellComponent??IF:IF,{children:[(0,Q.jsx)(MP.Provider,{value:t.routeId,children:(0,Q.jsx)(c,{fallback:r,children:(0,Q.jsx)(l,{getResetKey:()=>t,errorComponent:i,onCatch:(e,n)=>{if(AM(e))throw e.routeId??=t.routeId,e;a?.(e,n)},children:(0,Q.jsx)(u,{fallback:e=>{if(e.routeId??=t.routeId,e.routeId!==t.routeId)throw e;return X.createElement(o,e)},children:s?(0,Q.jsx)(DP,{fallback:r,children:(0,Q.jsx)(UF,{match:t})}):(0,Q.jsx)(UF,{match:t})})})})}),null]})}var UF=X.memo(function({match:e}){let t=jP(),n=e.routeId,r=t.routesById[n],i=X.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=X.useMemo(()=>{let e=r.options.component??t.options.defaultComponent;return e?(0,Q.jsx)(e,{},i):(0,Q.jsx)(WF,{})},[i,r.options.component,t.options.defaultComponent]);if(e.status===`pending`){if(t.ssr&&!BF(t,r,e.ssr))return a;if(t._tx)throw t._tx[5];return RF(t,r)}if(e.status===`notFound`)return LF(t,r,e.error);if(e.status===`error`)throw e.error;return a}),WF=X.memo(function(){let e=jP(),t=X.useContext(MP),n,r,i;{let a=e.stores.getMatchStore(t);[n,r]=iF(a,e=>[!!e._notFound,e.error],zF),i=iF(e.stores.ids,e=>e[e.indexOf(t)+1])}if(n)return LF(e,e.routesById[t],r);if(!i)return null;let a=(0,Q.jsx)(VF,{routeId:i});return t===`__root__`?(0,Q.jsx)(X.Suspense,{fallback:RF(e),children:a}):a});function GF(e,t){let n=e[1];e.length=0,n?.(t)}function KF({t:e}){let t=jP(),n=t._rendered??=[];return t.startTransition=(r,i)=>new Promise((a,o)=>{GF(n,!1),n.push(i,a),e(t),X.startTransition(()=>{try{r()}catch(e){n[1]===a&&(n.length=0),o(e)}})}),Sj(()=>{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(xM(r.publicHref)!==xM(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`,...vN(a,a)})}):t._tx||t.load().catch(console.error),e},[t,t.history]),null}function qF(){let e=jP(),t=e.routesById[$M],n=RF(e,t),r=e.ssr?IF:X.Suspense,i=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(KF,{t:X.useState()[1]}),(0,Q.jsx)(r,{fallback:n,children:(0,Q.jsx)(JF,{})})]});return e.options.InnerWrap?(0,Q.jsx)(e.options.InnerWrap,{children:i}):i}function JF(){let e=jP(),t=e._rendered,n=iF(e.stores.matches,e=>t[0]??e),r=n[0],i=r?.routeId;Sj(()=>{t[0]===n&&GF(t,!0)},[t,n]);let a=i?(0,Q.jsx)(VF,{routeId:i}):null;return(0,Q.jsx)(MP.Provider,{value:i,children:e.options.disableGlobalCatchBoundary?a:(0,Q.jsx)(wP,{getResetKey:()=>r,onCatch:void 0,children:a})})}var YF=e=>({createMutableStore:ZP,createReadonlyStore:ZP,batch:JP}),XF=e=>new ZF(e),ZF=class extends xN{constructor(e){super(e,YF)}};function QF({router:e,children:t,...n}){Aj(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,Q.jsx)(AP.Provider,{value:e,children:t});return e.options.Wrap?(0,Q.jsx)(e.options.Wrap,{children:r}):r}function $F({router:e,...t}){return(0,Q.jsx)(QF,{router:e,...t,children:(0,Q.jsx)(qF,{})})}function eI(e){let t=jP({warn:e?.router===void 0}),n=e?.router||t;return iF(n.stores.__store,oF(e,n))}function tI(){return iF(jP().stores.location,e=>e.state.__TSR_index!==0)}var nI=(0,X.createContext)(null),rI=nI.Provider,iI=NF({validateSearch:wa({agent:To().min(1).optional()}),component:()=>null}),aI=jF({getParentRoute:()=>iI,path:`/`}),oI=wa({agentId:To().min(1),sessionId:To().min(1)}),sI=jF({getParentRoute:()=>iI,path:`/sessions/$agentId/$sessionId`,params:{parse:e=>oI.parse(e)}});function cI(){return XF({routeTree:iI.addChildren([aI,sI]),history:pN(),InnerWrap:({children:e})=>(0,Q.jsxs)(Q.Fragment,{children:[(0,X.useContext)(nI),e]}),defaultPendingMs:0,defaultPendingMinMs:0})}function lI(e){let t=e.state.matches.find(e=>e.routeId===sI.id),n=oI.safeParse(t?.params);return n.success?n.data:null}function uI(e,t){let n=eI({router:e,select:e=>e.location.search}),r=sF({from:sI.id,shouldThrow:!1});vh(t,{canGoBack:tI(),canGoForward:!1,onForward:()=>!1,onBack:()=>e.history.canGoBack()?(e.history.back(),!0):!1});let i=(0,X.useCallback)(t=>{e.navigate({to:`.`,search:{agent:t??void 0},replace:!0})},[e]),a=(0,X.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 dI=qr.check(y(1,{message:`Give your Agent a name.`}),Y(256,{message:`Use at most 256 characters.`}));function fI({agentId:e,name:t,rename:n}){let[r,i]=(0,X.useState)(!1),a=BA({schema:(0,X.useMemo)(()=>q({name:dI.annotate(fA({label:`Agent name`,render:e=>(0,Q.jsx)(Mr,{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}=VA(a);return r?(0,Q.jsxs)(WA,{model:a,"aria-label":`Rename Agent`,footer:null,className:`flex min-w-0 items-center gap-1`,children:[(0,Q.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Q.jsx)(sA,{model:a,names:[`name`]})}),(0,Q.jsx)(U,{type:`submit`,size:`sm`,loading:o,disabled:o||!s,children:`Save`}),(0,Q.jsx)(wi,{"aria-label":`Cancel rename`,type:`button`,icon:(0,Q.jsx)(re,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!1)}})]}):(0,Q.jsx)(wi,{"aria-label":`Rename Agent`,icon:(0,Q.jsx)(nT,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!0)}})}function pI({status:e,approving:t,onApprove:n}){return e?.status===`pending`?(0,Q.jsx)(U,{variant:`outline`,size:`sm`,className:`flex-none`,loading:t,disabled:t,onClick:n,children:`Allow App tools`}):null}var mI=q({text:G}),hI=pa(structuredClone(Pe(mI,{onExcessProperty:`error`}).schema));function gI(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:hI,presentation:{type:`action`}},handler:({arguments:t})=>{let{text:n}=ot(mI,{onExcessProperty:`error`})(t);return{accepted:e().setDraft(n)}}}]}function _I(e,t){let n=(0,X.useRef)(e);n.current=e;let r=(0,X.useMemo)(()=>gI(()=>n.current),[]),i=(0,X.useMemo)(()=>lr(),[]);return(0,X.useEffect)(()=>{let e=i.contribute({sourceId:`grove`,namespace:`grove`,commands:r});return()=>{e.dispose()}},[r,i]),(0,X.useEffect)(()=>t?No(t,r):void 0,[r,t]),i}var vI=wo(za({providerId:To().min(1).max(256),providerName:To().min(1).max(256),id:To().min(1).max(256),name:To().min(1).max(256),reasoning:wo(ro(vt)).max(6).readonly()})).max(1024).readonly();async function yI(e,t,n,r=cg){if(!e.has(ng))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 vI.parse(await e.json())}finally{await i.close()}}var bI=`first-session`,xI=ot(q({requestId:ji}));async function SI(e,t){return xI((await e.claim({key:bI,scope:`member`,value:{requestId:t()}})).value).requestId}function CI(e){let t=Xt(),n=e?.capabilities.has(ng)===!0||e?.capabilities.has(rg)===!0,r=Oy(n?e:null),i=e&&!n?{...r,status:`live`}:r,a=wy.of(e,`agents`),o=rs({...Dy(e,zh,a,e=>e.list()),enabled:e?.capabilities.has(zh)===!0}),{refetch:s}=o,c=(0,X.useRef)(null);(0,X.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=wy.of(e,`agent-computers`);return{directory:o,inbox:i,computerChoices:rs({...Dy(e,Bh,l,()=>{if(!e)throw Error(`No App connection`);return ag(e.capabilities)}),enabled:e?.capabilities.has(Bh)===!0}),createAgent:is({mutationFn:t=>{if(!e)throw Error(`No App connection`);return ig(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:is({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Uh(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}}),setAgentAvatar:is({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Kh(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}})}}function wI(e,t){let n=Xt(),r=e?.capabilities.has(tg)===!0,i=wy.of(e,`agent-tool-policy`,t??`none`);return{canRead:r,status:rs({...Dy(e,tg,i,e=>t===null?Promise.resolve(null):e.status({agentId:t})),enabled:r&&t!==null}),approve:is({mutationFn:t=>{if(!e)throw Error(`No App connection`);return e.capabilities.require(tg).approve({agentId:t.agentId,level:`write`,expectedRevision:t.expectedRevision})},onSuccess:e=>{`error`in e||n.setQueryData(i,e)}})}}function TI(e,t){let n=Xt(),r=e?.capabilities.has(Xh)===!0;return{canUse:r,read:rs({...Dy(e,Xh,wy.of(e,`agent-instructions`,t??`none`),()=>{if(!e||t===null)throw Error(`No Agent is open`);return Zh(e.capabilities,t)}),enabled:r&&t!==null}),save:is({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Qh(e.capabilities,t)},onSuccess:t=>{n.setQueryData(wy.of(e,`agent-instructions`,t.agentId),t)}})}}var EI=new Set([`Enter`,` `]),DI=(0,X.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:f,onPointerUp:p,onPointerLeave:m,onPointerCancel:h,...g},_){let v=(0,X.useRef)(null),y=(0,X.useRef)(null),b=(0,X.useRef)(null),x=(0,X.useRef)(null),S=(0,X.useRef)(t),C=(0,X.useId)();(0,X.useEffect)(()=>{S.current=t},[t]),(0,X.useEffect)(()=>()=>{y.current?.cancel(),b.current!==null&&clearTimeout(b.current)},[]);let w=()=>{y.current=null,b.current=null,x.current=null,S.current();let e=v.current;if(!e||!Si(e))return;let t=Cn(e);e.animate([{opacity:1},{opacity:0}],{duration:t.normal,easing:br(t,t.easeExit)})},T=e=>{let t=v.current;if(a===!0||o||!t||y.current||b.current)return;if(x.current=e,!Si(t)){b.current=setTimeout(w,n);return}let r=Cn(t),i=t.animate([{transform:`scaleY(0)`},{transform:`scaleY(1)`}],{duration:n,easing:r.reduced?`steps(3, end)`:br(r,`cubic-bezier(0.3, 0, 0.7, 1)`)});i.addEventListener(`finish`,w),y.current=i},E=e=>{if(e!==void 0&&x.current!==e)return;x.current=null,b.current!==null&&(clearTimeout(b.current),b.current=null);let t=y.current,n=v.current;if(!t||!n)return;y.current=null;let r=getComputedStyle(n).transform;t.cancel();let i=Cn(n);n.animate([{transform:r===`none`?`scaleY(0)`:r},{transform:`scaleY(0)`}],{duration:i.fast,easing:br(i,i.ease)})};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(U,{...g,ref:_,disabled:a,loading:o,result:s,resultLabel:c??(s===void 0?void 0:e),"aria-describedby":C,className:Pn(`caps-hold-button`,i),onBlur:e=>{E(),l?.(e)},onPointerDown:e=>{f?.(e),e.button===0&&T(e.pointerId)},onPointerUp:e=>{p?.(e),E(e.pointerId)},onPointerLeave:e=>{m?.(e),E(e.pointerId)},onPointerCancel:e=>{h?.(e),E(e.pointerId)},onKeyDown:e=>{u?.(e),e.key===`Escape`&&E(),EI.has(e.key)&&(e.preventDefault(),e.repeat||T(`key`))},onKeyUp:e=>{d?.(e),EI.has(e.key)&&(e.preventDefault(),E(`key`))},children:[(0,Q.jsx)(`span`,{ref:v,"aria-hidden":`true`,className:`caps-hold-fill`}),e]}),(0,Q.jsx)(Zr,{id:C,children:r})]})});function OI({label:e,confirmLabel:t,onConfirm:n,error:r,variant:i=`destructive`,size:a,mode:o,phrase:s}){let[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(`idle`),m=(0,X.useRef)(!1),g=(0,X.useRef)(null),_=f===`busy`,v=o===`hold`||s.length>0&&u===s,y=_?void 0:r!==void 0&&r!==``?r:f instanceof Error?f.message:void 0,b=y?`failed`:f===`done`?`done`:void 0;async function x(){if(!(m.current||!v)){m.current=!0,p(`busy`);try{await n(),p(`done`),l(!1),d(``)}catch(e){p(Error(`Could not confirm the action. Try again.`,{cause:e}))}finally{m.current=!1}}}return o===`hold`?(0,Q.jsxs)(`div`,{className:`grid gap-sm`,children:[(0,Q.jsx)(DI,{variant:i,...a===void 0?{}:{size:a},loading:_,result:b,holdHint:t,onConfirm:()=>void x(),children:e}),(0,Q.jsx)(rr,{children:y})]}):(0,Q.jsxs)(h,{open:c,onOpenChange:(e,t)=>{if(m.current){t.cancel();return}l(e),d(``),p(`idle`)},children:[(0,Q.jsx)(Yt,{render:(0,Q.jsx)(U,{variant:i,...a===void 0?{}:{size:a}}),children:e}),(0,Q.jsx)(Nt,{initialFocus:g,children:(0,Q.jsxs)(Gi,{busy:_,onSubmit:e=>{e.preventDefault(),x()},children:[(0,Q.jsxs)(Ae,{children:[(0,Q.jsx)(tn,{children:e}),(0,Q.jsx)(Ut,{children:`Type the phrase exactly to confirm.`})]}),(0,Q.jsx)(dr,{label:`Type ${s} to confirm`,children:(0,Q.jsx)(Mr,{ref:g,autoComplete:`off`,autoCapitalize:`none`,spellCheck:!1,value:u,onChange:e=>{d(e.currentTarget.value)}})}),(0,Q.jsxs)(ca,{error:y,children:[(0,Q.jsx)(fe,{render:(0,Q.jsx)(U,{variant:`ghost`}),disabled:_,children:`Cancel`}),(0,Q.jsx)(U,{type:`submit`,variant:`destructive`,disabled:!v,loading:_,result:b,children:t})]})]})})]})}function kI(e){return`# ${e}'s instructions\n\nWrite what ${e} should do in every conversation, in plain language.\n\n- Keep replies short.\n`}var AI=new TextEncoder,jI=e=>e.toLocaleString(`en-US`),MI=.8,NI=`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 PI({agentId:e,name:t,file:n,loading:r,save:i,reload:a,notify:o}){let[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),g=(0,X.useId)(),_=n?.limit??0,v=AI.encode(s??``).byteLength,y=s!==null&&v>_,b=y||v>=_*MI,x=s===(l??``),S=n?.home===null,C=e=>{m(!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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(BE,{children:[(0,Q.jsx)(VE,{asChild:!0,children:(0,Q.jsx)(wi,{"aria-label":`Instructions`,"aria-haspopup":S?void 0:`dialog`,className:S?`opacity-40`:void 0,icon:(0,Q.jsx)(eT,{size:14,"aria-hidden":`true`}),disabled:r||n===void 0,onClick:()=>{n!==void 0&&(S?o(NI,`warning`):C(n))}})}),(0,Q.jsx)(HE,{children:S?NI:`Instructions`})]}),(0,Q.jsx)(h,{open:s!==null,onOpenChange:e=>{!e&&!d&&c(null)},children:(0,Q.jsxs)(Nt,{className:`flex flex-col gap-lg`,keepMounted:!1,forceBackdrop:!0,children:[(0,Q.jsxs)(Ae,{children:[(0,Q.jsxs)(tn,{children:[t,`'s instructions`]}),(0,Q.jsxs)(Ut,{children:[t,` follows these at the start of every conversation, and can update them as it learns.`]}),n?.home?(0,Q.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,Q.jsxs)(`div`,{className:`grid gap-xs`,children:[(0,Q.jsx)(`label`,{htmlFor:g,className:`text-sm font-medium`,children:`Instructions`}),(0,Q.jsx)(Tr,{id:g,rows:14,className:`font-mono text-sm`,value:s??``,invalid:y,disabled:d,placeholder:kI(t),onChange:e=>{c(e.currentTarget.value)}}),b?(0,Q.jsxs)(`p`,{className:`text-xs ${y?`text-error`:`text-base-content/70`}`,role:y?`alert`:void 0,children:[s!==null&&v!==s.length?`About `:``,jI(v),` of `,jI(_),` characters`,y?`. Shorten it to save.`:``]}):null]}),(0,Q.jsxs)(oe,{children:[(0,Q.jsx)(U,{type:`button`,variant:`ghost`,disabled:d,onClick:()=>{c(null)},children:`Cancel`}),p?s===(l??``)?(0,Q.jsx)(U,{type:`button`,variant:`primary`,onClick:()=>{w()},children:`Reload`}):(0,Q.jsx)(OI,{mode:`hold`,variant:`primary`,label:`Hold to reload`,confirmLabel:`Hold to reload and lose your edits`,onConfirm:w}):(0,Q.jsx)(U,{type:`button`,variant:`primary`,loading:d,disabled:d||s===null||y||x,onClick:()=>{s!==null&&(f(!0),i(e,{expectedContent:l,content:s}).then(e=>{f(!1),e===`saved`?c(null):e===`conflict`?(m(!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 FI({agentId:e,name:t,avatar:n,setAvatar:r}){let[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(!1),c=(0,Q.jsx)(Xr,{avatar:n,name:t,size:24});return r===void 0?(0,Q.jsx)(`span`,{className:`flex-none`,children:c}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(U,{variant:`ghost`,size:`sm`,"aria-label":`Change avatar`,className:`flex-none p-0`,onClick:()=>{a(n)},children:c}),(0,Q.jsx)(h,{open:i!==null,onOpenChange:e=>{!e&&!o&&a(null)},children:(0,Q.jsxs)(Nt,{className:`flex flex-col gap-lg`,keepMounted:!1,children:[(0,Q.jsxs)(Ae,{children:[(0,Q.jsxs)(tn,{children:[t,`'s avatar`]}),(0,Q.jsxs)(Ut,{children:[`Every conversation with `,t,` shows this look.`]})]}),i===null?null:(0,Q.jsx)(uj,{value:i,disabled:o,onChange:a}),(0,Q.jsxs)(oe,{children:[(0,Q.jsx)(U,{type:`button`,variant:`ghost`,disabled:o,onClick:()=>{a(null)},children:`Cancel`}),(0,Q.jsx)(U,{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 II=(0,X.forwardRef)(function({className:e,orientation:t,variant:n=`grip`,value:r,min:i,max:a,onValueChange:o,onKeyDown:s,...c},l){return(0,Q.jsx)(`div`,{...c,ref:l,className:Pn(`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,Q.jsx)(`span`,{className:`caps-resize-grip`,"aria-hidden":`true`})})});tt({frames:new Map,order:[],tiles:[],minima:new Map,participating:new Set,mainSize:void 0,zoomed:null,gesture:null,restore:new Map});function LI(e,t=!0,n){let r=(0,X.useRef)(e);r.current=e;let i=(0,X.useRef)(null);return(0,X.useEffect)(()=>(t||i.current?.release(!0),()=>i.current?.release(!0)),[t]),(0,X.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,X.createContext)(null);var RI=(0,X.createContext)(null);(0,X.forwardRef)(function({layer:e,style:t,children:n,...r},i){let a=(0,X.useContext)(RI),o=a?.update,s=a?.roots.get(`dialog`),[c,l]=(0,X.useState)(!1);(0,X.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,X.useRef)(null);(0,X.useImperativeHandle)(i,()=>u.current);let d=(0,X.useCallback)(t=>{u.current=t,o?.(e,t)},[o,e]);return(0,X.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 zI={min:224,max:480,initial:320},BI={agentRailOpen:!0,listRailOpen:!0,listWidth:zI.initial},VI=`layout`,HI=N(q({agentRailOpen:r,listRailOpen:r,listWidth:Hi.pipe(V(ft()))}));function UI(e){return Math.round(Math.min(zI.max,Math.max(zI.min,e)))}async function WI(e){let t=await e.read(VI),n=HI(t.member?.value);return{layout:lo(n)?{...n.value,listWidth:UI(n.value.listWidth)}:BI,revision:t.member?.revision??null}}async function GI(e,t,n){let{revision:r}=await e.write({key:VI,scope:`member`,basedOn:n,value:t});return r}function KI(e){let[t,n]=(0,X.useState)(BI),r=(0,X.useRef)(null),i=(0,X.useRef)(!1),a=(0,X.useRef)(!1);return(0,X.useEffect)(()=>{if(e===void 0)return;let t=!1;return WI(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,X.useEffect)(()=>{e===void 0||!a.current||!i.current||GI(e,t,r.current).then(e=>{r.current=e},e=>{console.warn(`Grove could not save its rail layout`,e)})},[e,t]),[t,(0,X.useCallback)(e=>{a.current=!0,n(e)},[])]}var qI=8e3,JI=(0,X.forwardRef)(function({className:e,detail:t,framed:n=!0,icon:r,message:i,onRetry:a,size:o=`md`,slowAfterMs:s=qI,variant:c=`line`,...l},u){let[d,f]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{if(f(!1),!Number.isFinite(s))return;let e=globalThis.setTimeout(()=>{f(!0)},s);return()=>{globalThis.clearTimeout(e)}},[s,i]),(0,Q.jsxs)(`div`,{...l,className:Pn(`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,Q.jsx)(`span`,{"aria-hidden":`true`,className:`caps-loading-state-icon`,children:r}):null,(0,Q.jsx)(un,{decorative:!0,size:o,variant:c}),(0,Q.jsxs)(`span`,{className:`caps-loading-state-copy`,children:[(0,Q.jsx)(`span`,{children:i}),t?(0,Q.jsx)(`span`,{className:`caps-loading-state-detail`,children:t}):null,d?(0,Q.jsx)(`span`,{className:`caps-loading-state-detail`,children:`Still working…`}):null]}),d&&a?(0,Q.jsx)(U,{className:`caps-loading-state-retry`,size:`sm`,variant:`outline`,onClick:a,children:`Retry`}):null]})}),YI=[{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 XI({connection:e,navigation:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.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,Q.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,Q.jsx)(mt,{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,Q.jsx)(`span`,{className:`block`,style:{width:`3.5rem`,height:`3.5rem`},children:(0,Q.jsx)(oT,{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,Q.jsx)(U,{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,Q.jsx)(Sr,{role:`alert`,message:`Model keys could not open. Try opening them again.`,onRetry:()=>void o(),onDismiss:()=>{r(!1)}}):null,(0,Q.jsx)(`ol`,{className:`m-0 grid list-none gap-lg p-0 text-sm @xl:grid-cols-3`,children:YI.map((e,t)=>(0,Q.jsxs)(`li`,{className:`flex flex-col gap-xs border-t border-base-300 pt-md`,children:[(0,Q.jsxs)(`strong`,{className:`font-semibold`,children:[String(t+1),`. `,e.title]}),(0,Q.jsx)(`span`,{className:`text-(--stipe-fg-muted)`,children:e.detail})]},e.title))})]})}function ZI({description:e,icon:t,label:n,density:r=`regular`,appearance:i=`plain`,iconSize:a=`default`,size:o,trailing:s,...c}){return(0,Q.jsxs)(U,{...c,className:Pn(`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,Q.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,Q.jsxs)(`span`,{className:`caps-action-row-copy`,children:[(0,Q.jsx)(`span`,{className:`caps-action-row-label max-w-full truncate`,children:n}),e?(0,Q.jsx)(`span`,{className:`caps-action-row-description max-w-full truncate`,children:e}):null]}),s?(0,Q.jsx)(`span`,{className:`caps-action-row-trailing`,children:s}):null]})}function QI(e,t,n,r,i,a){let o=[];r&&o.push({kind:`hint`,key:`loading`,loading:!0});let s=0,c=nD(e),l=new Map(c.map(e=>[rD(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:rD(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:rD(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 $I({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?rD(s,c):null,[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),b=g||v,[x,S]=(0,X.useState)(0),[C,w]=(0,X.useState)({placements:null,openKey:h,reopened:x}),T=(0,X.useMemo)(()=>QE(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,X.useEffect)(()=>{!b&&(C.placements!==T||C.openKey!==h||C.reopened!==x)&&w({placements:T,openKey:h,reopened:x})},[b,C,T,h,x]),(0,X.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 E=(0,X.useMemo)(()=>QI(t,T,f,r,i,a),[t,T,f,r,i,a]),D=(0,X.useCallback)(e=>E[e]?.key??e,[E]),O=Ye({count:E.length,getScrollElement:()=>e.current,getItemKey:D,estimateSize:e=>E[e]?.kind===`heading`?24:44,measureElement:(e,t,n)=>{let r=ct(e,t,n);return r>0?r:ct(e,void 0,n)||n.options.estimateSize(n.indexFromElement(e))},initialRect:{width:320,height:800},overscan:5,useFlushSync:!1});return(0,Q.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,Q.jsx)(`div`,{style:{height:O.getTotalSize(),position:`relative`,width:`100%`},children:O.getVirtualItems().map(e=>{let t=E[e.index],r=t.kind===`session`||t.kind===`unavailable`?t.session:null,i=r?n.get(r.agentId):void 0;return(0,Q.jsx)(`div`,{"data-index":e.index,ref:O.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,Q.jsx)(M,{style:{paddingBottom:0},children:t.title}):t.kind===`hint`?t.loading?(0,Q.jsx)(JI,{className:`inbox-empty px-2 py-3 text-sm text-(--stipe-fg-muted)`,message:`Loading conversations…`}):(0,Q.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,Q.jsx)(ZI,{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,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Q.jsx)(ri,{name:`internet`,size:14}),t.website.siteLabel]}),trailing:t.website.conversation.held?(0,Q.jsx)(`span`,{className:`text-xs`,children:t.website.conversation.heldByYou?`You're replying`:`With a teammate`}):t.website.conversation.needsYou?(0,Q.jsx)(Tn,{size:`compact`,tone:`accent`,title:t.website.conversation.needsYou.reason}):null,onClick:()=>{m(t.website)},variant:`ghost`}):t.kind===`unavailable`?i?(0,Q.jsx)(tL,{agent:i,row:t.session}):null:i?(0,Q.jsx)(eL,{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 eL({agent:e,session:t,attention:n,pending:r,selected:i,onSelect:a,onDelete:o,deleting:s}){let c=GE(t.state),l=t.state===`errored`,u=(0,Q.jsxs)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:[(0,Q.jsxs)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:[r||c||l?(0,Q.jsx)(`span`,{className:`sr-only`,children:r?`Opening`:UE[t.state]}):null,r||c?(0,Q.jsx)(Tn,{size:`compact`,title:r?`Opening`:UE[t.state],motion:t.state===`running`||r?`pulse`:`none`,tone:r?`neutral`:t.state===`needs_you`?`accent`:`info`}):l?(0,Q.jsx)(Tn,{size:`compact`,title:UE.errored,tone:`error`}):n?(0,Q.jsx)(Tn,{size:`compact`,title:`Finished since your last visit`,tone:`neutral`}):null]}),(0,Q.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:nL(t.lastActivityAt)})]});return(0,Q.jsxs)(`div`,{className:`relative group`,children:[(0,Q.jsx)(ZI,{"aria-current":i?`page`:void 0,"aria-label":`${t.title||`New conversation`} — ${iD(e)}${n?` — Finished since your last visit`:``}${t.ready?` — Ready`:c||l?` — ${UE[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:iD(e),label:t.title||`New conversation`,onClick:a,trailing:u,variant:`ghost`}),o?(0,Q.jsx)(wi,{"aria-label":`Delete conversation ${t.title||`New conversation`}`,title:`Delete conversation`,icon:(0,Q.jsx)(aT,{}),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 tL({agent:e,row:t}){return(0,Q.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,Q.jsxs)(`span`,{className:`inbox-row-copy flex min-w-0 flex-1 flex-col`,children:[(0,Q.jsx)(`strong`,{className:`truncate text-sm font-medium`,children:`Conversation unavailable`}),(0,Q.jsxs)(`small`,{className:`truncate text-xs text-(--stipe-fg-muted)`,children:[iD(e),` `,(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),` This saved conversation could not be read.`]})]}),(0,Q.jsx)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:(0,Q.jsx)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:(0,Q.jsx)(Tn,{size:`compact`,tone:`error`,title:`This saved conversation could not be read`})})})]})}function nL(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 rL=To().min(1).max(256),iL=La().int().nonnegative();Sa(`state`,[za({state:oo(`agent`),version:iL}),za({state:oo(`requested`),version:iL,reason:To().max(4e3),at:La().int().nonnegative()}),za({state:oo(`person`),version:iL,memberId:rL,memberName:To().min(1).max(128),since:La().int().nonnegative()})]);var aL=za({bindingId:rL,agentId:rL,origins:wo(To().min(1).max(2048)).min(1).max(16),lifecycle:ro([`active`,`suspended`])}),oL=za({sessionId:rL,label:To().max(4096),lastEventAt:La().int().nonnegative(),needsYou:za({at:La().int().nonnegative(),reason:To().max(4e3)}).nullable(),held:Co(),heldByYou:Co(),heldByName:To().min(1).max(128).nullable(),holdVersion:La().int().nonnegative()}),sL=za({bindingId:rL}).extend({sessionId:rL});sL.extend({requestId:To().min(1).max(128),text:To().trim().min(1).max(4e3)});var cL=za({expectedVersion:iL,confirm:Co()});sL.extend(cL.shape),sL.extend({expectedVersion:iL});var lL=za({websites:wo(aL).max(1e3)}),uL=za({conversations:wo(oL).max(100)});za({conversation:oL});var dL=za({status:oo(`sent`)}),fL=xh(`channels.read`,1,ya(()=>Sh({list:wh(Ch(lL)),conversations:wh(Ch(uL))}))),pL=xh(`channels.personal.manage`,1,ya(()=>Sh({hold:wh(Ch(oL)),release:wh(Ch(oL)),dismiss:wh(Ch(oL)),reply:wh(Ch(dL))})));function mL(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 hL(e,t){(0,X.useSyncExternalStore)(t=>e?.capabilities.subscribe(t)??(()=>void 0),()=>e?.capabilities.version??0);let n=Xt(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(null),s=e?.capabilities.has(fL)===!0,c=e?.capabilities.has(pL)===!0,l=rs({...Dy(e,fL,wy.of(e,`websites`),e=>e.list()),enabled:s}),u=s?l.data?.websites??[]:[],d=ts({queries:u.map(t=>({...Dy(e,fL,wy.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,X.useMemo)(()=>e===null?null:dT({connection:e,queryClient:n,services:t,onPending:()=>void 0,onConversation:o,onError:t=>{t!==null&&Pi(e.ui,{variant:`error`,message:`That conversation could not be opened. Try again.`})}}),[e,n,t]);(0,X.useEffect)(()=>()=>{m?.close()},[m]),(0,X.useEffect)(()=>{s||m?.clear()},[s,m]);let h=is({mutationFn:t=>{if(e===null)throw Error(`No App connection`);let n=e.capabilities.require(pL);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(wy.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,X.useMemo)(()=>a===null||g===void 0||_===void 0||e===null?null:mL(a.session,{bindingId:g,sessionId:_,canReply:()=>v&&e.capabilities.has(pL),reply:t=>e.capabilities.require(pL).reply(t)}),[e,a,g,_,v]),b=(0,X.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 gL=(0,X.lazy)(async()=>({default:(await de(()=>import(`./website-conversation-CAaCsY4j.js`),__vite__mapDeps([0,1,2,3,4]))).WebsiteConversation})),_L=(0,X.lazy)(async()=>({default:(await de(()=>import(`./parakeet-conversation-Dluuo5dN.js`),__vite__mapDeps([5,1,2,3,4,6]))).ParakeetConversation})),vL={openAgent:cg,createClient:_e,autoOpen:!0},yL=[`agent.list`,`agent.manage`,`agent.read`,`agent.send`],bL=[`agent.read`,`agent.send`,`agent.manage`],xL=F({family:`grove-session-create-request`,version:1,kinds:{request:{prefix:`request`}}});async function SL(e,t,n,r){let i=await n.openAgent(e.capabilities,{agentId:t}),a=n.createClient({baseUrl:i.baseUrl,eventSource:uT(i.fetch),fetch:i.fetch});try{return await r(a)}finally{Promise.allSettled([a.close(),i.close()])}}function CL({open:e,renderConversation:t,connection:n,commands:r,composeDraft:i,onPrefilled:a,onForked:o,onOpen:s,models:c,autoFocus:l,empty:u,opening:d=!1,label:f=`Conversation`,loadingAgent:p}){let m=e.session,h=(0,X.useRef)(null);(0,X.useEffect)(()=>{h.current?.toggleAttribute(`inert`,d)},[d]);let[g,_]=(0,X.useState)({kind:`loading`});return(0,X.useEffect)(()=>{if(!n||t)return;let r=new AbortController;return _({kind:`loading`}),yI(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]),(0,X.useEffect)(()=>{let i=r.contribute({sourceId:`grove-session`,namespace:`session`,commands:[...Yw(m,{sourceId:`grove-session`,namespace:`session`,sessionResumeAvailable:!1,forkAvailable:!0,onForked:o}),...t?[]:Bw(m,{sourceId:`grove-session`,namespace:`session`,models:g.kind===`ready`?g.models:[],refreshModels:t=>n?yI(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,n,e.agentId]),(0,Q.jsx)(`section`,{ref:h,className:`inbox-conversation min-h-0 min-w-0 flex-1`,"data-inbox-conversation":!0,"aria-busy":d,"aria-label":f,children:t?t(e,i,s):(0,Q.jsx)(X.Suspense,{fallback:(0,Q.jsx)(CT,{agent:p,message:`Opening conversation…`}),children:(0,Q.jsx)(_L,{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 wL={state:fT,error:null},TL=()=>()=>void 0;function EL(e){return gh(e.connection),(0,Q.jsx)(DL,{...e},JSON.stringify(wy.of(e.connection)))}function DL(e){let t=(0,X.useMemo)(cI,[e.connection]);return(0,Q.jsx)(rI,{value:(0,Q.jsx)(OL,{...e,router:t}),children:(0,Q.jsx)($F,{router:t})})}function OL({router:e,connection:t,services:r=vL}){let{agentFilterId:i,setFilter:a,selection:o,open:s}=uI(e,t?.window.navigation),c=Xt(),l=hL(t,r),u=(0,X.useMemo)(()=>t===null?null:ST({connection:t,queryClient:c,services:r,navigate:t=>t===null?e.navigate({to:`/`,search:!0,replace:!0}):s(t.agentId,t.sessionId),shownRoute:()=>lI(e)}),[t,s,c,e,r]),d=(0,X.useSyncExternalStore)(u?.subscribe??TL,u?.snapshot??(()=>wL)),{directory:f,inbox:p,computerChoices:m,createAgent:h,renameAgent:g,setAgentAvatar:_}=CI(t),v=f.data??[],y=f.isPending&&(t?.capabilities.has(zh)??!0),b=f.error?.message??null,x=h.isPending,S=is({mutationFn:e=>{if(!t)throw Error(`No App connection`);return SL(t,e.agentId,r,t=>t.createSession(e.requestId))}}),C=is({mutationFn:e=>{if(!t)throw Error(`No App connection`);return SL(t,e.agentId,r,t=>t.deleteSession(e.sessionId))},onError:()=>{t&&Pi(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=xT(d.state),E=bT(d.state),[D,O]=(0,X.useState)(!1),k=E?.agentId??null,A=E?.sessionId??null,[j,M]=(0,X.useState)(null),ee=(0,X.useRef)(null),te=(0,X.useMemo)(()=>t?.capabilities.has(ob)?t.capabilities.require(ob):void 0,[t]),[ne,N]=KI(te),{agentRailOpen:P,listRailOpen:re,listWidth:F}=ne,I=e=>{N(t=>({...t,agentRailOpen:e(t.agentRailOpen)}))},ie=e=>{N(t=>({...t,listRailOpen:e(t.listRailOpen)}))},L=e=>{N(t=>({...t,listWidth:UI(e(t.listWidth))}))},ae=LI({begin:()=>!0,move:e=>{L(t=>t+e)},end:()=>void 0}),[oe,se]=(0,X.useState)(!1),ce=(0,X.useRef)(null),le=uD(ce),R=le??!0,ue=(0,X.useRef)(null),[de,fe]=(0,X.useState)(null),pe=h.error?.message??null,me=h.data,he=(0,X.useRef)(null),[z,ge]=(0,X.useState)(null),[_e,ve]=(0,X.useState)(null),ye=gh(t),be=ye?.openRequest??null,xe=ye?.setup?.models===`missing`,Se=(0,X.useRef)(null),Ce=(0,X.useRef)(null);(0,X.useEffect)(()=>{if(u!==null)return u.observeRoute(Ce.current),()=>{he.current=null,u.close()}},[u]);let[we,Te]=(0,X.useState)(null),Ee=(0,X.useMemo)(()=>lr(),[]),De=(0,X.useMemo)(()=>t===null?null:dT({connection:t,queryClient:c,services:r,onPending:()=>void 0,onConversation:Te,onError:ge,reportsSelection:!1}),[t,c,r]);(0,X.useEffect)(()=>De===null?void 0:()=>{De.close()},[De]);let Oe=(0,X.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&&De?.select(n,r)},[De]),ke=(0,X.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]),Ae=o?.agentId,je=o?.sessionId;Ce.current=Ae!==void 0&&je!==void 0?{agentId:Ae,sessionId:je}:null,(0,X.useEffect)(()=>{u?.observeRoute(Ce.current)},[u,Ae,je]);let Me=(0,X.useCallback)(e=>{E&&(ke(E.agentId,e),p.refresh())},[E,ke,p.refresh]);(0,X.useEffect)(()=>{if(!t||be===null){be===null&&(Se.current=null);return}if(be.kind!==`navigate`||Se.current===be.requestId)return;let e=be.params.find(e=>e.key===`agent`)?.value,n=be.params.find(e=>e.key===`session`)?.value;!e||!n||(Se.current=be.requestId,a(e),ke(e,n,!0))},[t,be,ke,a]);let Ne=(0,X.useCallback)(async e=>{if(!t||x||!t.capabilities.has(Bh))return!1;try{let t=await h.mutateAsync(e);return a(t.agentId),fe(t.agentId),M(null),!0}catch{return!1}},[t,x,h.mutateAsync,a]),Pe=!!E||l.selected!==void 0,Fe=(0,X.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)){ge(null);try{let t=he.current?.agentId===e?he.current:{agentId:e,requestId:n===`auto`&&te!==void 0?await SI(te,()=>xL.request.generate()):xL.request.generate()};he.current=t;let i=await S.mutateAsync(t);u.created(r.ticket,{agentId:e,sessionId:i}).accepted&&(S.isError&&S.reset(),l.clear(),O(!1)),p.refresh(),M(null),se(!1),he.current===t&&(he.current=null);return}catch(e){return u.createFailed(r.ticket),console.error(`Grove conversation creation failed`,e),Pe&&Pi(t.ui,{variant:`error`,message:`The conversation could not be started. Try again.`}),e instanceof Error?e.message:`Couldn't start the conversation.`}}},[t,Pe,u,te,w,S.isError,S.mutateAsync,S.reset,l.clear,p.refresh]);(0,X.useEffect)(()=>{if(!(!t||be?.kind!==`compose`)&&Se.current!==be.requestId&&!(!E&&y)&&(Se.current=be.requestId,ve({requestId:be.requestId,text:be.text}),!E)){let e=t.capabilities.has(rg)?v.find(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)):void 0;e?Fe(e.agentId):M(`agent`)}},[v,t,y,E,be,Fe]);let Ie=_I({setDraft:e=>T!==null||!E||!t?.capabilities.has(rg)||!v.some(e=>e.agentId===E.agentId&&e.sessionOperations.includes(`agent.send`))?!1:(ve({requestId:lt(),text:e}),!0),newConversation:()=>{E&&Fe(E.agentId)},openPermissions:()=>{t?.ui.requestAppPermissions({}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})}},t?.commands),Le=new Set(l.rows.map(e=>`${e.agentId}:${e.conversation.sessionId}`)),Re=p.items.filter(e=>!(`kind`in e)).filter(e=>!Le.has(`${e.agentId}:${e.sessionId}`)),ze=ts({queries:(E?[E.session]:[]).map(e=>({...vr(e),enabled:!1}))}).at(0)?.data?.snapshot,Be=(0,X.useMemo)(()=>E&&ze?{agentId:E.agentId,sessionId:E.sessionId,state:Je(ze)}:void 0,[E,ze]),Ve=(0,X.useMemo)(()=>eD(v,D&&l.canRead?[]:Re,i,Be),[i,v,Re,D,l.canRead,Be]),He=(0,X.useMemo)(()=>{let e=new Map;for(let t of Re)`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},[Re]),Ue=(0,X.useMemo)(()=>new Map(v.map(e=>[e.agentId,e])),[v]),We=(0,X.useRef)(null),Ge=Re.find(e=>e.agentId===k&&e.sessionId===A),Ke=Ge!==void 0&&Ge.state!==`unavailable`,qe=Ge!==void 0&&Ge.state!==`unavailable`?Ge.settledAt:void 0;(0,X.useEffect)(()=>{!Ke||k===null||A===null||p.visit(k,A).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},[Ke,qe,k,A,p.visit]);let Ye=p.status===`loading`,Xe=p.status===`error`,Ze=t?.capabilities.has(Bh)??!1,Qe=t?.capabilities.has(rg)??!1,$e=v.filter(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)),et=$e.find(e=>e.agentId===(de??i))??$e.at(0),tt=Qe&&et!==void 0,nt=()=>{t?.ui.requestAppPermissions({agents:yL}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},rt=me&&(!me.sessionOperations.includes(`agent.read`)||!me.sessionOperations.includes(`agent.send`)||!me.sessionOperations.includes(`agent.manage`))?`Agent created. Allow Grove to read, send messages and manage its sessions to start a conversation.`:_e&&!E&&!tt&&h.isIdle?`Choose an Agent to compose your game idea.`:null,it=(0,X.useMemo)(()=>eD(v,Re,null,Be),[v,Re,Be]),at=(e,t)=>{se(!1),ke(e,t)},ot=()=>{ue.current=document.activeElement instanceof HTMLElement?document.activeElement:null,se(!0)},st=nD(Ve).length,ct=R&&re,ut=R&&xe&&st===0&&Ve.unavailable.length===0&&l.rows.length===0&&!E&&!l.selected&&!y&&!Ye&&!l.loading&&!Xe&&!b&&!l.failed;_h(t,[...R?[{kind:`button`,id:`agents`,text:`Agents`,expanded:P,title:P?`Hide Agents`:`Show Agents`},...ut?[]:[{kind:`button`,id:`conversations`,text:`Conversations`,expanded:re,title:re?`Hide conversations`:`Show conversations`}]]:[{kind:`button`,id:`agents`,text:`Agents and conversations`,opens:`dialog`,expanded:oe}],...we===null?[]:[{kind:`button`,id:`close-beside`,text:`Close beside`,title:`Close beside conversation`}]],e=>{if(j!==null)return!1;if(e.itemId===`close-beside`&&we!==null)De?.clear();else if(R&&e.itemId===`agents`)I(e=>!e);else if(R&&e.itemId===`conversations`)ie(e=>!e);else if(!R&&e.itemId===`agents`)oe?se(!1):ot();else return!1;return!0});let dt=e=>{a(e),fe(e);let t=[...it.active,...it.settled].filter(t=>t.agentId===e).sort((e,t)=>t.lastActivityAt-e.lastActivityAt).at(0);t&&at(e,t.sessionId)},ft={"--grove-list-width":`${String(F)}px`},pt=E?Ue.get(E.agentId):void 0,B=i===null?void 0:Ue.get(i),ht=t?.capabilities.has(Hh)??!1,gt=v.length===1?v[0]:void 0,_t=B??gt,vt=t?.capabilities.has(Gh)??!1,yt=wI(t,B?.agentId??null),bt=TI(t,B?.agentId??null),xt=(0,X.useCallback)(async(e,t)=>{try{return await bt.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`}},[bt.save.mutateAsync]),St=(0,X.useCallback)(async()=>{let e=await bt.read.refetch({throwOnError:!0});if(e.data===void 0)throw Error(`No instructions file`);return e.data},[bt.read.refetch]),Ct=(0,X.useCallback)((e,n)=>{t?.ui.showToast({message:e,tone:n}).catch(e=>{console.error(`Instructions toast failed`,e)})},[t]),wt=(0,X.useRef)(!1);(0,X.useEffect)(()=>{r.autoOpen!==!0||wt.current||!t||E||be!==null||y||Ye||Xe||b||xe||st>0||et===void 0||!Qe||w!==null||(wt.current=!0,Fe(et.agentId,`auto`))},[Qe,t,y,b,Xe,st,Ye,xe,E,be,r.autoOpen,et,Fe,w]);let Tt=(0,X.useCallback)(async(e,n)=>{if(!t)return!1;try{return await g.mutateAsync({agentId:e,name:n}),!0}catch{return!1}},[t,g.mutateAsync]),V=(0,X.useCallback)(async(e,n)=>{if(!t)return!1;try{return await _.mutateAsync({agentId:e,avatar:n}),!0}catch{return!1}},[t,_.mutateAsync]),Et=(0,X.useCallback)(()=>{let e=yt.status.data;!B||e==null||yt.approve.mutate({agentId:B.agentId,expectedRevision:e.revision})},[B,yt.status.data,yt.approve]),Dt=(0,X.useCallback)(e=>{if(!(!t||x||w!==null||e===`agent`&&!Ze)){if(e===`agent`&&xe){t.ui.showToast({message:aD,tone:`info`}).catch(e=>{console.error(`Grove toast failed`,e)});return}j===null&&(ee.current=oe?ue.current:document.activeElement instanceof HTMLElement?document.activeElement:null),se(!1),e===`session`&&fe(pt?.agentId??i??$e.at(0)?.agentId??null),M(e)}},[t,x,w,Ze,xe,j,oe,pt?.agentId,i,$e]);(0,X.useEffect)(()=>{let e=e=>{e.defaultPrevented||e.repeat||!e.ctrlKey||e.altKey||e.metaKey||e.key.toLowerCase()!==`n`||!t||e.shiftKey&&!Ze||(e.preventDefault(),Dt(e.shiftKey?`agent`:`session`))};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[t,Ze,Dt]);let Ot=t!==null&&Ze&&!y&&!xe&&!b&&v.length===0,kt=f.isFetching;(0,X.useEffect)(()=>{Ot&&Pi(t.ui,{variant:`error`,message:`Your first Agent couldn't be set up.`})},[Ot,t]);let At=S.isError?S.variables:null,jt=At&&j!==`session`&&!Pe?(0,Q.jsx)(n,{className:`inbox-empty m-auto max-w-[28rem]`,tone:`error`,title:`Couldn't start the conversation.`,description:S.error?.message,action:(0,Q.jsx)(U,{variant:`outline`,onClick:()=>void Fe(At.agentId),children:`Retry`})}):null;return(0,Q.jsxs)(`main`,{ref:ce,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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(bj,{open:j===`agent`,pending:x,error:pe,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:Ne,onClose:()=>{M(null)},returnFocus:ee}),j===`session`?(0,Q.jsx)(xj,{open:!0,agents:Qe?$e:[],defaultAgentId:et?.agentId??null,start:Fe,pending:w!==null,onClose:()=>{M(null)},onNewAgent:Ze?()=>{M(`agent`)}:void 0,returnFocus:ee}):null]}):null,le===null?null:(0,Q.jsxs)(dD,{desktop:R,open:oe,onOpenChange:se,returnFocus:ue,children:[(0,Q.jsx)(sD,{open:P,agents:v,agentActivity:He,agentFilterId:i,websitesSelected:D,websitesVisible:l.canRead,canCreate:t!==null&&Ze,modelsMissing:xe,createOpen:j===`agent`,onAll:()=>{a(null),O(!1)},onWebsites:()=>{a(null),O(!0)},onAgent:e=>{O(!1),dt(e)},onCreate:()=>{Dt(`agent`)}}),ut?null:(0,Q.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 ${re?`flex`:`flex @min-[900px]/grove:hidden`}`,style:ft,"aria-label":`Conversations`,children:[R?(0,Q.jsx)(II,{"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:F,min:zI.min,max:zI.max,onValueChange:e=>{L(()=>e)},onDoubleClick:()=>{L(()=>zI.initial)},...ae}):null,(0,Q.jsxs)(`header`,{className:`inbox-header flex h-10 flex-none items-center gap-1 border-b border-base-300 pl-3 pr-1`,children:[B?(0,Q.jsx)(FI,{agentId:B.agentId,name:iD(B),avatar:B.avatar,...vt?{setAvatar:V}:{}},B.agentId):null,(0,Q.jsx)(Bn,{level:2,className:`m-0 min-w-0 flex-1 truncate text-sm`,children:D&&l.canRead?`Websites`:B?iD(B):`All agents`}),_t&&ht?(0,Q.jsx)(fI,{agentId:_t.agentId,name:_t.name,rename:Tt},_t.agentId):null,B&&bt.canUse?(0,Q.jsx)(PI,{agentId:B.agentId,name:B.name,file:bt.read.data,loading:bt.read.isPending,save:xt,reload:St,notify:Ct},B.agentId):null,t&&(tt||Ze)?(0,Q.jsx)(wi,{"aria-label":`New conversation`,"aria-haspopup":`dialog`,icon:(0,Q.jsx)(iT,{}),iconSize:`sm`,size:`sm`,onClick:()=>{Dt(`session`)}}):null]}),B&&yt.canRead?(0,Q.jsx)(pI,{status:yt.status.data,approving:yt.approve.isPending,onApprove:Et}):null,rt?(0,Q.jsx)(n,{tone:`info`,title:rt,action:(0,Q.jsx)(U,{variant:`ghost`,onClick:()=>{t?.ui.requestAppPermissions({agents:bL}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},children:`Allow conversation access`})}):null,t&&v.length>0&&!tt&&!Ze?(0,Q.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,Q.jsx)(Bn,{level:2,id:`inbox-agent-access-title`,className:`inbox-access-title m-0`,children:`Let Grove manage your Agents`}),(0,Q.jsx)(`p`,{children:`Grove creates Agents and carries their conversations. Your Team decides what it may do.`}),(0,Q.jsx)(U,{size:`sm`,onClick:nt,children:`Allow Agent access`})]}):null,b?(0,Q.jsx)(n,{className:`inbox-error`,tone:`error`,title:b,action:(0,Q.jsx)(U,{variant:`ghost`,size:`sm`,onClick:()=>{f.refetch()},children:`Try again`})}):null,Xe?(0,Q.jsx)(n,{className:`inbox-error`,tone:`error`,title:`Conversations are unavailable.`,action:(0,Q.jsx)(U,{variant:`ghost`,size:`sm`,onClick:()=>{p.refresh()},children:`Retry conversations`})}):null,(0,Q.jsx)(yE,{ref:We,className:`inbox-surface min-h-0 flex-1`,"aria-label":`Conversations`,children:t?y?(0,Q.jsx)(JI,{framed:!1,message:`Loading Agents…`}):(0,Q.jsx)($I,{viewport:We,view:Ve,agents:Ue,loading:Ye||l.loading,failed:!!b||Xe||l.failed,showEmptyState:!xe,pendingSelection:T,selectedAgentId:k,selectedSessionId:A,onSelect:at,onDelete:Qe?(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),se(!1),l.select(e)}}):(0,Q.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)]}),R&&!re&&!ut?(0,Q.jsx)(`div`,{className:`flex w-10 flex-none flex-col items-center border-r border-base-300 pt-1`,children:(0,Q.jsx)(wi,{"aria-label":`Show conversations`,"aria-controls":`grove-list-rail`,"aria-expanded":!1,icon:(0,Q.jsx)(tT,{}),iconSize:`sm`,size:`sm`,onClick:()=>{ie(()=>!0)}})}):null]}),(0,Q.jsxs)(`section`,{className:`inbox-conversation-shell flex min-h-0 min-w-0 flex-1 flex-col`,"aria-label":`Conversation`,children:[(0,Q.jsx)(cD,{app:t}),z??d.error?(0,Q.jsx)(n,{className:`inbox-error m-2`,tone:`error`,title:z??d.error??``}):null,l.selected?(0,Q.jsx)(X.Suspense,{fallback:null,children:(0,Q.jsx)(gL,{inbox:l,ui:t?.ui??null})}):T!==null&&E===null?(0,Q.jsx)(JI,{className:`m-auto`,framed:!1,message:`Opening conversation…`}):E?(0,Q.jsx)(CL,{open:E,connection:t,commands:Ie,renderConversation:r.renderConversation,composeDraft:_e,onPrefilled:()=>{ve(null)},onForked:Me,onOpen:Oe,models:ye?.setup?.models,autoFocus:R&&j===null,opening:T!==null}):!t||y?(0,Q.jsx)(JI,{className:`m-auto`,framed:!1,message:t?Ze?`Getting Shiitake ready…`:`Loading Agents…`:`Connecting to Oyster…`}):xe&&(v.length>0||Ze)?(0,Q.jsx)(XI,{connection:t,navigation:R?void 0:{open:oe,onOpen:ot}}):v.length===0&&!b?(0,Q.jsx)(mt,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`speech`,thinking:kt,renderVisual:({speaking:e,thinking:t})=>(0,Q.jsx)(oT,{className:`h-full w-full`,state:{activity:t?`thinking`:e?`speaking`:`idle`,expression:`normal`}}),title:Ze?`Shiitake isn't ready yet`:`Welcome to Grove`,description:Ze?`Your first Agent couldn't be set up. Try again, or check your Team's credit.`:`Let Grove find your AI helpers, create new ones, and open conversations. Your Team controls this access.`,actions:Ze?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(U,{loading:kt,onClick:()=>{f.refetch()},children:`Retry`}),(0,Q.jsx)(U,{variant:`outline`,onClick:()=>void t.ui.openTeamBilling(),children:`Open billing`})]}):(0,Q.jsx)(U,{onClick:nt,children:`Allow Agent access`})}):jt??(0,Q.jsx)(mt,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`panel`,title:st>0?`Pick up a conversation`:et?`Say hello to ${iD(et)}`:`No conversations yet`,description:st>0?`${ct?`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,Q.jsxs)(Q.Fragment,{children:[R||st===0?null:(0,Q.jsx)(U,{variant:`outline`,"aria-haspopup":`dialog`,"aria-controls":`grove-nav`,"aria-expanded":oe,onClick:ot,children:`Agents and conversations`}),tt?(0,Q.jsx)(U,{variant:`outline`,loading:w===et.agentId,disabled:w!==null,onClick:()=>void Fe(et.agentId),children:st>0?`Ask ${iD(et)} something`:`Start a conversation`}):null]})})]}),we===null?null:(0,Q.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,Q.jsx)(CL,{open:we,connection:t,commands:Ee,renderConversation:r.renderConversation,composeDraft:null,onPrefilled:()=>void 0,onForked:e=>{De?.select(we.agentId,e)},onOpen:Oe,models:ye?.setup?.models,label:`Beside conversation`})})]})}var kL=[{label:`Set me up`,prompt:`I'm new here. Set yourself up for me: ask me at most three quick questions about what I want to use you for, show me a short plan, and wait for my OK before you change anything. Save what you learn about me in your AGENTS.md.`},{label:`Help me set up my Oyster`,prompt:`Help me set up my Oyster, Fungi running on my own machine. First ask what I'm installing it on (Mac, Linux, or a server). Then take me through the official install from docs.fungi.computer one step at a time. Give me one command, wait until I say it worked, then the next. Never guess a command. Finish by checking that my Oyster answers, and tell me what to do next.`},{label:`Make an image or video`,prompt:`I want to make an image or a short video. Ask me what it's for and offer three style options to pick from. Then make a quick first draft in Prints and show it to me. After that, ask what to change. Save the style I like in your AGENTS.md so you remember it.`},{label:`Work on my code`,prompt:`I want help with a code project. Ask for the repo link, or help me connect GitHub if it's private. Then clone it onto your Computer and read it: the README, build, test and CI files. Write an AGENTS.md for the project with the exact build and test commands, then tell me the three most useful things you learned and suggest one small first task.`}];function AL(e,t){return{appId:e.appId,intent:{kind:`navigate`,params:t}}}function jL(e){return[{key:`agent`,value:e.agentId},{key:`session`,value:e.sessionId}]}var ML={state:fT,error:null},NL=()=>()=>void 0;function PL(e){let t=gh(e.connection)?.openRequest??null,n=t?.kind===`navigate`?t.params.find(e=>e.key===`gill`)?.value:void 0,[r,i]=(0,X.useState)(null);return(0,X.useEffect)(()=>{n!==void 0&&i(n)},[n]),(r??n)===`chat`?(0,Q.jsx)(FL,{...e}):(0,Q.jsx)(EL,{connection:e.connection,...e.services===void 0?{}:{services:e.services}})}function FL(e){return(0,Q.jsx)(BL,{...e},JSON.stringify(wy.of(e.connection)))}var IL=260;function LL(e){let t=(0,X.useRef)(null),[n,r]=(0,X.useState)(!1);return(0,X.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 RL({agent:e}){let t=ni(),[n,r]=LL(IL),i=e===void 0?`your Agent`:iD(e);return(0,Q.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,Q.jsx)(Xr,{avatar:e.avatar,className:`chat-gill-hero`,name:i,size:72}),(0,Q.jsxs)(`h2`,{className:`text-lg font-semibold text-base-content`,children:[`Hi, I’m `,i,`. What brings you here?`]}),(0,Q.jsx)(`div`,{"aria-label":`What brings you here?`,className:`flex flex-wrap justify-center gap-sm`,role:`group`,children:kL.map(({label:e,prompt:n})=>(0,Q.jsx)(U,{size:`sm`,variant:`outline`,onClick:()=>{t.setDraft(n),t.send()},children:e},e))})]})}function zL({agent:e,connection:t}){let n=e===void 0?`your Agent`:iD(e),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),s=async()=>{o(!1),i(!0);try{o(await t.ui.openSetup(`model`)!==`opened`)}catch(e){console.error(`Grove chat widget could not open model setup`,e),o(!0)}finally{i(!1)}};return(0,Q.jsxs)(`div`,{className:`chat-gill-connect m-auto flex min-h-0 max-w-[24rem] flex-col items-center gap-md overflow-y-auto px-md py-sm text-center`,"data-chat-gill-connect-model":!0,children:[e===void 0?null:(0,Q.jsx)(Xr,{avatar:e.avatar,className:`chat-gill-hero`,name:n,size:72}),(0,Q.jsxs)(`h2`,{className:`text-lg font-semibold text-base-content`,children:[`Connect a model so `,n,` can reply`]}),(0,Q.jsx)(`p`,{className:`text-sm text-dim`,children:`Use Cloudflare Workers AI, or a key from your own model provider. Your key stays on this Oyster.`}),(0,Q.jsx)(U,{disabled:r,onClick:()=>{s()},children:r?`Opening Model keys…`:`Add a model key`}),a?(0,Q.jsx)(Sr,{role:`alert`,message:`Model keys could not open. Try opening them again.`,onRetry:()=>{s()},onDismiss:()=>{o(!1)}}):null]})}function BL({connection:e,services:t=vL,credit:n,openFunding:r}){let i=Xt(),a=gh(e),o=a?.setup?.models===`missing`,{directory:s,inbox:c}=CI(e),l=hL(e,t),u=(0,X.useMemo)(()=>lr(),[]),d=s.data??[],f=d.find(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)),p=e?.capabilities.has(rg)??!1,m=e?.capabilities.has(Bh)??!1,h=(0,X.useMemo)(()=>e===null?null:ST({connection:e,queryClient:i,services:t}),[e,i,t]);(0,X.useEffect)(()=>()=>{h?.close()},[h]);let g=(0,X.useSyncExternalStore)(h?.subscribe??NL,h?.snapshot??(()=>ML)),_=bT(g.state),v=xT(g.state),y=g.state.creating!==null,[b,x]=(0,X.useState)(!1),S=(0,X.useMemo)(()=>{if(f===void 0)return;let e=new Set(l.rows.map(e=>`${e.agentId}:${e.conversation.sessionId}`)),t=eD(d,c.items.filter(t=>!(`kind`in t)&&!e.has(`${t.agentId}:${t.sessionId}`)),f.agentId);return[...t.active,...t.settled].sort((e,t)=>t.lastActivityAt-e.lastActivityAt).at(0)},[f,d,c.items,l.rows]),C=(0,X.useCallback)(async n=>{if(!e||!h||f===void 0)return;let r=h.create(n);if(!(!r.accepted||r.ticket===null)){x(!1);try{let i=()=>xL.request.generate(),a=n===`auto`&&e.capabilities.has(ob)?await SI(e.capabilities.require(ob),i):i(),o=await SL(e,f.agentId,t,e=>e.createSession(a));h.created(r.ticket,{agentId:f.agentId,sessionId:o}),c.refresh()}catch(t){h.createFailed(r.ticket),console.error(`Grove chat widget could not start a conversation`,t),x(!0),Pi(e.ui,{variant:`error`,message:`The conversation could not be started. Try again.`})}}},[f,e,c.refresh,t,h]),w=(0,X.useRef)(null),T=e!==null&&!s.isPending&&c.status!==`loading`&&c.status!==`error`&&!l.loading;(0,X.useEffect)(()=>{!T||!h||f===void 0||!p||o||g.state.view.kind!==`none`||y||w.current!==f.agentId&&(w.current=f.agentId,S===void 0?C(`auto`):h.select({agentId:f.agentId,sessionId:S.sessionId},`host`))},[f,p,y,S,o,T,g.state.view.kind,C,h]);let E=(0,X.useCallback)(t=>{e&&(async()=>{try{await e.capabilities.require(jy).open(AL(e.identity,t))}catch(t){console.error(`Grove chat widget could not open Grove`,t),Pi(e.ui,{variant:`error`,message:`Grove could not be opened. Try again.`})}})()},[e]),D=e?.capabilities.has(jy)??!1,O=(0,X.useCallback)(e=>{!_||!h||(h.select({agentId:_.agentId,sessionId:e}),c.refresh())},[c.refresh,_,h]),k=(_===null?void 0:d.find(e=>e.agentId===_.agentId))??f,A=o&&e!==null&&f!==void 0&&p,j;return j=_?null:!e||s.isPending||v!==null||y?(0,Q.jsx)(CT,{agent:f,message:e?`Getting ready…`:`Connecting…`}):d.length===0&&m?(0,Q.jsxs)(`div`,{className:`m-auto flex max-w-[24rem] flex-col items-center gap-sm px-md text-center`,children:[(0,Q.jsx)(`p`,{className:`text-sm font-semibold`,children:`Shiitake isn’t ready yet`}),(0,Q.jsx)(`p`,{className:`text-sm text-dim`,children:`Your first Agent couldn’t be set up. Try again, or check your Team’s credit.`}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-sm`,children:[(0,Q.jsx)(U,{loading:s.isFetching,size:`sm`,onClick:()=>{s.refetch()},children:`Try again`}),(0,Q.jsx)(U,{size:`sm`,variant:`outline`,onClick:()=>{e.ui.openTeamBilling().catch(e=>{console.error(`Grove chat widget could not open billing`,e)})},children:`Open billing`})]})]}):f===void 0||!p?(0,Q.jsxs)(`div`,{className:`m-auto flex max-w-[24rem] flex-col items-center gap-sm px-md text-center`,children:[(0,Q.jsx)(`p`,{className:`text-sm text-dim`,children:`Allow Grove to chat with your Agent here.`}),(0,Q.jsx)(U,{size:`sm`,onClick:()=>{e.ui.requestAppPermissions({agents:yL}).catch(e=>{console.error(`Grove chat widget permission request failed`,e)})},children:`Allow Agent access`})]}):(0,Q.jsxs)(`div`,{className:`m-auto flex flex-col items-center gap-sm`,children:[(0,Q.jsx)(`p`,{className:`text-sm text-dim`,children:b||g.error!==null?`The conversation could not be started.`:`No conversation is open.`}),(0,Q.jsx)(U,{variant:`outline`,onClick:()=>{C(`person`)},children:`Start a conversation`})]}),(0,Q.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-chat-gill":!0,children:[(0,Q.jsxs)(`header`,{className:`flex flex-none items-center gap-sm border-b border-base-300 px-md py-xs`,children:[k===void 0?null:(0,Q.jsx)(Xr,{avatar:k.avatar,name:iD(k),size:20}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-semibold`,children:k===void 0?`Grove`:iD(k)}),(0,Q.jsx)(U,{disabled:!D,size:`xs`,variant:`ghost`,onClick:()=>{E(_===null?[]:jL(_))},children:`Open in Grove`}),(0,Q.jsxs)(fw,{children:[(0,Q.jsx)(mw,{render:(0,Q.jsx)(wi,{"aria-label":`Conversation options`,icon:(0,Q.jsx)(Xw,{}),size:`sm`})}),(0,Q.jsx)(vw,{align:`end`,children:(0,Q.jsx)(bw,{disabled:f===void 0||!p||y,onSelect:()=>{C(`person`)},children:`New conversation`})})]})]}),(0,Q.jsx)(`section`,{"aria-label":`Conversation`,className:`flex min-h-0 min-w-0 flex-1 flex-col`,children:A?(0,Q.jsx)(zL,{agent:k,connection:e}):_?(0,Q.jsx)(CL,{commands:u,composeDraft:null,connection:e,empty:(0,Q.jsx)(RL,{agent:k}),label:`Chat`,loadingAgent:k,models:a?.setup?.models,onForked:O,onOpen:e=>{E(e.params)},onPrefilled:()=>void 0,open:_,opening:v!==null,renderConversation:t.renderConversation},`${_.agentId}:${_.sessionId}`):j}),n===void 0?null:(0,Q.jsxs)(`p`,{className:`flex-none px-md pb-sm text-center text-xs text-dim`,"data-chat-gill-footer":!0,children:[`Credit: `,(0,Q.jsx)(`strong`,{className:`font-semibold`,children:n}),` · `,r===void 0?`Start Pro`:(0,Q.jsx)(U,{className:`align-baseline`,size:`xs`,variant:`link`,onClick:r,children:`Start Pro`})]})]})}var VL=document.getElementById(`inbox-root`);if(!VL)throw Error(`Inbox root is missing`);ph(VL,{name:`Grove`,queryClient:Ey()},({app:e})=>(0,X.createElement)(PL,{connection:e}));export{Ch as a,xh as c,wy as i,rs as l,JA as n,Sh as o,My as r,wh as s,ZA as t};