@fungi.computer/inkcap 0.3.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{FileTab-BIzFBzDK.js → FileTab-ZK1QFAd5.js} +25 -25
- package/dist/assets/InkcapFileTree-DTYIjm_0.js +1 -0
- package/dist/assets/InkcapRepositoryApp-q1CrI-Kd.js +1 -0
- package/dist/assets/empty-state-BPRNo51e.js +1 -0
- package/dist/assets/index-B5ZsAojZ.js +2 -0
- package/dist/assets/index-dbf7RxFf.css +2 -0
- package/dist/assets/refresh-cw-xZ5ayQTq.js +1 -0
- package/dist/assets/{dialog-C49TyOKM.js → tree-path-B5mQdKbM.js} +3 -2
- package/dist/assets/{useFileTree-Dyiqmbq-.js → useFileTree-grDspEh1.js} +1 -1
- package/dist/assets/useForm-DF2JFOTS.js +1 -0
- package/dist/index.html +4 -4
- package/package.json +8 -7
- package/dist/assets/InkcapFileTree-WCY0DAx7.js +0 -1
- package/dist/assets/InkcapRepositoryApp-C74ueO0p.js +0 -1
- package/dist/assets/index-BfmirAP5.css +0 -2
- package/dist/assets/index-D89bIeb6.js +0 -2
- package/dist/assets/refresh-cw-LAlYuFfb.js +0 -1
- package/dist/assets/tree-path-BjPaqwnl.js +0 -1
- package/dist/assets/useForm-LW3qRsbm.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$r as t,Bn as n,Fi as r,Gi as i,Gr as a,Hi as o,Hr as s,Ir as c,Jr as l,Ki as u,Kr as d,Ln as ee,Lr as te,Pi as ne,Qi as re,Qr as ie,Rr as f,Ui as ae,Ur as p,Vn as oe,Vr as m,Wi as se,Wr as ce,Xi as le,Yr as h,Zr as ue,_i as g,ai as de,ar as fe,br as _,ci as pe,di as me,dr as v,ei as y,fi as he,fr as b,gi as ge,gr as _e,hi as ve,hr as ye,ii as be,ir as xe,lr as Se,mi as x,mr as S,ni as C,oi as w,or as T,pi as E,pr as Ce,qi as we,rr as Te,si as Ee,sr as De,ui as Oe,ur as ke,vi as D,vr as O,xr as Ae,yi as k,yr as je,zr as A}from"./dialog-C49TyOKM.js";var Me=new WeakMap,Ne=`~effect/Redacted`,Pe=e=>we(e,Ne),Fe=(e,t)=>{let n=Object.create(Ie);return t?.label&&(n.label=t.label),Me.set(n,e),n},Ie={[Ne]:{_A:e=>e},label:void 0,...o,toJSON(){return this.toString()},toString(){return`<redacted${le(this.label)?`:`+this.label:``}>`},[u](){return i(Me.get(this))},[se](e){return Pe(e)&&ae(Me.get(this),Me.get(e))}},j=e(te(),1),Le=c(),Re=j.createContext(void 0),ze=e=>{let t=j.useContext(Re);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Be=({client:e,children:t})=>(j.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Le.jsx)(Re.Provider,{value:e,children:t})),Ve={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},He=new class{#e=Ve;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function Ue(e){setTimeout(e,0)}var We=typeof window>`u`||`Deno`in globalThis;function M(){}function Ge(e,t){return typeof e==`function`?e(t):e}function Ke(e){return typeof e==`number`&&e>=0&&e!==1/0}function qe(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Je(e,t){return typeof e==`function`?e(t):e}function Ye(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Ze(o,t.options))return!1}else if(!$e(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function Xe(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Qe(t.options.mutationKey)!==Qe(a))return!1}else if(!$e(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ze(e,t){return(t?.queryKeyHashFn||Qe)(e)}function Qe(e){return JSON.stringify(e,(e,t)=>it(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function $e(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n<t.length;n++)if(!$e(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!$e(e[r],t[r]))return!1;return!0}return!1}var et=Object.prototype.hasOwnProperty;function tt(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=rt(e)&&rt(t);if(!r&&!(it(e)&&it(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:et.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let ee=tt(u,d,n+1);s[o]=ee,ee===u&&c++}return i===o&&c===i?e:s}function nt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function rt(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function it(e){if(!at(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!at(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function at(e){return Object.prototype.toString.call(e)===`[object Object]`}function ot(e){return new Promise(t=>{He.setTimeout(t,e)})}function st(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:tt(e,t)}function ct(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function lt(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ut=Symbol();function dt(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ut?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ft(e,t){return typeof e==`function`?e(...t):!!e}function pt(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var mt=()=>We,ht=()=>mt(),gt=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},_t=new class extends gt{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},vt=Ue;function yt(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=vt,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var N=yt(),bt=new class extends gt{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function xt(e){return Math.min(1e3*2**e,3e4)}function St(e){return(e??`online`)!==`online`||bt.isOnline()}var Ct=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function wt(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(M);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Ct(t);re(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},ee=()=>_t.isFocused()&&(e.networkMode===`always`||bt.isOnline())&&e.canRun(),te=()=>St(e.networkMode)&&e.canRun(),ne=e=>{c()||(r?.(),i=`resolved`,a(e))},re=e=>{c()||(r?.(),i=`rejected`,o(e))},ie=()=>new Promise(t=>{r=e=>{(c()||ee())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),f=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(ne).catch(r=>{if(c())return;let i=e.retry??(ht()?0:3),a=e.retryDelay??xt,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!s){re(r);return}n++,e.onFail?.(n,r),ot(o).then(()=>ee()?void 0:ie()).then(()=>{t?re(r):f()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:te,start:()=>(te()?f():ie().then(f),s)}}var Tt=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ke(this.gcTime)&&(this.#e=He.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ht()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(He.clearTimeout(this.#e),this.#e=void 0)}};function Et(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{pt(e,()=>t.signal,()=>n=!0)},u=dt(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?lt:ct;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Ot:Dt,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:Dt(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Dt(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Ot(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var kt=class extends Tt{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Mt(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Mt(this.options);e.data!==void 0&&(this.setState(jt(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=st(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(M).catch(M):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Je(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ut||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Je(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!qe(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=dt(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Et(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=wt({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Ct&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Ct){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...At(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...jt(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),N.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function At(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:St(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function jt(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Mt(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Nt=class extends Tt{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Pt(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=wt({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),N.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Pt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Ft=class extends gt{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Nt({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=It(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=It(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=It(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=It(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){N.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>Xe(t,e))}findAll(e={}){return this.getAll().filter(t=>Xe(e,t))}notify(e){N.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return N.batch(()=>Promise.all(e.map(e=>e.continue().catch(M))))}};function It(e){return e.options.scope?.id}var Lt=class extends gt{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??Ze(r,t),a=this.get(i);return a||(a=new kt({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){N.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>Ye(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>Ye(e,t)):t}notify(e){N.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){N.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){N.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Rt=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Lt,this.#t=e.mutationCache||new Ft,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=_t.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=bt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Je(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=Ge(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return N.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;N.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return N.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=N.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(M).catch(M)}invalidateQueries(e,t={}){return N.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=N.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(M)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(M)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(Je(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(Je(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(M).catch(M)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(M).catch(M)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return bt.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(Qe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{$e(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(Qe(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{$e(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=Ze(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===ut&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};function zt(e){return e}var Bt=ke(),Vt=v(()=>Se(`status`,[S({status:b(`available`)}).strict(),S({status:b(`unavailable`),reason:O()}).strict()])),Ht=Bt,Ut=v(()=>_e(O(),Ht)),Wt=e=>Ht.parse(e),Gt=v(()=>S({code:O().min(1).max(160),message:O().min(1).max(512),details:Ht.optional()}).strict()),Kt=e=>Gt.parse(e),qt=Ut,P=v(()=>O().refine(e=>e.trim().length>0)),Jt=Vt,Yt=v(()=>je([S({type:b(`action`)}).strict(),S({type:b(`custom`),data:Ut}).strict(),S({type:b(`choice`),options:T(S({value:Ht,label:P,description:P.optional()}))}).strict(),S({type:b(`form`),submitLabel:P.optional()}).strict(),S({type:b(`confirmation`),message:P,confirmLabel:P.optional(),cancelLabel:P.optional()}).strict()])),Xt=v(()=>S({inputSchema:qt.optional(),outputSchema:qt.optional(),presentation:Yt.optional()}).strict()),Zt=v(()=>Ce().int().refine(e=>Number.isSafeInteger(e))),Qt=v(()=>S({hint:P.pipe(O().max(120)),words:T(S({word:O().regex(/^\S{1,64}$/u),description:P.pipe(O().max(512)).optional(),arguments:Ut}).strict()).max(32).optional(),text:S({field:P.pipe(O().max(120)),arguments:Ut,requestIdField:P.pipe(O().max(120)).optional()}).strict().optional()}).strict().refine(e=>e.words!==void 0||e.text!==void 0,`slash arguments need words or text`)),$t=v(()=>S({order:Zt.optional()}).strict()),en=v(()=>S({bindings:S({order:Zt.optional(),values:T(P).max(16)}).strict().optional(),agent:S({keybind:P.optional(),order:Zt.optional()}).strict().optional(),help:$t.optional(),menu:$t.optional(),palette:$t.optional(),slash:S({aliases:T(P).max(16),consumesDraft:De().optional(),order:Zt.optional(),arguments:Qt.optional()}).strict().optional()}).strict()),tn=v(()=>S({id:P.refine(e=>!e.includes(`:`)),title:P,category:P,description:P.optional(),projections:en.optional(),action:Xt.optional(),availability:Jt.optional()}).strict()),nn=e=>tn.parse(e),rn=v(()=>S({inputSchema:qt.optional(),outputSchema:qt.optional()}).strict()),an=O().min(1).brand(),on=v(()=>S({commandId:an,command:S({namespace:O(),id:O()}).strict(),sourceId:O(),scope:O().optional(),title:O(),category:O(),description:O().optional(),order:Ce(),availability:Vt,action:rn.optional(),keybind:O().optional()}).strict());T(on);var sn=8192,F=P.pipe(O().max(sn)),cn=P.pipe(O().max(60)),ln=Ae({protocol:/^https?$/u}),un=S({label:F,value:F}).strict(),dn={summary:F.optional(),facts:T(un).max(4).optional(),body:F.optional(),bodyLabel:F.optional(),details:T(un).max(24).optional()};Se(`type`,[S({type:b(`choice`),message:cn,...dn,current:F.optional(),collapsedGroup:F.optional(),options:T(S({value:F,label:F,description:F.optional(),group:F.optional(),destructive:b(!0).optional()}).strict()).min(1).max(256)}).strict(),S({type:b(`text`),message:cn,...dn,placeholder:F.optional(),secret:De().optional()}).strict(),S({type:b(`confirmation`),message:cn,...dn,confirmLabel:F.optional(),cancelLabel:F.optional(),destructive:b(!0).optional()}).strict(),S({type:b(`decision`),message:cn,...dn,options:T(S({value:F,label:F,description:F.optional(),destructive:b(!0).optional()}).strict()).min(1).max(8).refine(e=>new Set(e.map(e=>e.value)).size===e.length,`Decision option values must be unique`),multiple:De().optional(),other:S({label:F,placeholder:F.optional(),maxLength:Ce().int().min(1).max(sn),blank:F.optional()}).strict().optional(),escape:F.optional()}).strict().refine(e=>[e.escape,e.other?.blank].every(t=>t===void 0||e.options.some(e=>e.value===t)),`A decision's escape and blank answers must be offered options`)]),v(()=>Se(`type`,[S({type:b(`info`),message:F,links:T(S({url:ln,label:F.optional()}).strict()).max(16).optional()}).strict(),S({type:b(`progress`),message:F}).strict(),S({type:b(`handoff`),url:ln,code:F.optional(),message:F.optional()}).strict(),S({type:b(`success`),message:F}).strict()]));var fn=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name=`WhistleActionError`}},pn=class extends Error{constructor(){super(`Whistle runtime is closed`),this.name=`WhistleClosedError`}};function mn(){let e=!1,t=Gn,n=[],r=[],i=!1,a=[],o=new Set,s=()=>{for(let e of o)e()};return Object.freeze({close:()=>{e||(e=!0,n=[],a=[],r=[],t=Gn,s(),o.clear())},contribute:t=>{if(Cn(t),e)throw new pn;wn(t,n),Tn(t,n);let r=Symbol(`whistle-contribution`);Sn(t)||(n=[...n,{contribution:En(t),generation:r}],i=!0,s());let a=!0;return Wn(o=>{if(!a||e)return;let c={...t,commands:o};Cn(c);let l=n.findIndex(e=>e.generation===r),u=n.filter(e=>e.generation!==r);wn(c,u),Tn(c,u);let d=En(c);if(Sn(c)){if(l<0)return;n=u}else n=l<0?[...n,{contribution:d,generation:r}]:n.map(e=>e.generation===r?{contribution:d,generation:r}:e);i=!0,s()},()=>{a&&(a=!1,n.find(e=>e.generation===r)!==void 0&&(n=n.filter(e=>e.generation!==r),i=!0,s()))})},execute:async(t,r)=>{if(t.namespace.trim().length===0||t.id.trim().length===0)return{status:`invalid`};if(e)return{status:`closed`};let i=xn(t,n);if(i===void 0)return{status:`missing`};let o;try{let e=qn(i);if(e.status===`unavailable`)return e;let n=a.at(-1)?.presenter;r.interaction===void 0&&n!==void 0&&hn.has(r.origin)&&(o=n({commandId:bn(t.namespace,t.id),title:i.title}));let s={...r,signal:r.signal??new AbortController().signal};o!==void 0&&(s.interaction=o.interaction,s.signal=AbortSignal.any([s.signal,o.interaction.signal]));let c=await i.handler(s);return o?.settle({status:`handled`}),c===void 0?{status:`handled`}:{status:`handled`,result:c}}catch(e){let t=Yn(e instanceof Error?e:Error(`Command handler threw a non-Error value`));return o?.settle(o.interaction.signal.aborted?{status:`cancelled`}:{status:`failed`,message:t.message}),{status:`failed`,error:t}}},present:t=>{let n={presenter:t};return e||(a=[...a,n]),()=>{a=a.filter(e=>e!==n)}},snapshot:()=>{if(e)return Gn;let a=n.flatMap(e=>e.contribution.commands.map(qn));return(i||a.some((e,t)=>!Jn(e,r[t])))&&(t=Xn(n,a),r=a,i=!1),t},subscribe:t=>e?()=>void 0:(o.add(t),()=>{o.delete(t)})})}var hn=new Set([`browser`,`keyboard`,`menu`,`palette`,`slash`,`terminal`]),gn=16,_n=32,vn=64,yn=256;function bn(e,t){return an.parse(`${e}:${t}`)}function xn(e,t){for(let n of t)if(n.contribution.namespace===e.namespace){for(let t of n.contribution.commands)if(t.id===e.id)return t}}function Sn(e){return e.commands.length===0}function Cn(e){I(e.sourceId,`source ID`),I(e.namespace,`namespace`),e.scope!==void 0&&I(e.scope,`scope`);for(let t of e.commands)Rn(t)}function wn(e,t){t.find(t=>t.contribution.namespace===e.namespace&&t.contribution.sourceId!==e.sourceId)!==void 0&&L(`Namespace is already owned by another source`);let n=new Set,r=new Set;for(let i of t){let t=i.contribution.scope===e.scope;for(let e of i.contribution.commands)if(n.add(bn(i.contribution.namespace,e.id)),t)for(let t of e.projections?.slash?.aliases??[])r.add(t)}for(let t of e.commands){let i=bn(e.namespace,t.id);n.has(i)&&L(`Canonical command ID is already registered`),n.add(i);for(let e of t.projections?.slash?.aliases??[])r.has(e)&&L(`Slash alias is already registered`),r.add(e)}}function Tn(e,t){t.length>=vn&&L(`Live contribution capacity exceeded`),t.reduce((e,t)=>e+t.contribution.commands.length,0)+e.commands.length>yn&&L(`Live command capacity exceeded`)}function En(e){let t={sourceId:e.sourceId,namespace:e.namespace,commands:e.commands.map(Dn)};return e.scope===void 0?t:{...t,scope:e.scope}}function Dn(e){let t={id:e.id,title:e.title,category:e.category,handler:e.handler};return e.description!==void 0&&(t.description=e.description),e.action!==void 0&&(t.action=On(e.action)),e.availability!==void 0&&(t.availability=e.availability),e.projections!==void 0&&(t.projections=Mn(e.projections)),t}function On(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=kn(e.inputSchema)),e.outputSchema!==void 0&&(t.outputSchema=kn(e.outputSchema)),e.presentation!==void 0&&(t.presentation=jn(e.presentation)),Object.freeze(t)}function kn(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,An(t)])))}function An(e){return Array.isArray(e)?Object.freeze(e.map(An)):e!==null&&e instanceof Object?Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,An(t)]))):e}function jn(e){switch(e.type){case`action`:return Object.freeze({type:`action`});case`custom`:return Object.freeze({type:`custom`,data:kn(e.data)});case`choice`:return Object.freeze({type:`choice`,options:Object.freeze(e.options.map(e=>Object.freeze({...e,value:An(e.value)})))});case`form`:return Object.freeze({...e});case`confirmation`:return Object.freeze({...e})}}function Mn(e){let t={};return e.bindings!==void 0&&(t.bindings=Nn(e.bindings)),e.agent!==void 0&&(t.agent=Pn(e.agent)),e.help!==void 0&&(t.help=Fn(e.help.order)),e.menu!==void 0&&(t.menu=Fn(e.menu.order)),e.palette!==void 0&&(t.palette=Fn(e.palette.order)),e.slash!==void 0&&(t.slash=In(e.slash)),t}function Nn(e){let t={values:[...e.values]};return e.order!==void 0&&(t.order=e.order),t}function Pn(e){let t={};return e.keybind!==void 0&&(t.keybind=e.keybind),e.order!==void 0&&(t.order=e.order),t}function Fn(e){let t={};return e!==void 0&&(t.order=e),t}function In(e){let t={aliases:[...e.aliases]};return e.order!==void 0&&(t.order=e.order),e.consumesDraft!==void 0&&(t.consumesDraft=e.consumesDraft),e.arguments!==void 0&&(t.arguments=Ln(e.arguments)),t}function Ln(e){let t={hint:e.hint};return e.words!==void 0&&(t.words=Object.freeze(e.words.map(e=>Object.freeze({...e,arguments:kn(e.arguments)})))),e.text!==void 0&&(t.text=Object.freeze({...e.text,arguments:kn(e.text.arguments)})),Object.freeze(t)}function Rn(e){I(e.id,`command ID`,!0),I(e.title,`title`),I(e.category,`category`),zn(e.action),Bn(e.projections)}function zn(e){if(e?.presentation!==void 0)switch(e.presentation.type){case`action`:case`custom`:return;case`choice`:for(let t of e.presentation.options)I(t.label,`choice label`),t.description!==void 0&&I(t.description,`choice description`);return;case`form`:e.presentation.submitLabel!==void 0&&I(e.presentation.submitLabel,`submit label`);return;case`confirmation`:I(e.presentation.message,`confirmation message`),e.presentation.confirmLabel!==void 0&&I(e.presentation.confirmLabel,`confirmation label`),e.presentation.cancelLabel!==void 0&&I(e.presentation.cancelLabel,`cancellation label`)}}function Bn(e){if(e!==void 0){for(let t of[e.bindings,e.palette,e.slash,e.help,e.menu,e.agent])t!==void 0&&Un(t.order);if(e.bindings!==void 0&&Hn(e.bindings.values,`binding`),e.slash!==void 0){Hn(e.slash.aliases,`slash alias`);for(let t of e.slash.aliases)/\s/u.test(t)&&L(`slash alias must not contain whitespace`);Vn(e.slash.arguments)}e.agent?.keybind!==void 0&&I(e.agent.keybind,`agent keybind`)}}function Vn(e){if(e===void 0)return;I(e.hint,`argument hint`),e.words===void 0&&e.text===void 0&&L(`slash arguments need words or text`);let t=new Set;for(let n of e.words??[])I(n.word,`argument word`),/\s/u.test(n.word)&&L(`argument word must not contain whitespace`),t.has(n.word)&&L(`argument word is repeated`),t.add(n.word),n.description!==void 0&&I(n.description,`argument word description`);t.size>_n&&L(`argument word count exceeds 32`),e.text!==void 0&&(I(e.text.field,`argument text field`),e.text.requestIdField!==void 0&&I(e.text.requestIdField,`request id field`))}function Hn(e,t){e.length>gn&&L(`${t} count exceeds 16`);for(let n of e)I(n,t)}function I(e,t,n=!1){e.trim().length===0&&L(`${t} must not be blank`),n&&e.includes(`:`)&&L(`${t} must not contain a colon`)}function Un(e){e!==void 0&&!Number.isSafeInteger(e)&&L(`order must be a safe integer`)}function Wn(e=()=>void 0,t=()=>void 0){return Object.freeze({update:e,dispose:t})}function L(e){throw Error(e)}var Gn=Object.freeze({bindings:Object.freeze([]),palette:Object.freeze([]),slash:Object.freeze([]),help:Object.freeze([]),menu:Object.freeze([]),agent:Object.freeze([])}),Kn=Object.freeze({status:`available`});function qn(e){let t=e.availability?.()??Kn;return t.status===`available`?Kn:Object.freeze({status:`unavailable`,reason:t.reason})}function Jn(e,t){return e.status===`available`?t?.status===`available`:t?.status===`unavailable`&&e.reason===t.reason}function Yn(e){if(e instanceof fn){let t={code:e.code,message:e.message};return Object.freeze(e.details===void 0?t:{...t,details:An(e.details)})}return Object.freeze({code:`command_failed`,message:e.message})}function Xn(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=0;for(let l of e){let e=l.contribution;for(let l of e.commands){let u=l.projections,d=t[c++]??Kn;if(u?.bindings!==void 0)for(let t of u.bindings.values)n.push({...rr(e,l,u.bindings.order,d),binding:t});if(u?.palette!==void 0&&r.push({...rr(e,l,u.palette.order,d)}),u?.slash!==void 0)for(let t of u.slash.aliases){let n={...rr(e,l,u.slash.order,d),alias:t};u.slash.consumesDraft!==void 0&&(n={...n,consumesDraft:u.slash.consumesDraft}),u.slash.arguments!==void 0&&(n={...n,arguments:u.slash.arguments}),i.push(n)}u?.help!==void 0&&a.push({...rr(e,l,u.help.order,d)}),u?.menu!==void 0&&o.push({...rr(e,l,u.menu.order,d)}),u?.agent!==void 0&&s.push(ar(e,l,u.agent,d))}}return er(n),tr(i),$n(r),$n(a),$n(o),$n(s),Object.freeze({bindings:nr(n),palette:nr(r),slash:nr(i),help:nr(a),menu:nr(o),agent:nr(s)})}var Zn=new TextEncoder;function Qn(e,t){let n=Zn.encode(e),r=Zn.encode(t),i=Math.min(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??0,i=r[e]??0;if(t!==i)return t<i?-1:1}return n.length<r.length?-1:+(n.length>r.length)}function $n(e){e.sort((e,t)=>e.order-t.order||Qn(e.commandId,t.commandId))}function er(e){e.sort((e,t)=>e.order-t.order||Qn(e.commandId,t.commandId)||Qn(e.binding,t.binding))}function tr(e){e.sort((e,t)=>e.order-t.order||Qn(e.commandId,t.commandId)||Qn(e.alias,t.alias))}function nr(e){return Object.freeze(e.map(e=>Object.freeze(e)))}function rr(e,t,n,r){let i=ir(e,t,n,r);return e.scope===void 0?i:{...i,scope:e.scope}}function ir(e,t,n,r){let i={commandId:bn(e.namespace,t.id),command:Object.freeze({namespace:e.namespace,id:t.id}),sourceId:e.sourceId,title:t.title,category:t.category,order:n??0,availability:r},a=t.description===void 0?i:{...i,description:t.description};return t.action===void 0?a:{...a,action:t.action}}function ar(e,t,n,r){let i=rr(e,t,n.order,r),a=i.action===void 0?i:{...i,action:or(i.action)};return n.keybind===void 0?a:{...a,keybind:n.keybind}}function or(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=e.inputSchema),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),Object.freeze(t)}function sr(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()};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:Wt(r)}).then(e=>{n?e():r.push(e)},e=>{console.warn(`App command ${i.id} was not registered`,e)})}return()=>{if(!n){n=!0;for(let e of r.splice(0))e()}}}function cr(e,t){console.error(JSON.stringify({source:`agar`,operation:e,failureKind:t instanceof Error?`Error`:`NonErrorThrown`}),Fe(t))}var lr=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 ur=globalThis[lr],dr=ur?ur.RpcTarget:class{},fr=async function(){}.constructor,pr=typeof Buffer<`u`?Buffer.prototype:void 0;function mr(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 fr.prototype:return`function`;case Array.prototype:return`array`;case Date.prototype:return`date`;case Uint8Array.prototype:case pr: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 H.prototype:return`stub`;case U.prototype:return`rpc-promise`;default:if(ur){if(t==ur.RpcStub.prototype||e instanceof ur.ServiceStub)return`rpc-target`;if(t==ur.RpcPromise.prototype||t==ur.RpcProperty.prototype)return`rpc-thenable`}return e instanceof dr?`rpc-target`:e instanceof Error?`error`:`unsupported`}}function hr(){throw Error(`RPC map() implementation was not loaded.`)}var gr={applyMap:hr,sendMap:hr};function _r(){throw Error(`Stream implementation was not loaded.`)}var R={createWritableStreamHook:_r,createWritableStreamFromHook:_r,createReadableStreamHook:_r},z=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}}},B=class extends z{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)}}},vr=new B(Error(`Attempted to use RPC stub after it has been disposed.`)),yr=(e,t,n)=>e.call(t,n);function br(e,t){let n=yr;yr=e;try{return t()}finally{yr=n}}var V=Symbol(`realStub`),xr={apply(e,t,n){let r=e.raw;return new U(yr(r.hook,r.pathIfPromise||[],W.fromAppParams(n)),[])},get(e,t,n){let r=e.raw;if(t===V)return r;if(t in U.prototype)return r[t];if(typeof t==`string`)return new U(r.hook,r.pathIfPromise?[...r.pathIfPromise,t]:[t]);if(t===Symbol.dispose&&(!r.pathIfPromise||r.pathIfPromise.length==0))return()=>{r.hook.dispose(),r.hook=vr}},has(e,t){let n=e.raw;return t===V?!0:t in U.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.`)}},H=class e extends dr{constructor(e,t){if(super(),!(e instanceof z)){let n=e;if(e=n instanceof dr||n instanceof Function?jr.create(n,void 0):new G(W.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,xr)}hook;pathIfPromise;dup(){let t=this[V];return t.pathIfPromise?new e(t.hook.get(t.pathIfPromise)):new e(t.hook.dup())}onRpcBroken(e){this[V].hook.onBroken(e)}map(e){let{hook:t,pathIfPromise:n}=this[V];return gr.sendMap(t,n||[],e)}toString(){return`[object RpcStub]`}},U=class extends H{constructor(e,t){if(e instanceof z)super(e,t??[]);else{if(t!==void 0)throw TypeError(`RpcPromise constructor expected one argument, received two.`);let n=mr(e);if(n===`rpc-promise`){let t=Er(e);if(t.pathIfPromise.length>0)super(t.hook,t.pathIfPromise);else{let e=t.hook;t.hook=vr,super(e,[])}}else if(n===`rpc-thenable`)super(jr.create(e,void 0),[]);else{let t=new Mr(Promise.resolve(e).then(e=>new G(W.fromAppReturn(e))));t.ignoreUnhandledRejections(),super(t,[])}}}then(e,t){return Dr(this).then(...arguments)}catch(e){return Dr(this).catch(...arguments)}finally(e){return Dr(this).finally(...arguments)}toString(){return`[object RpcPromise]`}};function Sr(e){let{hook:t,pathIfPromise:n}=e[V];return n&&n.length>0?t.get(n):t}function Cr(e){let{hook:t,pathIfPromise:n}=e[V];return n?t.get(n):t.dup()}function wr(e){let{hook:t,pathIfPromise:n}=e[V];if(!(n&&n.length>0))return t}function Tr(e){return e[V].hook}function Er(e){return e[V]}async function Dr(e){let{hook:t,pathIfPromise:n}=e[V];return n.length>0&&(t=t.get(n)),(await t.pull()).deliverResolve()}var W=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 jr.create(e,t)}if(this.source===`return`){let r=this.rpcTargets?.get(e);return r?n?r.dup():(this.rpcTargets?.delete(e),r):(r=jr.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 R.createWritableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=R.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 R.createReadableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=R.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(mr(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?Cr(t):Sr(t),t instanceof U){let e=new U(a,[]);return this.promises.push({parent:r,property:n,promise:e}),e}return this.hooks.push(a),new H(a)}case`function`:case`rpc-target`:{let n=e,r;return r=a?a.getHookForRpcTarget(n,t,i):jr.create(n,t),this.hooks.push(r),new H(r)}case`rpc-thenable`:{let o=e,s;return s=a?new U(a.getHookForRpcTarget(o,t,i),[]):new U(jr.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):R.createWritableStreamHook(n),this.hooks.push(r),n}case`readable`:{let n=e,r;return r=a?a.getHookForReadableStream(n,t,i):R.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 U)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=wr(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 U?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(mr(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=wr(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)):Ar(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=R.createWritableStreamHook(t),n.dispose();return}case`readable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=R.createReadableStreamHook(t),n.dispose();return}default:return}}ignoreUnhandledRejections(){this.hooks?(this.hooks.forEach(e=>{e.ignoreUnhandledRejections()}),this.promises.forEach(e=>Tr(e.promise).ignoreUnhandledRejections())):this.ignoreUnhandledRejectionsImpl(this.value)}ignoreUnhandledRejectionsImpl(e){switch(mr(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`:Tr(e).ignoreUnhandledRejections();return;case`rpc-thenable`:e.then(e=>{},e=>{});return;default:return}}};function Or(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(mr(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}=Er(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 U){let{hook:t,pathIfPromise:n}=Er(e);return{hook:t,remainingPath:n||[]}}return{value:e,parent:t,owner:r}}var kr=class extends z{call(e,t){let n;try{let{value:t,owner:r}=this.getValue();n=Or(t,void 0,e,r)}catch(e){return t.dispose(),new B(e)}return n.hook?n.hook.call(n.remainingPath,t):typeof n.value==`function`?new Mr(t.deliverCall(n.value,n.parent).then(e=>new G(e))):(t.dispose(),new B(TypeError(`'${e.join(`.`)}' is not a function.`)))}map(e,t,n){try{let r;try{let{value:t,owner:n}=this.getValue();r=Or(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):gr.applyMap(r.value,r.parent,r.owner,t,n)}catch(e){return new B(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=Or(t,void 0,e,n);return r.hook?r.hook.get(r.remainingPath):new G(W.deepCopyFrom(r.value,r.parent,r.owner))}catch(e){return new B(e)}}},G=class e extends kr{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(W.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 H&&this.payload.value.onRpcBroken(e)}};function Ar(e){if(Symbol.dispose in e)try{e[Symbol.dispose]()}catch(e){Promise.reject(e)}}var jr=class e extends kr{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=>W.fromAppReturn(e)):Promise.reject(Error(`Tried to resolve a non-promise stub.`))}ignoreUnhandledRejections(){}dispose(){this.target&&=(this.refcount&&--this.refcount.count==0&&Ar(this.target),void 0)}onBroken(e){let t=this.target;t&&`then`in t&&Promise.resolve(t).then(()=>{},e)}},Mr=class e extends z{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)}},Nr={maxBigIntDigits:16384,maxDepth:256,maxMessageSize:33554432},Pr=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,Fr=[`ArrayBuffer`,`DataView`,`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`,`Float32Array`,`Float64Array`];function Ir(e){return Fr.includes(e)}var Lr={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},Rr={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},zr=new Map;for(let e of Object.keys(Rr))zr.set(Rr[e],e);function Br(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 Vr=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 Hr(e,t){let n=await new Response(e).blob();return n.type===t?n:n.slice(0,n.size,t)}var Ur={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError},K=class e{exporter;source;encodingLevel;constructor(e,t,n){this.exporter=e,this.source=t,this.encodingLevel=n}static devaluate(t,n,r=Vr,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(mr(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=zr.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=Lr[t];!Pr&&i&&(n=n.slice(),Br(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=R.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=R.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}=Er(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 Nr}};function Wr(e,t){return new U(new Mr(new Response(t).arrayBuffer().then(t=>{let n=new Uint8Array(t),r=new Request(e,{body:n});return new G(W.fromAppReturn(r))})),[])}function Gr(e,t){return new U(new Mr(Hr(e,t).then(e=>new G(W.fromAppReturn(e)))),[])}var Kr=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=W.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(!Ir(t[2])){let e=t[2].slice(0,64);throw TypeError(`Unknown bytes type marker: ${e}`)}let n=t[2],r=Lr[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(!Pr&&r!==void 0&&Br(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=Ur[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=Wr(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=Gr(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 U(e,[]);return this.promises.push({promise:t,parent:n,property:r}),t}return this.hooks.push(e),new U(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 U(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 U(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 H(e)}}break;case`writable`:if(typeof t[1]==`number`){let e=this.importer.importStub(t[1]),n=R.createWritableStreamFromHook(e);return this.hooks.push(e),n}break;case`readable`:if(typeof t[1]==`number`){let e=this.importer.getPipeReadable(t[1]),n=R.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}},qr=16,Jr=8,Yr=16,Xr=64;function Zr(e){return 2+e.length*3}function Qr(e,t,n=0){if(n>=Xr)return Jr;switch(typeof e){case`string`:return Zr(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 Yr+e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return Yr+e.size;if(e instanceof Date)return 16;if(t??=new WeakSet,t.has(e))return Jr;if(t.add(e),e instanceof Array){let r=qr;for(let i of e)r+=Jr+Qr(i,t,n+1);return r}if(e instanceof Error){let r=qr+Zr(e.name)+Zr(e.message)+Zr(e.stack??``);for(let i of Object.keys(e))r+=Jr+Zr(i)+Qr(e[i],t,n+1);return r}let r=qr;for(let i of Object.keys(e))r+=Jr+Zr(i)+Qr(e[i],t,n+1);return r}default:return 16}}var $r=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 B(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)}},ei=class e extends z{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)}},ti=class extends ei{session;constructor(e){super(!1,e),this.session=e.session}dispose(){if(this.session){let e=this.session;this.session=void 0,e.shutdown()}}},ni=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={...Nr,...n.limits},this.exports.push({hook:t,refcount:1}),this.imports.push(new $r(this,0,!1)),this.readLoop().catch(e=>this.abort(e))}getMainImport(){return new ti(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,K.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 H){let{hook:n,pathIfPromise:r}=Er(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=K.devaluate(t.value,void 0,this,t,this.encodingLevel);this.send([`resolve`,e,n]),r&&this.releaseExport(e,1)},t=>{this.send([`reject`,e,K.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}).catch(t=>{try{this.send([`reject`,e,K.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 ei&&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 $r(this,e,!1),this.imports[e]=t),new ei(!1,t)}importPromise(e){if(this.abortReason)throw this.abortReason;if(this.imports[e])return new B(Error(`Bug in RPC system: The peer sent a promise reusing an existing export ID.`));let t=new $r(this,e,!0);return this.imports[e]=t,new ei(!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 $r(this,n,!1);this.imports.push(r);let i=new ei(!1,r),a=R.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=K.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 $r(this,this.imports.length,!1);return this.imports.push(i),new ei(!0,i)}sendStream(e,t,n){if(this.abortReason)throw n.dispose(),this.abortReason;let r=[`pipeline`,e,t],i;try{i=K.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=Qr(a));let s=this.imports.length,c=new $r(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 $r(this,this.imports.length,!1);return this.imports.push(a),new ei(!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`,K.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 G(new Kr(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 G(new Kr(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=R.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 G(new Kr(this,this.encodingLevel).evaluate(n[2])));else{let e=new Kr(this,this.encodingLevel).evaluate(n[2]);e.dispose(),t.resolve(new B(e.value))}}else n[0]==`resolve`&&new Kr(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 Kr(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}},ri=class{#e;#t;constructor(e,t,n={}){let r;r=t?new G(W.fromAppReturn(t)):new B(Error(`This connection has no main object.`)),this.#e=new ni(e,r,n),this.#t=new H(this.#e.getMainImport())}getRemoteMain(){return this.#t}getStats(){return this.#e.getStats()}drain(){return this.#e.drain()}};function ii(e,t,n){return new ri(new ai(e),t,n).getRemoteMain()}var ai=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))}},oi,si=class{context;captureMap=new Map;instructions=[];constructor(e,t){this.context=oi?{parent:oi,captures:[],subject:oi.capture(e),path:t}:{parent:void 0,captures:[],subject:e,path:t},oi=this}unregister(){oi=this.context.parent}makeInput(){return new li(this,0)}makeOutput(e){let t;try{t=K.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 li(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=K.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 li(this,this.instructions.length)}pushGet(e,t){let n=this.capture(e.dup());return this.instructions.push([`pipeline`,n,t]),new li(this,this.instructions.length)}capture(e){if(e instanceof li&&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){}};gr.sendMap=(e,t,n)=>{let r=new si(e,t),i;try{i=W.fromAppReturn(br(r.pushCall.bind(r),()=>n(new U(r.makeInput(),[]))))}finally{r.unregister()}if(i instanceof Promise)throw i.catch(e=>{}),Error(`RPC map() callbacks cannot be async.`);return new U(r.makeOutput(i),[])};function ci(){throw Error(`Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.`)}var li=class extends z{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(oi)return oi.pushGet(this,e);ci()}call(e,t){t.dispose(),ci()}map(e,t,n){for(let e of t)e.dispose();ci()}pull(){ci()}ignoreUnhandledRejections(){}onBroken(e){ci()}},ui=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 Kr(this).evaluateCopy(t);if(e.value instanceof H){let t=wr(e.value);if(t){this.variables.push(t);continue}}this.variables.push(new G(e))}return new Kr(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 Nr}};function di(e,t,n,r,i){let a=new ui(r,new G(W.deepCopyFrom(e,t,n)));try{return a.apply(i)}finally{a.dispose()}}gr.applyMap=(e,t,n,r,i)=>{try{let a;if(e instanceof U)throw Error(`applyMap() can't be called on RpcPromise`);if(e instanceof Array){let t=[];try{for(let a of e)t.push(di(a,e,n,r,i))}catch(e){for(let e of t)e.dispose();throw e}a=W.fromArray(t)}else a=e==null?W.fromAppReturn(e):di(e,t,n,r,i);return new G(a)}finally{for(let e of r)e.dispose()}};var fi=class e extends z{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 Mr((r===`write`?t.deliverStreamWrite(n.writer):t.deliverCall(n.writer[r],n.writer)).then(e=>new G(e)))}catch(e){return t.dispose(),new B(e)}}map(e,t,n){for(let e of t)e.dispose();return new B(Error(`Cannot use map() on a WritableStream`))}get(e){return new B(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)}},pi=262144,mi=1073741824,hi=65536,gi=2,_i=1.25,vi=.9,yi=3,bi=class{now;window=pi;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?gi:_i,s=a*this.minRtt*o;s=Math.min(s,e.windowAtSend*o),s=e.windowFullAtSend?Math.max(s,e.windowAtSend*vi):Math.max(s,this.window),this.window=Math.max(Math.min(s,mi),hi),this.inStartupPhase&&e.sentTime>=this.roundStartTime&&(this.window>this.lastRoundWindow*_i?this.roundsWithoutIncrease=0:++this.roundsWithoutIncrease>=yi&&(this.inStartupPhase=!1),this.roundStartTime=t,this.lastRoundWindow=this.window)}return this.bytesInFlight<this.window}};function xi(e){let t,n=!1,r=new bi(()=>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=W.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`],W.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`],W.fromAppParams([n]));r.then(()=>o(),()=>o())}})}var Si=class e extends z{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 B(Error(`Cannot call methods on a ReadableStream stub`))}map(e,t,n){for(let e of t)e.dispose();return new B(Error(`Cannot use map() on a ReadableStream`))}get(e){return new B(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){}};R.createWritableStreamHook=fi.create,R.createWritableStreamFromHook=xi,R.createReadableStreamHook=Si.create;var Ci=H,wi=dr,Ti=ii;function Ei(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 Di(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,onActivate:()=>()=>void 0});function Oi(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}var ki=`fungi.app.ready`,Ai=`fungi.app.connect`,q=e=>l.pipe(C(ve(1)),C(x(e))),ji=e=>D(q(e)),Mi=d.pipe(C(E()),C(g(Number.isSafeInteger,{message:`Expected a safe integer`}))),Ni=Mi.pipe(C(he(0))),Pi=Mi.pipe(C(me(0))),Fi=h({appId:q(160),releaseId:q(160),surfaceId:q(160)}),Ii=h({editing:A,surface:t([q(160),ce])}),Li=t([h({kind:m(`compose`),requestId:q(160),text:q(2e3)}),h({kind:m(`navigate`),requestId:q(160),params:f(h({key:q(64),value:q(4096)})).pipe(C(x(16)))})]),Ri=h({computerId:t([q(256),ce]),teamHasComputers:D(a(A)),computerAccessGranted:D(A),focus:Ii,openRequest:t([ce,Li]),visibility:s([`visible`,`hidden`])}),zi=s([`connecting`,`connected`,`suspended`,`disconnected`,`disposing`,`disposed`]),Bi=h({altKey:A,ctrlKey:A,id:q(160),key:q(64),metaKey:A,shiftKey:A}),Vi=h({action:D(y),availability:D(y),category:q(160),description:ji(512),id:q(160),projections:D(y),title:q(160)}),Hi=h({arguments:D(y),commandId:q(321),origin:s([`agent`,`browser`,`keyboard`,`menu`,`palette`,`programmatic`,`slash`,`terminal`]),requestId:q(160)}),Ui=t([h({result:D(y),status:m(`handled`)}),h({error:y,status:m(`failed`)})]),Wi=e=>q(e).pipe(C(g(e=>{for(let t=0;t<e.length;t+=1)if(Ei(e.charCodeAt(t)))return!1;return!0},{message:`Expected one line of plain text`}))),Gi={id:q(64),text:Wi(80),end:k(A)},Ki=k(d.pipe(C(E()),C(Oe({minimum:0,maximum:9999})))),qi=f(t([h({...Gi,kind:m(`text`),tone:k(s([`neutral`,`success`,`warning`,`error`]))}),h({...Gi,kind:m(`button`),icon:k(s([`folder`,`ports`,`processes`,`access`])),count:Ki,tone:k(s([`neutral`,`success`,`warning`,`error`])),busy:k(A),title:k(Wi(1024)),disabled:k(A),opens:k(m(`dialog`)),expanded:k(A)}),h({...Gi,kind:m(`toggle`),pressed:A}),h({...Gi,kind:m(`menu`),count:Ki,title:k(Wi(1024)),options:f(h({id:q(64),text:Wi(80),checked:k(A),disabled:k(A)})).pipe(C(x(16)),C(g(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status option ids`})))})])).pipe(C(x(6)),C(g(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status item ids`}))),Ji=h({computerId:q(256),path:q(1024)}),Yi=q(80).pipe(C(g(e=>e.trim()===e,{message:`Expected a trimmed title`}))),Xi=q(64),Zi=q(80),Qi=e=>new Set(e.map(e=>e.id)).size===e.length,$i=h({id:Xi,label:Zi,siblings:D(f(h({id:Xi,label:Zi})).pipe(C(x(16)),C(g(Qi,{message:`Expected unique crumb sibling ids`}))))}),ea=h({id:Xi,label:Zi,icon:D(m(`play`)),variant:D(s([`primary`,`outline`,`ghost`])),tone:D(m(`destructive`)),disabled:D(A)}),ta=e=>f(ea).pipe(C(x(e)),C(g(Qi,{message:`Expected unique header command ids`}))),na=h({id:Xi,label:Zi,presentation:D(m(`bead`)),tone:D(s([`neutral`,`info`,`warning`,`success`,`error`]))}),ra={status:D(f(na).pipe(C(x(4)),C(g(Qi,{message:`Expected unique header status ids`})))),crumbs:D(f($i).pipe(C(x(8)),C(g(Qi,{message:`Expected unique crumb ids`})))),primary:D(ta(3)),menu:D(ta(12))},ia=h({contractVersion:m(1),canGoBack:A,title:D(Yi),...ra}),aa=h({canGoBack:A,title:D(l),...ra}),oa=t([h({kind:m(`crumb`),crumbId:Xi,siblingId:D(Xi)}),h({kind:m(`action`),actionId:Xi})]),sa=a(h({agentId:q(256),sessionId:q(256)})),ca=h({agents:D(f(s([`agent.list`,`agent.manage`,`agent.read`,`agent.send`])).pipe(C(x(4)))),computers:D(f(s([`computer.list`,`computer.readFile`,`computer.writeFile`,`computer.execute`])).pipe(C(x(4))))}),la=s([`granted`,`declined`,`customize`]),ua=h({message:q(512),tone:D(s([`info`,`success`,`warning`,`error`]))}),da=s(oe);h({code:da.pick([`DELIVERY_PENDING`])});var fa=h({code:da,message:q(512),retryable:A}),pa=h({protocolVersion:m(2),type:m(ki)}),ma=h({epoch:q(160),protocolVersion:m(2),type:m(Ai)}),ha=h({epoch:q(160),protocolVersion:m(2)}),ga={[Symbol.dispose]:D(y)},_a=t([h({...ga,ok:m(!0),value:y}),h({...ga,error:fa,ok:m(!1)})]);function J(e,t,i=`PROTOCOL`){return re(de(e,{onExcessProperty:`error`}),r({onFailure:e=>{throw new n(`The peer sent malformed protocol data`,{cause:e,code:i,retryable:!1})},onSuccess:t}))}function Y(e){return Object.freeze(e)}function va(e,t){let n=e.arguments===void 0?void 0:Wt(e.arguments),r={origin:e.origin,signal:t};return n!==void 0&&Object.assign(r,{arguments:n}),Y(r)}var ya=J(Vi,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}),Y(co(()=>nn(t)))},`INVALID_ARGUMENT`),ba=J(q(321),e=>e),xa=J(Hi,e=>{let t=e.arguments===void 0?void 0:Wt(e.arguments),n={commandId:e.commandId,origin:e.origin,requestId:e.requestId};return t!==void 0&&Object.assign(n,{arguments:t}),Y(n)}),Sa=J(t([ie,y]),e=>e===void 0?void 0:Wt(e)),Ca=J(ma,e=>Y(e));J(ha,e=>Y(e));var wa=J(Ri,e=>{let t={computerId:e.computerId,focus:Y({...e.focus}),openRequest:e.openRequest===null?null:Y({...e.openRequest}),visibility:e.visibility};return e.teamHasComputers!==void 0&&(t.teamHasComputers=e.teamHasComputers),e.computerAccessGranted!==void 0&&(t.computerAccessGranted=e.computerAccessGranted),Y(t)}),Ta=J(fa,e=>Y({...e})),Ea=J(Ii,e=>Y({...e}),`INVALID_ARGUMENT`),Da=J(Fi,e=>Y({...e})),Oa=J(zi,e=>e),ka=J(qi,e=>Y(e.map(e=>e.kind===`menu`?Y({...e,options:Y(e.options.map(e=>Y(e)))}):Y(e))),`INVALID_ARGUMENT`),Aa=J(h({itemId:q(64),optionId:k(q(64)),anchor:k(h({start:d.pipe(C(Oe({minimum:0,maximum:1e5}))),width:d.pipe(C(Oe({minimum:0,maximum:1e5})))}))}),e=>Y(e.anchor===void 0?{...e}:{...e,anchor:Y({...e.anchor})}),`INVALID_ARGUMENT`),ja=J(Ji,e=>Y({...e}),`INVALID_ARGUMENT`);function Ma(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}),Y(t)}function Na(e){let t={id:e.id,label:e.label};return e.siblings===void 0?Y(t):Y({...t,siblings:Y(e.siblings.map(e=>Y({...e})))})}function Pa(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}),Y(t)}function Fa(e){let t={canGoBack:e.canGoBack};return e.title!==void 0&&(t={...t,title:e.title}),e.crumbs!==void 0&&(t={...t,crumbs:Y(e.crumbs.map(Na))}),e.primary!==void 0&&(t={...t,primary:Y(e.primary.map(Pa))}),e.menu!==void 0&&(t={...t,menu:Y(e.menu.map(Pa))}),e.status!==void 0&&(t={...t,status:Y(e.status.map(Ma))}),Y(t)}var Ia=J(ia,Fa,`INVALID_ARGUMENT`),La=J(aa,e=>{let t=e.title?.trim();return Ra({...Fa({...e,title:t===void 0||t.length===0?void 0:t}),contractVersion:1})},`INVALID_ARGUMENT`),Ra=J(ia,e=>Y({...Fa(e),contractVersion:1}),`INVALID_ARGUMENT`),za=J(oa,e=>e.kind===`action`?Y({...e}):Y(e.siblingId===void 0?{kind:e.kind,crumbId:e.crumbId}:e),`INVALID_ARGUMENT`),Ba=J(sa,e=>e===null?null:Y({...e}),`INVALID_ARGUMENT`),Va=J(ca,e=>Y({agents:Y([...new Set(e.agents??[])]),computers:Y([...new Set(e.computers??[])])}),`INVALID_ARGUMENT`);J(pa,e=>Y(e));var Ha=J(q(512),e=>e),Ua=J(ua,e=>Y({...e}),`INVALID_ARGUMENT`);J(h({id:q(160),repeat:A}),e=>Y(e));var Wa=J(f(Bi).pipe(C(x(64))),e=>{if(new Set(e.map(e=>e.id)).size!==e.length)throw new n(`Reserved chords are invalid`,{code:`PROTOCOL`,retryable:!1});return Y(e.map(e=>Y({...e})))});function Ga(e){return J(h({value:y,version:Ni}),t=>Y({value:e(t.value),version:t.version}))}var Ka=Ga(wa),qa=J(h({capabilities:f(y).pipe(C(x(128))),context:y}),e=>Y({capabilities:Y(e.capabilities.map(e=>$a(e))),context:Ka(e.context)})),Ja=Ga(Oa),Ya=Ga(Wa),Xa=Ga(Ha),Za=re(Ja,e=>{if(e.value!==`connected`&&e.value!==`suspended`)throw new n(`The host lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return Y({value:e.value,version:e.version})});function Qa(e){return J(h({handle:y,id:q(160),version:Pi}),t=>{if(!(t.handle instanceof Ci)&&!(e&&t.handle instanceof wi))throw new n(`A capability handle is invalid`,{code:`PROTOCOL`,retryable:!1});return Y({handle:t.handle,id:t.id,version:t.version})})}var $a=Qa(!1),eo=Qa(!0);function to(e){let t=e?eo:$a;return J(h({capabilities:f(y).pipe(C(x(128))),context:y,identity:y,lifecycle:y,reservedChords:y,theme:y}),e=>Y({capabilities:Y(e.capabilities.map(e=>t(e))),context:Ka(e.context),identity:Da(e.identity),lifecycle:Za(e.lifecycle),reservedChords:Ya(e.reservedChords),theme:Xa(e.theme)}))}var no=to(!1);to(!0);function ro(e){return J(_a,t=>t.ok?Y({ok:!0,value:e(t.value)}):Y({ok:!1,error:Ta(t.error)}))}var io=ro(no),ao=ro(J(h({commandId:q(321)}),e=>Y(e)));ro(J(Ui,e=>{if(e.status===`failed`)return Y({status:`failed`,error:co(()=>Kt(e.error))});let t=e.result===void 0?void 0:Wt(e.result);return Y(t===void 0?{status:`handled`}:{status:`handled`,result:t})}));var oo=ro(J(ie,()=>void 0)),so=ro(J(la,e=>e));ro(J(A,e=>e)),ro(J(A,e=>e));function co(e){try{return e()}catch(e){throw new n(`The command metadata is invalid`,{cause:e,code:`INVALID_ARGUMENT`,retryable:!1})}}var lo=t([h({kind:m(`saveFile`),name:q(255).pipe(C(ge(/^[^\p{Cc}/\\]+$/u))),mime:q(255),bytes:ue}),h({kind:m(`copyText`),text:l})]);function uo(e){let t=de(lo,{onExcessProperty:`error`})(e);if(ne(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 fo=ro(J(t([h({kind:m(`saved`)}),h({kind:m(`copied`)}),h({kind:m(`refused`),reason:s([`no-user-gesture`,`too-large`,`invalid-request`,`unavailable`,`denied`,`busy`])})]),e=>Y(e)));function po(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 mo(e){let t=new Map,r=po(0),i=!1,a=e=>{let t=new Map;try{for(let r of e){let e=$a(r),i=vo(e.id,e.version);if(t.has(i))throw go(e.handle),new n(`Duplicate capability grant`,{code:`PROTOCOL`,retryable:!1});t.set(i,e.handle)}}catch(e){for(let e of t.values())go(e);throw e}return t};for(let[n,r]of a(e))t.set(n,r);let o=e=>{for(let t of e)go(t)},s=e=>{if(i)throw new n(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let r=vo(e.id,e.version);return t.get(r)};return{directory:Object.freeze({get version(){return r.get()},subscribe:e=>r.subscribe(e),has(e){return!!s(e)},require(e){let t=s(e);if(!t)throw new n(`The capability is not granted`,{code:`CAPABILITY_DENIED`,retryable:!1});try{return e.schema.parse(t)}catch(e){throw new n(`The capability interface is malformed`,{cause:e,code:`PROTOCOL`,retryable:!1})}}}),replace(e){if(i)throw new n(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let s=a(e),c=[...t.values()];t.clear();for(let[e,n]of s)t.set(e,n);o(c.filter(e=>![...s.values()].includes(e))),r.update(r.get()+1)},disconnect(){i||(i=!0,o(t.values()),t.clear(),r.update(r.get()+1))}}}var ho=_().transform(e=>{let t=xe(Object).safeParse(e);if(!t.success)return;let n=Object.create(t.data),r=w(h({[Symbol.dispose]:D(pe(Function))}))(n);return{owner:t.data,dispose:r[Symbol.dispose]}});function go(e){try{let t=ho.parse(e);if(t===void 0||_o.has(t.owner))return;_o.add(t.owner),t.dispose?.call(t.owner)}catch(e){console.warn(`RPC value disposal failed`,e)}}var _o=new WeakSet;function vo(e,t){return`${e}@${String(t)}`}function yo(e){let t=(0,j.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,j.useCallback)(()=>e?.get(),[e]);return(0,j.useSyncExternalStore)(t,n,n)}function bo(e){return yo(e?.context)??null}function xo(e){return bo(e)?.computerId??null}function So(e,t,n,r){let i=(0,j.useRef)(t);i.current=t;let a=(0,j.useRef)(n);a.current=n;let o=(0,j.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,j.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,j.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,j.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function Co(e,{sourceId:t,namespace:n},r){let i=(0,j.useMemo)(()=>mn(),[]),a=(0,j.useMemo)(r,[r]);return(0,j.useEffect)(()=>{let e=i.contribute({sourceId:t,namespace:n,commands:a});return()=>{e.dispose()}},[i,t,n,a]),(0,j.useEffect)(()=>e?sr(e.commands,a):void 0,[e,a]),i}function wo(e,{canGoBack:t,title:n,crumbs:r,primary:i,menu:a,status:o,onBack:s,onCrumb:c,onAction:l}){let u=(0,j.useRef)(s),d=(0,j.useRef)(c),ee=(0,j.useRef)(l);(0,j.useEffect)(()=>{u.current=s,d.current=c,ee.current=l},[s,c,l]),(0,j.useEffect)(()=>{if(!e)return;let t=e.onBack(()=>u.current()),n=e.onActivate(e=>{if(e.kind===`action`){let t=ee.current;return t?.(e.actionId),t!==void 0}let t=d.current;return e.siblingId===void 0?t?.(e.crumbId):t?.(e.crumbId,e.siblingId),t!==void 0});return()=>{t(),n(),To(e,{canGoBack:!1})}},[e]);let te=JSON.stringify([r,i,a,o]),ne=(0,j.useRef)({crumbs:r,primary:i,menu:a,status:o});(0,j.useEffect)(()=>{ne.current={crumbs:r,primary:i,menu:a,status:o}},[r,i,a,o]),(0,j.useEffect)(()=>{if(!e)return;let r={canGoBack:t};n!==void 0&&(r={...r,title:n});let i=ne.current;i.crumbs!==void 0&&(r={...r,crumbs:i.crumbs}),i.primary!==void 0&&(r={...r,primary:i.primary}),i.menu!==void 0&&(r={...r,menu:i.menu}),i.status!==void 0&&(r={...r,status:i.status}),To(e,r)},[e,t,n,te])}function To(e,t){e.publish(t).catch(e=>{e instanceof n&&e.code===`DISCONNECTED`||console.warn(`App navigation report failed`,e)})}var Eo=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 X(e,t,n){return new Eo(e,t,n)}function Z(e){let t=S(e),n=xe(Object),r=S(Object.fromEntries(Object.keys(e).map(e=>[e,_().optional()])));return _().transform(e=>{let i=n.parse(e),a=Object.create(i),o=r.parse(a),s=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,Te().parse(t).bind(i)]));return{...t.parse(s),[Symbol.dispose](){go(e)}}})}function Q(e){return _().transform(t=>{try{return e.parse(t)}catch(e){throw e instanceof n?e:new n(`The capability returned malformed data`,{cause:e,code:`PROTOCOL`,retryable:!1})}finally{go(t)}})}function $(e){return Te({output:ye(_().transform(t=>{try{return e.parse(t)}catch(e){throw go(t),e instanceof n?e:new n(`The capability returned a malformed result`,{cause:e,code:`PROTOCOL`,retryable:!1})}}))})}var Do=$(Q(fe()));Z({fetch:$(xe(Response)),close:Do});function Oo(e){return e instanceof n?e:new n(`App operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!1})}var ko=new WeakMap,Ao={of(e,...t){return[e?.identity.surfaceId??null,e?.context.get().computerId??null,...t]}};function jo(e){let t={};return e&&ko.set(t,e),t}function Mo(){let e=new Rt({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&&ko.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 No(e,t,r,i){let a=e?.context.get().computerId;return zt({queryKey:r,meta:jo(e),enabled:e!==null,retry:!1,queryFn:async({signal:r})=>{try{if(!e)throw new n(`No App connection`,{code:`DISCONNECTED`,retryable:!0});if(e.context.get().computerId!==a)throw new n(`The selected Computer changed`,{code:`SELECTION_CHANGED`,retryable:!1});return await i(e.capabilities.require(t),r)}catch(e){throw Oo(e)}}})}var Po=be(Ee(h({error:m(`too_large`)})));async function Fo(e,t){let r,i=()=>r??=e.close(),a=()=>{i().catch(e=>{cr(`files.read.abort-close`,e)})};t.signal?.addEventListener(`abort`,a,{once:!0});try{t.signal?.throwIfAborted();let r=await e.response();try{let e=w(pe(Response))(r);if(e.status===413){let t=Po(await e.text());throw new n(`App file exceeds the read bound`,{code:t._tag===`Some`?`FILE_TOO_LARGE`:`PROTOCOL`,retryable:!1})}if(!e.ok)throw Error(`App file unavailable (${String(e.status)})`);let i=await e.blob();return t.signal?.throwIfAborted(),new File([i],t.name,{type:i.type,lastModified:0})}finally{go(r)}}finally{t.signal?.removeEventListener(`abort`,a);try{await i()}finally{e[Symbol.dispose]()}}}async function Io(e,t,n){let r,i=()=>r??=e.close(),a=()=>{i().catch(e=>{cr(`files.write.abort-close`,e)})};n.signal?.addEventListener(`abort`,a,{once:!0});try{n.signal?.throwIfAborted(),await e.write(t.stream())}finally{n.signal?.removeEventListener(`abort`,a);try{await i()}catch(e){cr(`files.write.remote-close`,e)}try{e[Symbol.dispose]()}catch(e){cr(`files.write.local-dispose`,e)}}}var Lo=h({path:l,entries:f(h({name:l,type:s([`file`,`directory`,`symlink`]),size:d,modifiedAt:d})),nextOffset:a(d)}),Ro=X(`computer.list`,1,v(()=>Z({list:$(Q(_().transform(e=>w(Lo)(e))))}))),zo=t([h({state:s([`running`,`sleeping`,`starting`,`start_failed`])}),h({state:m(`queued`),position:d.pipe(C(E()),C(me(0)))})]),Bo=h({enabled:A,effective:A,blockedBy:a(s([`team`,`global`]))}),Vo=h({computerId:p,name:p,runtime:zo,backends:f(h({id:p,kind:s([`platform-container`,`on-box-vm`,`local`]),status:s([`ready`,`queued`,`online`,`offline`]),queuePosition:a(d.pipe(C(E()),C(me(0)))),hostId:a(l),hostLabel:a(l),folderLabel:a(l),detachable:A})),internet:Bo});X(`computer.instrument.read`,1,v(()=>Z({read:$(Q(_().transform(e=>w(Vo)(e))))}))),X(`computer.instrument.control`,1,v(()=>Z({start:$(Q(_().transform(e=>w(zo)(e)))),setInternetAccess:$(Q(_().transform(e=>w(Bo)(e)))),detachLocal:$(Q(_().transform(e=>w(h({detached:A}))(e))))})));var Ho=h({ports:f(h({port:d.pipe(C(E()),C(Oe({minimum:1,maximum:65535}))),previewUrl:p,openMode:s([`inline`,`external-only`]),expiresAt:d.pipe(C(E()),C(me(0)))})).pipe(C(x(64)))}),Uo=t([Ho,h({error:m(`port_previews_not_configured`)})]),Wo=h({port:d.annotate({message:`Use a port from 1 to 65535.`}).check(E({message:`Use a port from 1 to 65535.`}),Oe({minimum:1,maximum:65535},{message:`Use a port from 1 to 65535.`})),exposed:A}),Go=h({port:d.pipe(C(E()),C(Oe({minimum:1,maximum:65535}))),removed:A});X(`computer.ports`,2,v(()=>Z({list:$(Q(_().transform(e=>w(Uo)(e)))),expose:$(Q(_().transform(e=>w(Wo)(e)))),unexpose:$(Q(_().transform(e=>w(Go)(e))))})));var Ko=s([`synced`,`pending`,`unknown`]),qo=h({port:a(Wo.fields.port),id:p,command:p,cwd:a(l),startedAt:d.pipe(C(E()),C(he(0))),state:s([`running`,`exited`,`uncertain`]),exitCode:a(d.pipe(C(E()))),sync:Ko,endedAt:a(d.pipe(C(E()),C(he(0))))}),Jo=h({processes:f(qo)}),Yo=h({process:qo,signalled:A});h({requestId:p.pipe(C(x(256))),command:p.pipe(C(x(16384))),cwd:k(l),port:k(Wo.fields.port)}),X(`computer.processes`,1,v(()=>Z({start:$(Q(_().transform(e=>w(qo)(e)))),list:$(Q(_().transform(e=>w(Jo)(e)))),kill:$(Q(_().transform(e=>w(Yo)(e))))})));var Xo=X(`computer.readFile`,1,v(()=>Z({open:$(Z({response:$(xe(Response)),close:Do}))})));async function Zo(e,t,n){return await Fo(await e.require(Xo).open(t),{...n,name:t.path.split(`/`).at(-1)??`file`})}async function Qo(e,t){return w(Lo)(await e.require(Ro).list(t))}var $o=X(`computer.writeFile`,3,v(()=>Z({open:$(Z({write:Do,close:Do})),mkdir:Do,replace:$(Q(_().transform(e=>w(es)(e))))}))),es=t([h({kind:m(`replaced`),path:p,bytes:d.pipe(C(E()),C(he(0)))}),h({kind:m(`conflict`)})]);async function ts(e,t,r){r.signal?.throwIfAborted();let i=await e.require($o).replace(t);if(i.kind===`conflict`)throw new n(`Computer file changed since it was opened`,{code:`CONFLICT`,retryable:!1});return{path:i.path,bytes:i.bytes}}var ns=h({computerName:p.pipe(C(x(256))),teamName:p.pipe(C(x(256))),modelDoor:p.pipe(C(x(256))),uptimeSeconds:d.pipe(C(E()),C(he(0))),version:p.pipe(C(x(64)))});X(`computer.terminal`,2,v(()=>Z({open:$(Z({information:$(Q(_().transform(e=>w(ns)(e)))),output:$(xe(ReadableStream).transform(e=>e.pipeThrough(new TransformStream({transform(e,t){t.enqueue(xe(Uint8Array).parse(e))}})))),input:$(xe(WritableStream)),resize:Do,close:Do}))})));async function rs(e,t,n){await Io(await e.require($o).open({path:t.path}),t.content,n)}var is=ee(`FilePlus2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M3 15h6`,key:`4e2qda`}],[`path`,{d:`M6 12v6`,key:`1u72j0`}]]),as=ee(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]);function os(e,t){let n=e.trim();return n.startsWith(`/`)?n:`${t.endsWith(`/`)?t:`${t}/`}${n}`}function ss(e){if(e.endsWith(`/`))return e.replace(/\/+$/,``)||`/`;let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}export{ka as $,uo as A,Fe as At,Ea as B,So as C,Je as Ct,va as D,He as Dt,po as E,qe as Et,Sa as F,za as G,Da as H,Ca as I,so as J,Ia as K,wa as L,ya as M,ba as N,Ba as O,Be as Ot,xa as P,Aa as Q,Ta as R,wo as S,tt as St,go as T,ft as Tt,Oa as U,qa as V,ja as W,ao as X,Va as Y,Wa as Z,Do as _,gt as _t,Ro as a,Oi as at,bo as b,M as bt,Zo as c,wi as ct,No as d,fn as dt,Ha as et,Mo as f,Kt as ft,$ as g,_t as gt,Z as h,N as ht,is as i,ki as it,fo as j,io as k,ze as kt,ts as l,Ti as lt,Q as m,At as mt,os as n,oo as nt,$o as o,Di as ot,Ao as p,Wt as pt,La as q,as as r,Ai as rt,Qo as s,Ci as st,ss as t,Ua as tt,rs as u,cr as ut,X as v,ht as vt,mo as w,nt as wt,xo as x,st as xt,Co as y,Ke as yt,Ga as z};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{At as t,Bt as n,Dn as r,Dt as i,Et as a,Ft as o,G as s,Ht as c,Ir as l,It as u,Jt as d,Ln as f,Lr as p,Lt as m,Mn as h,Mt as g,Nt as _,Ot as v,Pn as y,Pt as b,Rn as x,Rt as S,S as C,St as w,Tt as T,Ut as E,Vt as D,W as O,Wt as k,Xt as A,Y as j,Z as M,Zt as ee,at as te,bt as ne,ct as re,dt as ie,en as ae,ft as oe,it as se,jt as ce,kn as le,kt as N,lt as ue,nt as P,ot as de,rt as fe,st as pe,tt as me,ut as he,wt as ge,zn as _e,zt as F}from"./dialog-C49TyOKM.js";var ve=f(`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`}]]),ye=f(`Minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),be=f(`Plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),I=e(p(),1);function xe(e,t){return t!=null&&!ue(t)?0:typeof e==`function`?e():e}function Se(e,t,n){let r=xe(e,n);return typeof r==`number`?r:r?.[t]}function Ce(e){return typeof e==`function`?e():e}function we(e,t){return t||e===`click`||e===`mousedown`}function Te(e){return e?.includes(`mouse`)&&e!==`mousedown`}var L=l(),R=Math.min,z=Math.max,Ee=Math.round,De=Math.floor,B=e=>({x:e,y:e}),Oe={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function ke(e,t,n){return z(e,R(t,n))}function V(e,t){return typeof e==`function`?e(t):e}function H(e){return e.split(`-`)[0]}function U(e){return e.split(`-`)[1]}function Ae(e){return e===`x`?`y`:`x`}function W(e){return e===`y`?`height`:`width`}function G(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function je(e){return Ae(G(e))}function Me(e,t,n){n===void 0&&(n=!1);let r=U(e),i=je(e),a=W(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=Ve(o)),[o,Ve(o)]}function Ne(e){let t=Ve(e);return[Pe(e),t,Pe(t)]}function Pe(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var Fe=[`left`,`right`],Ie=[`right`,`left`],Le=[`top`,`bottom`],Re=[`bottom`,`top`];function ze(e,t,n){switch(e){case`top`:case`bottom`:return n?t?Ie:Fe:t?Fe:Ie;case`left`:case`right`:return t?Le:Re;default:return[]}}function Be(e,t,n,r){let i=U(e),a=ze(H(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(Pe)))),a}function Ve(e){let t=H(e);return Oe[t]+e.slice(t.length)}function He(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function Ue(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:He(e)}function We(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}}var Ge=class e{pointerType=void 0;interactedInside=!1;handler=void 0;blockMouseMove=!0;performedPointerEventsMutation=!1;pointerEventsScopeElement=null;pointerEventsReferenceElement=null;pointerEventsFloatingElement=null;restTimeoutPending=!1;openChangeTimeout=new he;restTimeout=new he;handleCloseOptions=void 0;static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose},Ke=new WeakMap;function qe(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&Ke.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),Ke.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function Je(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=Ke.get(n);a&&a!==e&&qe(a),qe(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,Ke.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function Ye(e){let t=e.context.dataRef.current,n=ee(()=>t.hoverInteractionState??Ge.create()).current;return t.hoverInteractionState||=n,oe(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function Xe(e,t={}){let{enabled:n=!0,closeDelay:r=0,nodeId:i}=t,o=e.useState(`open`),c=e.useState(`floatingElement`),l=e.useState(`domReferenceElement`),{dataRef:u}=e.context,d=s(),f=O(),p=Ye(e),h=ie(),g=a(()=>we(u.current.openEvent?.type,p.interactedInside)),_=a(()=>Te(u.current.openEvent?.type)),v=a(()=>{qe(p)});T(()=>{o||(p.pointerType=void 0,p.restTimeoutPending=!1,p.interactedInside=!1,v())},[o,p,v]),I.useEffect(()=>v,[v]),T(()=>{if(n&&o&&p.handleCloseOptions?.blockPointerEvents&&_()&&m(l)&&c){let e=l,t=c,n=ge(c),r=d?.nodesRef.current.find(e=>e.id===f)?.context?.elements.floating;r&&(r.style.pointerEvents=``);let i=p.pointerEventsScopeElement===t?null:p.pointerEventsScopeElement,a=r===t?null:r,o=p.handleCloseOptions?.getScope?.()??i??a??de(e,`[data-rootownerid]`)??n.body;return Je(p,{scopeElement:o,referenceElement:e,floatingElement:t}),()=>{v()}}},[n,o,l,c,p,_,d,f,v]),I.useEffect(()=>{if(!n)return;function t(){return!!(d&&f&&M(d.nodesRef.current,f).length>0)}function a(t){let n=Se(r,`close`,p.pointerType),i=()=>{e.setOpen(!1,w(ne,t)),d?.events.emit(`floating.closed`,t)};n?p.openChangeTimeout.start(n,i):(p.openChangeTimeout.clear(),i())}function o(e){let t=re(e);if(!se(t)){p.interactedInside=!1;return}p.interactedInside=de(t,`[aria-haspopup]`)!=null}function s(){p.openChangeTimeout.clear(),h.clear(),d?.events.off(`floating.closed`,y),v()}function l(n){if(t()&&d){d.events.on(`floating.closed`,y);return}if(te(n.relatedTarget,e.context.triggerElements))return;let r=u.current.floatingContext?.nodeId??i,o=n.relatedTarget;if(!(d&&r&&m(o)&&M(d.nodesRef.current,r,!1).some(e=>pe(e.context?.elements.floating,o)))){if(p.handler){p.handler(n);return}v(),_()&&!g()&&a(n)}}function y(n){!d||!f||t()||h.start(0,()=>{d.events.off(`floating.closed`,y),e.setOpen(!1,w(ne,n)),d.events.emit(`floating.closed`,n)})}let b=c;return P(b&&fe(b,`mouseenter`,s),b&&fe(b,`mouseleave`,l),b&&fe(b,`pointerdown`,o,!0),()=>{d?.events.off(`floating.closed`,y)})},[n,c,e,u,r,i,_,g,v,p,d,f,h])}function Ze(e,t,n){let{reference:r,floating:i}=e,a=G(t),o=je(t),s=W(o),c=H(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=U(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function Qe(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=V(t,e),p=Ue(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=We(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=We(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 $e=50,et=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:Qe},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=Ze(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<$e&&(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}=Ze(l,f,c)),n=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:m}},tt=function(e){return e===void 0&&(e={}),{name:`flip`,options:e,async fn(t){var n;let{placement:r,middlewareData:i,rects:a,initialPlacement:o,platform:s,elements:c}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:f=`bestFit`,fallbackAxisSideDirection:p=`none`,flipAlignment:m=!0,...h}=V(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let g=H(r),_=G(o),v=H(o)===o,y=await(s.isRTL==null?void 0:s.isRTL(c.floating)),b=d||(v||!m?[Ve(o)]:Ne(o)),x=p!==`none`;!d&&x&&b.push(...Be(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=Me(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`||_===G(t)||T.every(e=>G(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=G(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{}}}},nt=new Set([`left`,`top`]);async function rt(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=H(n),s=U(n),c=G(n)===`y`,l=nt.has(o)?-1:1,u=a&&c?-1:1,d=V(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var it=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 rt(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}}}}},at=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=V(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=G(i),p=Ae(f),m=u[p],h=u[f],g=(e,t)=>ke(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}}}}}},ot=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=V(e,t),u={x:n,y:r},d=G(i),f=Ae(d),p=u[f],m=u[d],h=V(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;p<t?p=t:p>n&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=nt.has(H(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);m<n?m=n:m>r&&(m=r)}return{[f]:p,[d]:m}}}},st=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=V(e,t),c=await i.detectOverflow(t,s),l=H(n),u=U(n),d=G(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=R(p-c[m],g),y=R(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*z(c.left,c.right):S=p-2*z(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 ct(e){let t=i(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,a=S(e),o=a?e.offsetWidth:n,s=a?e.offsetHeight:r,c=Ee(n)!==o||Ee(r)!==s;return c&&(n=o,r=s),{width:n,height:r,$:c}}function lt(e){return m(e)?e:e.contextElement}function ut(e){let t=lt(e);if(!S(t))return B(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=ct(t),o=(a?Ee(n.width):n.width)/r,s=(a?Ee(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var dt=B(0);function ft(e){let t=o(e);return!E()||!t.visualViewport?dt:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function pt(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===o(e)}function mt(e,n,r,a){n===void 0&&(n=!1),r===void 0&&(r=!1);let s=e.getBoundingClientRect(),c=lt(e),l=B(1);n&&(a?m(a)&&(l=ut(a)):l=ut(e));let u=pt(c,r,a)?ft(c):B(0),d=(s.left+u.x)/l.x,f=(s.top+u.y)/l.y,p=s.width/l.x,h=s.height/l.y;if(c&&a){let e=o(c),n=m(a)?o(a):a,r=e,s=t(r);for(;s&&n!==r;){let e=ut(s),n=s.getBoundingClientRect(),a=i(s),c=n.left+(s.clientLeft+parseFloat(a.paddingLeft))*e.x,l=n.top+(s.clientTop+parseFloat(a.paddingTop))*e.y;d*=e.x,f*=e.y,p*=e.x,h*=e.y,d+=c,f+=l,r=o(s),s=t(r)}}return We({width:p,height:h,x:d,y:f})}function ht(e,t){let n=g(e).scrollLeft;return t?t.left+n:mt(N(e)).left+n}function gt(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ht(e,n),y:n.top+t.scrollTop}}function _t(e){let{elements:t,rect:r,offsetParent:i,strategy:a}=e,o=a===`fixed`,s=N(i),l=t?c(t.floating):!1;if(i===s||l&&o)return r;let u={scrollLeft:0,scrollTop:0},d=B(1),f=B(0),p=S(i);if((p||!o)&&((ce(i)!==`body`||n(s))&&(u=g(i)),p)){let e=mt(i);d=ut(i),f.x=e.x+i.clientLeft,f.y=e.y+i.clientTop}let m=s&&!p&&!o?gt(s,u):B(0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-u.scrollLeft*d.x+f.x+m.x,y:r.y*d.y-u.scrollTop*d.y+f.y+m.y}}function vt(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function yt(e){let t=g(e),n=e.ownerDocument.body,r=z(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),a=z(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),o=-t.scrollLeft+ht(e),s=-t.scrollTop;return i(n).direction===`rtl`&&(o+=z(e.clientWidth,n.clientWidth)-r),{width:r,height:a,x:o,y:s}}var bt=25;function xt(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=o(e),a=N(e),s=i.visualViewport,c=a.clientWidth,l=a.clientHeight,u=0,d=0;if(s){let e=!E()||t===`fixed`;r?e||(u=-s.offsetLeft,d=-s.offsetTop):(c=s.width,l=s.height,e&&(u=s.offsetLeft,d=s.offsetTop))}if(ht(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<=bt&&(c-=o)}return{width:c,height:l,x:u,y:d}}function St(e,t){let n=mt(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=ut(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function Ct(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=xt(e,n,t);else if(t===`document`)r=yt(N(e));else if(m(t))r=St(t,n);else{let n=ft(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return We(r)}function wt(e,t){let n=t.get(e);if(n)return n;let r=_(e,[],!1).filter(e=>m(e)&&ce(e)!==`body`),a=null,o=i(e).position===`fixed`,s=o?b(e):e;for(;m(s)&&!F(s);){let e=i(s),t=u(s),n=a?a.position:o?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==s):a=e,s=b(s)}return t.set(e,r),r}function Tt(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?c(t)?[]:wt(t,this._c):[].concat(n),r],o=Ct(t,a[0],i),s=o.top,l=o.right,u=o.bottom,d=o.left;for(let e=1;e<a.length;e++){let n=Ct(t,a[e],i);s=z(n.top,s),l=R(n.right,l),u=R(n.bottom,u),d=z(n.left,d)}return{width:l-d,height:u-s,x:d,y:s}}function Et(e){let{width:t,height:n}=ct(e);return{width:t,height:n}}function Dt(e,t,r){let i=S(t),a=N(t),o=r===`fixed`,s=mt(e,!0,o,t),c={scrollLeft:0,scrollTop:0},l=B(0);if((i||!o)&&((ce(t)!==`body`||n(a))&&(c=g(t)),i)){let e=mt(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}!i&&a&&(l.x=ht(a));let u=a&&!i&&!o?gt(a,c):B(0);return{x:s.left+c.scrollLeft-l.x-u.x,y:s.top+c.scrollTop-l.y-u.y,width:s.width,height:s.height}}function Ot(e){return i(e).position===`static`}function kt(e,t){if(!S(e)||i(e).position===`fixed`)return null;if(t)return t(e);let n=e.offsetParent;return N(e)===n&&(n=n.ownerDocument.body),n}function At(e,t){let n=o(e);if(c(e))return n;if(!S(e)){let t=b(e);for(;t&&!F(t);){if(m(t)&&!Ot(t))return t;t=b(t)}return n}let r=kt(e,t);for(;r&&D(r)&&Ot(r);)r=kt(r,t);return r&&F(r)&&Ot(r)&&!u(r)?n:r||v(e)||n}var jt=async function(e){let t=this.getOffsetParent||At,n=this.getDimensions,r=await n(e.floating);return{reference:Dt(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Mt(e){return i(e).direction===`rtl`}var Nt={convertOffsetParentRelativeRectToViewportRelativeRect:_t,getDocumentElement:N,getClippingRect:Tt,getOffsetParent:At,getElementRects:jt,getClientRects:vt,getDimensions:Et,getScale:ut,isElement:m,isRTL:Mt};function Pt(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Ft(e,t,n){let r=null,i,a=N(e);function s(){var e;clearTimeout(i),(e=r)==null||e.disconnect(),r=null}function c(n,o){n===void 0&&(n=!1),o===void 0&&(o=1),s();let l=e.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=l;if(n||t(),!f||!p)return;let m=De(d),h=De(a.clientWidth-(u+f)),g=De(a.clientHeight-(d+p)),_=De(u),v={rootMargin:-m+`px `+-h+`px `+-g+`px `+-_+`px`,threshold:z(0,R(1,o))||1},y=!0;function b(t){let n=t[0].intersectionRatio;if(!Pt(l,e.getBoundingClientRect()))return c();if(n!==o){if(!y)return c();n?c(!1,n):i=setTimeout(()=>{c(!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 l=o(e),u=()=>c(n);return l.addEventListener(`resize`,u),c(!0),()=>{l.removeEventListener(`resize`,u),s()}}function It(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=lt(e),u=i||a?[...l?_(l):[],...t?_(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?Ft(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?mt(e):null;c&&g();function g(){let t=mt(e);h&&!Pt(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 Lt=it,Rt=at,zt=tt,Bt=st,Vt=ot,Ht=(e,t,n)=>{let r=new Map,i=n??{},a={...Nt,...i.platform,_c:r};return et(e,t,{...i,platform:a})},Ut=e(_e(),1),Wt=typeof document<`u`?I.useLayoutEffect:function(){};function Gt(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(!Gt(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)&&!Gt(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function Kt(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function qt(e,t){let n=Kt(e);return Math.round(t*n)/n}function Jt(e){let t=I.useRef(e);return Wt(()=>{t.current=e}),t}function Yt(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]=I.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=I.useState(r);Gt(f,r)||p(r);let[m,h]=I.useState(null),[g,_]=I.useState(null),v=I.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=I.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=I.useRef(null),C=I.useRef(null),w=I.useRef(u),T=c!=null,E=Jt(c),D=Jt(i),O=Jt(l),k=I.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),Ht(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};A.current&&!Gt(w.current,t)&&(w.current=t,Ut.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);Wt(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let A=I.useRef(!1);Wt(()=>(A.current=!0,()=>{A.current=!1}),[]),Wt(()=>{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=I.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),M=I.useMemo(()=>({reference:b,floating:x}),[b,x]),ee=I.useMemo(()=>{let e={position:n,left:0,top:0};if(!M.floating)return e;let t=qt(M.floating,u.x),r=qt(M.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...Kt(M.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,M.floating,u.x,u.y]);return I.useMemo(()=>({...u,update:k,refs:j,elements:M,floatingStyles:ee}),[u,k,j,M,ee])}var Xt=(e,t)=>{let n=Lt(e);return{name:n.name,fn:n.fn,options:[e,t]}},Zt=(e,t)=>{let n=Rt(e);return{name:n.name,fn:n.fn,options:[e,t]}},Qt=(e,t)=>({fn:Vt(e).fn,options:[e,t]}),$t=(e,t)=>{let n=zt(e);return{name:n.name,fn:n.fn,options:[e,t]}},en=(e,t)=>{let n=Bt(e);return{name:n.name,fn:n.fn,options:[e,t]}},tn=(0,I.forwardRef)(function({className:e,invalid:t,...n},r){return(0,L.jsx)(`input`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:x(`input caps-input w-full`,e),ref:r})});(0,I.forwardRef)(function({leading:e,className:t,...n},r){return(0,L.jsxs)(`span`,{className:`caps-search-input`,"data-leading":e?`true`:void 0,children:[e?(0,L.jsx)(`span`,{className:`caps-search-leading`,"aria-hidden":`true`,children:e}):null,(0,L.jsx)(tn,{...n,type:`search`,className:t,ref:r})]})});function nn(e){let{nodeId:t,externalTree:n,rootContext:r}=e,i=r.useState(`referenceElement`),a=r.useState(`floatingElement`),o=r.useState(`domReferenceElement`),c=r.useState(`open`),l=r.useState(`floatingId`),[u,d]=I.useState(null),f=I.useRef(null),p=s(n),h=I.useMemo(()=>({reference:i,floating:a,domReference:o}),[i,a,o]),g=Yt({...e,elements:{...h,...u&&{reference:u}}}),_=I.useCallback(e=>{let t=m(e)?{getBoundingClientRect:()=>e.getBoundingClientRect(),getClientRects:()=>e.getClientRects(),contextElement:e}:e;d(t),g.refs.setReference(t)},[g.refs]),v=I.useMemo(()=>({...g.refs,setPositionReference:_,domReference:f}),[g.refs,_]),y=I.useMemo(()=>({...g.elements,domReference:o}),[g.elements,o]),b=I.useMemo(()=>({...g,dataRef:r.context.dataRef,open:c,onOpenChange:r.setOpen,events:r.context.events,floatingId:l,refs:v,elements:y,nodeId:t,rootStore:r}),[g,v,y,t,r,c,l]);return T(()=>{o&&(f.current=o)},[o]),T(()=>{r.context.dataRef.current.floatingContext=b;let e=p?.nodesRef.current.find(e=>e.id===t);e&&(e.context=b)}),I.useMemo(()=>({...g,context:b,refs:v,elements:y,rootStore:r}),[g,v,y,b,r])}var rn=I.createContext(void 0);function an(){return I.useContext(rn)?.direction??`ltr`}var on=e=>({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=V(e,t)||{};if(l==null)return{};let d=Ue(u),f={x:n,y:r},p=je(i),m=W(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=ke(D,k,O),j=!c.arrow&&U(i)!=null&&k!==A&&a.reference[m]/2-(k<D?T:E)-h[m]/2<0,M=j?k<D?k-D:k-O:0;return{[p]:f[p]+M,data:{[p]:A,centerOffset:k-A-M,...j&&{alignmentOffset:M}},reset:j}}}),sn=(e,t)=>{let{name:n,fn:r}=on(e);return{name:n,fn:r,options:[e,t]}},cn={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}}}},ln={sideX:`left`,sideY:`top`},un=`--available-width`,dn=`--available-height`,fn=`--anchor-width`,pn=`--anchor-height`,mn=`--transform-origin`,hn=un,gn=dn;function _n(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 vn(e,t,n){let{rects:r,placement:i}=e;return{side:_n(t,H(i),n),align:U(i)||`center`,anchor:{width:r.reference.width,height:r.reference.height},positioner:{width:r.floating.width,height:r.floating.height}}}function yn(e){return bn(e,nn)}function bn(e,t){let{anchor:n,positionMethod:r=`absolute`,side:i=`bottom`,sideOffset:s=0,align:c=`center`,alignOffset:l=0,collisionBoundary:u,collisionPadding:d=5,sticky:f=!1,arrowPadding:p=5,disableAnchorTracking:m=!1,inline:h,keepMounted:g=!1,floatingRootContext:_,mounted:v,collisionAvoidance:y,shift:b,nodeId:x,adaptiveOrigin:S,lazyFlip:C=!1,externalTree:w}=e,E=y.side||`flip`,D=y.align||`flip`,O=y.fallbackAxisSide||`end`,k=b?.crossAxis??!1,A=b?.rootBoundary,j=typeof n==`function`?n:void 0,M=a(j),ee=j?M:n,te=me(n),ne=me(v),re=an()===`rtl`,[ie,ae]=I.useState(null);!v&&ie!==null&&ae(null);let oe=C===`placement`,se=ie?H(ie):null,ce=ie&&oe?U(ie)||`center`:null,le=se||{top:`top`,right:`right`,bottom:`bottom`,left:`left`,"inline-end":re?`left`:`right`,"inline-start":re?`right`:`left`}[i],N=ce||c,ue=N===`center`?le:`${le}-${N}`,P=d;typeof P==`number`?P={top:P,right:P,bottom:P,left:P}:P&&={top:P.top||0,right:P.right||0,bottom:P.bottom||0,left:P.left||0};let de=+(i===`bottom`),fe=+(i===`top`),pe=+(i===`right`),he=+(i===`left`),_e={boundary:u===`clipping-ancestors`?`clippingAncestors`:u,padding:P},F=I.useRef(null),ve=me(s),ye=me(l),be=typeof s==`function`?0:s,xe=typeof l==`function`?0:l,Se=[];h&&Se.push(h),Se.push(Xt(e=>{let t=vn(e,i,re),n=typeof ve.current==`function`?ve.current(t):ve.current,r=typeof ye.current==`function`?ye.current(t):ye.current;return{mainAxis:n,crossAxis:r,alignmentAxis:r}},[be,xe,re,i]));let Ce=D===`none`&&E!==`shift`,we=!Ce&&(f||k||E===`shift`),Te=E===`none`?null:$t({..._e,padding:{top:P.top+1+de,right:P.right+1+he,bottom:P.bottom+1+fe,left:P.left+1+pe},mainAxis:!k&&E===`flip`,crossAxis:D===`flip`&&`alignment`,fallbackAxisSideDirection:O}),L=Ce?null:Zt({..._e,rootBoundary:A,mainAxis:D!==`none`,crossAxis:we,limiter:f||k?void 0:Qt(e=>{if(!F.current)return{};let{width:t,height:n}=F.current.getBoundingClientRect(),r=G(H(e.placement)),i=r===`y`?t:n,a=r===`y`?P.left+P.right:P.top+P.bottom;return{offset:i/2+a/2}})},[_e,f,k,A,P,D]);E===`shift`||D===`shift`||N===`center`?Se.push(L,Te):Se.push(Te,L),Se.push(en({..._e,apply({elements:{floating:e},availableWidth:t,availableHeight:n,rects:r}){if(!ne.current)return;let i=e.style;i.setProperty(hn,`${t}px`),i.setProperty(gn,`${n}px`);let a=o(e).devicePixelRatio||1,{x:s,y:c,width:l,height:u}=r.reference,d=(Math.round((s+l)*a)-Math.round(s*a))/a,f=(Math.round((c+u)*a)-Math.round(c*a))/a;i.setProperty(fn,`${d}px`),i.setProperty(pn,`${f}px`)}}),sn(e=>({element:F.current||ge(e.elements.floating).createElement(`div`),padding:F.current?p:0}),[p]),{name:`transformOrigin`,fn(e){let{elements:{floating:t},middlewareData:n,placement:r,platform:a,rects:o,y:c}=e,l=H(r),u=U(r),d=G(l)===`y`,f=F.current,p=typeof s==`function`?s(vn(e,i,re)):s,m;m=!f&&u&&Math.abs(d?n.shift?.x||0:n.shift?.y||0)<=1?u===`start`===(d&&a.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 we&&d&&Math.abs(n.shift?.y||0)>p&&(h=`${o.reference.y+o.reference.height/2-c}px`),t.style.setProperty(mn,d?`${m} ${h}`:`${h} ${m}`),{}}},cn,S),T(()=>{!v&&_&&_.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[v,_]);let R=I.useMemo(()=>({ancestorScroll:!m,elementResize:!m&&typeof ResizeObserver<`u`,layoutShift:!m&&typeof IntersectionObserver<`u`}),[m]),{refs:z,elements:Ee,x:De,y:B,middlewareData:Oe,update:ke,placement:V,context:Ae,isPositioned:W,floatingStyles:je}=t({rootContext:_,open:g?v:void 0,placement:ue,middleware:Se,strategy:r,whileElementsMounted:g?void 0:(...e)=>It(...e,R),nodeId:x,externalTree:w}),{sideX:Me,sideY:Ne}=Oe.adaptiveOrigin||ln,Pe=W?r:`fixed`,Fe=I.useMemo(()=>{let e;return e=W?S?{position:Pe,[Me]:De,[Ne]:B}:{...je,position:Pe}:{position:Pe,top:0,left:0},e[hn]=`100vw`,e[gn]=`100vh`,W||(e.opacity=0),e},[S,Pe,Me,De,Ne,B,je,W]),Ie=I.useRef(null);T(()=>{if(!v)return;let e=te.current,t=typeof e==`function`?e():e,n=(xn(t)?t.current:t)||null;n!==Ie.current&&(z.setPositionReference(n),Ie.current=n)},[v,z,ee,te]),I.useEffect(()=>{if(!v)return;let e=te.current;typeof e!=`function`&&xn(e)&&e.current!==Ie.current&&(z.setPositionReference(e.current),Ie.current=e.current)},[v,z,ee,te]),I.useEffect(()=>{if(g&&v&&Ee.reference&&Ee.floating)return It(Ee.reference,Ee.floating,ke,R)},[g,v,Ee,ke,R]);let Le=H(V),Re=_n(i,Le,re),ze=U(V)||`center`,Be=!!Oe.hide?.referenceHidden;T(()=>{C&&v&&W&&(Le!==le||oe&&ze!==N)&&ae(V)},[C,oe,v,W,V,Le,ze,le,N]);let Ve=I.useMemo(()=>({position:`absolute`,top:Oe.arrow?.y,left:Oe.arrow?.x}),[Oe.arrow]),He=Oe.arrow?.centerOffset!==0;return I.useMemo(()=>({positionerStyles:Fe,arrowStyles:Ve,arrowRef:F,arrowUncentered:He,side:Re,align:ze,physicalSide:Le,anchorHidden:Be,refs:z,context:Ae,isPositioned:W,update:ke}),[Fe,Ve,F,He,Re,ze,Le,Be,z,Ae,W,ke])}function xn(e){return e!=null&&`current`in e}function Sn(e){return e===`starting`?j:A}function Cn(e,t,{styles:n,transitionStatus:r,props:i,refs:a,hidden:o,inert:s=!1}){let c={...n};return s&&(c.pointerEvents=`none`),d(`div`,e,{state:t,ref:a,props:[{role:`presentation`,hidden:o,style:c},Sn(r),i],stateAttributesMapping:k})}var wn=(0,I.forwardRef)(function({children:e,className:t,optional:n,required:r,...i},a){return(0,L.jsxs)(`label`,{...i,className:x(`label caps-label cursor-pointer justify-start gap-sm text-sm font-semibold text-base-content`,t),ref:a,children:[e,r?(0,L.jsx)(`span`,{"aria-hidden":`true`,className:`text-error`,children:`*`}):null,n&&!r?(0,L.jsx)(`span`,{className:`caps-label-optional`,children:`Optional`}):null]})}),Tn=(0,I.forwardRef)(function({children:e,className:t,...n},r){return(0,L.jsx)(`div`,{...n,className:x(`caps-input-group join flex w-full items-stretch [&>*]:join-item [&>*:first-child]:rounded-e-none [&>*:last-child]:rounded-s-none [&>*:not(:first-child):not(:last-child)]:rounded-none [&>.btn]:shrink-0 [&>.input]:min-w-0 [&>.input]:flex-1 [&>.select]:min-w-0 [&>.select]:flex-1`,t),ref:r,children:I.Children.map(e,e=>(0,I.isValidElement)(e)?(0,I.cloneElement)(e,{className:x(`join-item caps-input-group-control`,e.props.className)}):e)})}),En=(0,I.forwardRef)(function({className:e,...t},n){return(0,L.jsx)(`div`,{...t,className:x(`join-item flex items-center border border-base-300 bg-base-200 px-md text-sm text-base-content`,e),ref:n})});function Dn(e){let t=e.parentElement;if(!t||e.previousElementSibling===null)return 0;let n=getComputedStyle(t);if(!(n.display.includes(`grid`)||n.display.includes(`flex`)&&n.flexDirection.startsWith(`column`)))return 0;let r=Number.parseFloat(n.rowGap);return Number.isFinite(r)?r:0}(0,I.forwardRef)(function({show:e,appear:t=!1,children:n,className:i,...a},o){let s=(0,I.useRef)(null);(0,I.useImperativeHandle)(o,()=>s.current);let c=y(),[l,u]=(0,I.useState)(e),d=(0,I.useRef)(!0);return e&&!l&&u(!0),(0,I.useLayoutEffect)(()=>{let n=s.current,i=d.current;if(d.current=!1,!n||i&&!t)return;if(!r(n)){e||u(!1);return}let a=h(n),o=`translateY(${String(a.distance)}px)`,l=le(a,a.ease),f=n.getBoundingClientRect().height,p=Dn(n),m=(e,t)=>{n.style.overflow=`clip`;let r=e=>({height:`${String(e)}px`,marginBlockStart:`${String(e===0?-p:0)}px`}),i=n.animate([r(e),r(t)],{duration:a.normal,easing:l}),o=()=>{n.style.removeProperty(`overflow`)};return i.addEventListener(`finish`,o),i.addEventListener(`cancel`,o),i};if(e){let e=[n.animate([{opacity:0,transform:o},{opacity:1,transform:`none`}],{duration:a.normal,easing:l})];return!c&&f>0&&e.push(m(0,f)),()=>{for(let t of e)t.cancel()}}let g=n.animate([{opacity:1,transform:`none`},{opacity:0,transform:o}],{duration:a.fast,easing:le(a,a.easeExit),fill:`forwards`}),_=!c&&f>0?m(f,0):g;return _!==g&&_.effect?.updateTiming({fill:`forwards`}),_.addEventListener(`finish`,()=>{u(!1)}),()=>{g.cancel(),_.cancel()}},[e,t,c]),l?(0,L.jsx)(`div`,{...a,ref:s,className:x(`caps-presence`,i),"data-present":e,"aria-hidden":!e||void 0,children:n}):null});var On=(0,I.forwardRef)(function({open:e,children:t,className:n,...r},i){return(0,L.jsx)(`div`,{...r,ref:i,className:x(`caps-collapse`,n),"data-open":e,"aria-hidden":!e||void 0,children:(0,L.jsx)(`div`,{className:`caps-collapse-clip`,children:t})})});(0,I.forwardRef)(function({swapKey:e,anchor:t=`start`,children:n,className:i,...a},o){let s=(0,I.useRef)(null);(0,I.useImperativeHandle)(o,()=>s.current);let c=y(),[l,u]=(0,I.useState)({key:e,content:n}),[d,f]=(0,I.useState)([]);l.key===e?l.content!==n&&u({key:e,content:n}):(f([...d.filter(t=>t.key!==e&&t.key!==l.key),l]),u({key:e,content:n}));let p=(0,I.useRef)(null);return(0,I.useLayoutEffect)(()=>{let e=s.current;if(!e||!(`ResizeObserver`in globalThis))return;p.current=e.getBoundingClientRect();let t=new ResizeObserver(()=>{e.getAnimations().length===0&&(p.current=e.getBoundingClientRect())});return t.observe(e),()=>{t.disconnect()}},[]),(0,I.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=[...e.querySelectorAll(`:scope > [data-swap-leaving]`)],n=e.querySelector(`:scope > [data-swap-current]`);if(n===null||t.length===0)return;if(!r(e)){f([]);return}let i=p.current,a=e.getBoundingClientRect(),o=h(e),l=[n.animate([{opacity:0,filter:`blur(${String(o.blur)}px)`,transform:`translateY(${String(o.distance/2)}px)`},{opacity:1,filter:`blur(0px)`,transform:`none`}],{duration:o.normal,easing:le(o,o.ease)})];for(let e of t){let t=e.animate([{opacity:1,filter:`blur(0px)`,transform:`none`},{opacity:0,filter:`blur(${String(o.blur)}px)`,transform:`translateY(${String(-o.distance/2)}px)`}],{duration:o.fast,easing:le(o,o.easeExit),fill:`forwards`}),n=e.dataset.swapLeaving;t.onfinish=()=>{f(e=>e.filter(e=>e.key!==n))},l.push(t)}let u=i!==null&&(Math.abs(i.height-a.height)>.5||Math.abs(i.width-a.width)>.5);return!c&&u&&l.push(e.animate([{width:`${String(i.width)}px`,height:`${String(i.height)}px`},{width:`${String(a.width)}px`,height:`${String(a.height)}px`}],{duration:o.normal,easing:le(o,o.ease)})),()=>{for(let e of l)e.cancel()}},[e,c]),(0,L.jsx)(`div`,{...a,ref:s,className:x(`caps-swap`,i),"data-anchor":t,children:[...d.map(e=>(0,L.jsx)(`div`,{className:`caps-swap-layer`,"data-swap-leaving":e.key,"aria-hidden":`true`,children:e.content},e.key)),(0,L.jsx)(`div`,{className:`caps-swap-layer`,"data-swap-current":``,children:n},e)]})});function kn({children:e,...t}){let[n,r]=(0,I.useState)(e);return e&&e!==n&&r(e),(0,L.jsx)(On,{...t,className:x(`caps-field-error-reveal`,t.className),open:!!e,children:(0,L.jsx)(`div`,{className:`caps-field-error`,role:`alert`,"aria-hidden":!e,children:n})})}function An({children:e,divider:t=!0,error:n,layout:r=`end`,status:i,...a}){return(0,L.jsxs)(`footer`,{...a,className:x(`caps-form-footer`,a.className),"data-divider":t,"data-layout":r,children:[(0,L.jsx)(kn,{children:n}),(0,L.jsxs)(`div`,{className:`caps-form-footer-row`,children:[i?(0,L.jsx)(`div`,{className:`caps-form-footer-status`,role:`status`,children:i}):null,(0,L.jsx)(`div`,{className:`caps-form-footer-actions`,children:e})]})]})}var jn=(0,I.forwardRef)(function({busy:e=!1,children:t,className:n,layout:r,...i},a){return(0,L.jsx)(`form`,{...i,"aria-busy":e||void 0,className:x(`caps-form`,n),"data-layout":r,ref:a,children:(0,L.jsx)(`fieldset`,{className:`caps-form-body`,disabled:e,children:t})})}),Mn={2:`h2`,3:`h3`,4:`h4`},Nn=(0,I.forwardRef)(function({children:e,className:t,description:n,layout:r,level:i=3,title:a,...o},s){let c=(0,I.useId)(),l=Mn[i];return(0,L.jsxs)(`section`,{...o,"aria-labelledby":`${c}-title`,className:x(`caps-form-section`,t),"data-layout":r,ref:s,children:[(0,L.jsxs)(`header`,{className:`caps-form-section-copy`,children:[(0,L.jsx)(l,{className:`caps-form-section-title`,id:`${c}-title`,children:a}),n?(0,L.jsx)(`p`,{className:`caps-form-section-description`,children:n}):null]}),(0,L.jsx)(`div`,{className:`caps-form-section-fields`,children:e})]})}),Pn=(0,I.forwardRef)(function({children:e,className:t,description:n,error:r,icon:i,layout:a,legend:o,legendTitle:s,...c},l){let u=(0,I.useId)(),d=[n?`${u}-description`:c[`aria-describedby`],r?`${u}-error`:null].filter(Boolean).join(` `)||void 0;return(0,L.jsxs)(`fieldset`,{...c,"aria-describedby":d,"aria-invalid":r?!0:c[`aria-invalid`],className:x(`caps-fieldset`,t),"data-layout":a,ref:l,children:[(0,L.jsxs)(`legend`,{className:`caps-fieldset-legend`,title:s,children:[i?(0,L.jsx)(`span`,{className:`caps-field-icon`,"aria-hidden":`true`,children:i}):null,o]}),n?(0,L.jsx)(`p`,{className:`caps-fieldset-description`,id:`${u}-description`,children:n}):null,(0,L.jsx)(`div`,{className:`caps-fieldset-fields`,children:e}),r===void 0?null:(0,L.jsx)(kn,{id:`${u}-error`,children:r})]})});function Fn(e){let t=[];return I.Children.forEach(e.props.children,e=>{(0,I.isValidElement)(e)&&e.type!==En&&t.push(e)}),t[0]??null}var In=(0,I.forwardRef)(function({children:e,className:t,description:n,error:r,icon:i,label:a,labelTitle:o,optional:s,orientation:c=`vertical`,readout:l=!1,required:u,...d},f){let p=(0,I.useId)(),m=(0,I.isValidElement)(e)?e:null,h=m?.type===Tn,g=h?Fn(m):m,_=g?.props.id??p,v=`${_}-description`,y=`${_}-error`,b=[g?.props[`aria-describedby`],n?v:null,r?y:null].filter(Boolean).join(` `)||void 0,S=u===!0||g?.props.required,C=r?!0:g?.props[`aria-invalid`],w=u===!0||g?.props[`aria-required`],T={id:_};S!==void 0&&(T.required=S),b!==void 0&&(T[`aria-describedby`]=b),C!==void 0&&(T[`aria-invalid`]=C),w!==void 0&&(T[`aria-required`]=w);let E=m&&g&&!l?h?(0,I.cloneElement)(m,void 0,I.Children.map(m.props.children,e=>e===g?(0,I.cloneElement)(g,T):e)):(0,I.cloneElement)(m,T):e,D=a?(0,L.jsx)(wn,{htmlFor:l?void 0:_,title:o,className:c===`inline`?`font-normal`:void 0,...u===void 0?{}:{required:u},...s===void 0?{}:{optional:s},children:a}):null,O=a||n?(0,L.jsxs)(`div`,{className:`caps-field-copy`,children:[D,n?(0,L.jsx)(`p`,{className:`caps-field-description`,id:v,children:n}):null]}):null,k=i?(0,L.jsxs)(`div`,{className:`caps-field-lead`,children:[(0,L.jsx)(`span`,{className:`caps-field-icon`,"aria-hidden":`true`,children:i}),O]}):O;return(0,L.jsxs)(`div`,{...d,className:x(`caps-field`,t),"data-orientation":c,ref:f,children:[c===`horizontal`?(0,L.jsxs)(`div`,{className:`caps-field-row`,children:[k,E]}):c===`inline`?(0,L.jsxs)(`div`,{className:`caps-field-row`,children:[E,k]}):(0,L.jsxs)(L.Fragment,{children:[k,E]}),(0,L.jsx)(kn,{id:y,children:r})]})});function Ln(e){let t=String(e),n=t.indexOf(`.`);return n===-1?0:t.length-n-1}var Rn=`M 9.86 38.14 A 20 20 0 1 1 38.14 38.14`,zn=6,Bn=new Map([[`ArrowUp`,1],[`ArrowDown`,-1],[`PageUp`,10],[`PageDown`,-10]]),Vn=(0,I.forwardRef)(function({className:e,decrementLabel:t=`Decrease`,defaultValue:n=null,disabled:r,incrementLabel:i=`Increase`,invalid:a,max:o,min:s,onBlur:c,onKeyDown:l,onValueChange:u,step:d=1,unit:f,value:p,wrap:m=!1,...h},g){let[_,v]=(0,I.useState)(n),[y,b]=(0,I.useState)(null),S=p===void 0?_:p,C=Ln(d),w=e=>{let t=Number(e.toFixed(C));return s!==void 0&&t<s?s:o!==void 0&&t>o?o:t},T=e=>{let t=e===null?null:w(e);v(t),b(null),t!==S&&u?.(t)},E=()=>{if(y===null)return;let e=Number(y);T(y.trim()===``||!Number.isFinite(e)?null:e)},D=e=>{let t=(S??s??0)+e*d;if(m&&s!==void 0&&o!==void 0){if(t>o){T(s);return}if(t<s){T(o);return}}T(t)},O=s!==void 0&&S!==null&&S<=s,k=o!==void 0&&S!==null&&S>=o,A=r===!0,j=(0,I.useRef)(null),M=s!==void 0&&o!==void 0&&o>s?((S??s)-s)/(o-s):null,ee=e=>{A||(e.currentTarget.setPointerCapture(e.pointerId),j.current={y:e.clientY,value:S??s??0})},te=e=>{if(!j.current)return;let t=Math.trunc((j.current.y-e.clientY)/zn),n=w(j.current.value+t*d);n!==S&&T(n)},ne=()=>{j.current=null};return(0,L.jsxs)(`span`,{className:x(`caps-number-field`,e),"data-at-max":k||void 0,"data-at-min":O||void 0,"data-disabled":A||void 0,"data-wrap":m||void 0,children:[M===null?null:(0,L.jsxs)(`svg`,{className:`caps-number-field-dial`,viewBox:`0 0 48 48`,"aria-hidden":`true`,focusable:`false`,onPointerDown:ee,onPointerMove:te,onPointerUp:ne,onPointerCancel:ne,children:[(0,L.jsx)(`path`,{className:`caps-number-field-dial-track`,d:Rn,pathLength:100}),(0,L.jsx)(`path`,{className:`caps-number-field-dial-level`,d:Rn,pathLength:100,strokeDasharray:`${String(Math.max(.5,M*100))} 100`})]}),(0,L.jsx)(ae,{type:`button`,variant:`outline`,size:`icon`,className:`caps-number-field-decrement`,"aria-label":t,"aria-controls":h.id,tabIndex:-1,disabled:A||O&&!m,onClick:()=>{D(-1)},children:(0,L.jsx)(ye,{"aria-hidden":`true`})}),(0,L.jsxs)(`span`,{className:`caps-number-field-readout`,children:[(0,L.jsx)(`input`,{...h,"aria-invalid":a?!0:h[`aria-invalid`]===!1?void 0:h[`aria-invalid`],className:`input caps-input caps-number-field-input`,disabled:r,inputMode:h.inputMode??(C>0?`decimal`:`numeric`),max:o,min:s,onBlur:e=>{E(),c?.(e)},onChange:e=>{b(e.target.value)},onKeyDown:e=>{if(l?.(e),e.defaultPrevented)return;let t=Bn.get(e.key);t===void 0?e.key===`Home`&&s!==void 0?(e.preventDefault(),T(s)):e.key===`End`&&o!==void 0?(e.preventDefault(),T(o)):e.key===`Enter`&&E():(e.preventDefault(),D(t))},ref:g,step:d,type:`number`,value:y??(S===null?``:String(S))}),f?(0,L.jsx)(`span`,{className:`caps-number-field-unit`,"aria-hidden":`true`,children:f}):null]}),(0,L.jsx)(ae,{type:`button`,variant:`outline`,size:`icon`,className:`caps-number-field-increment`,"aria-label":i,"aria-controls":h.id,tabIndex:-1,disabled:A||k&&!m,onClick:()=>{D(1)},children:(0,L.jsx)(be,{"aria-hidden":`true`})})]})});function Hn({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 Un(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 Wn=[],Gn=0,{link:Kn,unlink:qn,propagate:Jn,checkDirty:Yn,shallowPropagate:Xn}=Hn({update(e){return e._update()},notify(e){Wn[Qn++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,er(e))}}),Zn=0,Qn=0,K,$n=0;function q(e){try{++$n,e()}finally{--$n||tr()}}function er(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=qn(n,e)}function tr(){if(!($n>0)){for(;Zn<Qn;){let e=Wn[Zn];Wn[Zn++]=void 0,e.notify()}Zn=0,Qn=0}}function nr(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 K!==void 0&&Kn(i,K,Gn),i._snapshot},subscribe(e){let t=Un(e),n={current:!1},r=rr(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=K,o=t?.compare??Object.is;if(n)K=i,++Gn,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{K=a,n&&(i.flags&=-5),er(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&Yn(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&Xn(e)}}else e&32&&(i.flags=e&-33);return K!==void 0&&Kn(i,K,Gn),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Jn(e),Xn(e),tr())}},i}function rr(e){let t=()=>{let t=K;K=n,++Gn,n.depsTail=void 0,n.flags=6;try{return e()}finally{K=t,n.flags&=-5,er(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&&Yn(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,er(this)}};return t(),n}var ir=class{constructor(e,t){this.atom=nr(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(Un(e))}},ar=class{constructor(e){this.atom=nr(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(Un(e))}};function or(e,t){return typeof e==`function`?new ar(e):t?new ir(e,t):new ir(e)}var sr=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 cr(e,t){return new sr(e,t).maybeExecute}var lr=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)}},J=new class extends lr{constructor(){super({pluginId:`form-devtools`,reconnectEveryMs:1e3})}};function ur(e,t){return typeof e==`function`?e(t):e}function dr(e,t){return yr(t).reduce((e,t)=>{if(e===null)return null;if(e!==void 0)return e[t]},e)}function fr(e,t,n){let r=yr(t);function i(e){if(!r.length)return ur(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 pr(e,t){let n=yr(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 mr=46,hr=91,gr=93,_r=48,vr=57;function yr(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)===hr),i=!0,a=-1;for(let o=r;o<=t;o++){let s=o<t?e.charCodeAt(o):-1;if(o===t||s===mr||s===hr||s===gr){let t=o-r;if(t>0){let a=i&&(t===1||e.charCodeAt(r)!==_r),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!==gr&&(a!==-1||s!==gr)&&(a!==s||s!==mr&&s!==hr)&&n.push(``);r=o+1,i=!0}else(s<_r||s>vr)&&(i=!1);a=s}return n.length||n.push(``),n}function br(e){return!(Array.isArray(e)&&e.length===0)}function xr(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 Sr(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 Cr=e=>!!e&&typeof e==`object`&&`fields`in e;function Y(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)||!Y(e[i],t[i]))return!1;return!0}var wr=({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},Tr=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:`field`}:e?{newErrorValue:e,newSource:`form`}:{newErrorValue:void 0,newSource:void 0};function X(e,t){return e==null?t:{...e,...t}}for(var Er=256,Dr=[],Or;Er--;)Dr[Er]=(Er+256).toString(16).substring(1);function kr(){let e=0,t,n=``;if(!Or||Er+16>256){for(Or=Array(256),e=256;e--;)Or[e]=256*Math.random()|0;e=0,Er=0}for(;e<16;e++)t=Or[Er+e],n+=e===6?Dr[t&15|64]:e===8?Dr[t&63|128]:Dr[t],e&1&&e>1&&e<11&&(n+=`-`);return Er++,n}var Ar=cr(e=>J.emit(`form-state`,{id:e.formId,state:e.store.state}),{wait:300});function jr(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]=jr(e[n]);return t}if(e instanceof Map){let t=new Map;return e.forEach((e,n)=>{t.set(n,jr(e))}),t}if(e instanceof Set){let t=new Set;return e.forEach(e=>{t.add(jr(e))}),t}let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=jr(e[n]));return t}function Mr(e,t){return t===e||t.startsWith(`${e}.`)||t.startsWith(`${e}[`)}var Z=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 Nr(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 Pr=(e,t)=>{let n=Nr(e,t);return{form:n,fields:n}},Fr={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:Pr(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:Pr(r.issues,e)}},Ir=e=>!!e&&`~standard`in e,Q={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{},_arrayVersion:0,_pendingValidationsCount:0};function Lr(e){function t(t){let n=e.getFieldMeta(t)??Q;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=()=>Q;return{bumpArrayVersion:t,handleArrayMove:n,handleArrayRemove:r,handleArraySwap:i,handleArrayInsert:a}}function Rr(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 zr=class{constructor(e){this.options={},this.fieldInfo={},this.formGroupApis=new Set,this.mount=()=>{let e=this.store.subscribe(()=>{Ar(this)}),t=J.on(`request-form-state`,e=>{e.payload.id===this._formId&&J.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}),n=J.on(`request-form-reset`,e=>{e.payload.id===this._formId&&this.reset()}),r=J.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(),J.emit(`form-unmounted`,{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});let{onMount:a}=this.options.validators||{};return J.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&&!Y(e.defaultValues,t.defaultValues)&&!this.state.isTouched,r=!Y(e.defaultState,t.defaultState)&&!this.state.isTouched;if(!(!n&&!r)){if(q(()=>{this.baseStore.setState(()=>Rr(Object.assign({},this.state,r?e.defaultState:{},n?{values:e.defaultValues}:{})))}),n){let e=Lr(this);for(let t of Object.keys(this.fieldInfo))Array.isArray(this.getFieldValue(t))&&e.bumpArrayVersion(t)}J.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=fr(t,e.instance.name,e.instance.options.defaultValue))}),Rr({...this.options.defaultState,values:t,fieldMetaBase:r})})},this.validateAllFields=async e=>{let t=[];return q(()=>{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 q(()=>{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=xr(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||Z}),r=!1,i={};return q(()=>{for(let e of n){if(!e.validate)continue;let{formError:n,fieldErrors:a}=Br(this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`},type:`validate`})),o=Vr(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)??Q,r=a?.[e],{newErrorValue:s,newSource:c}=wr({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[o]===`form`,previousErrorValue:t?.[o]});c===`form`&&(i[e]={...i[e],[o]:r}),t?.[o]!==s&&this.setFieldMeta(e,(e=Q)=>({...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=Vr(`submit`);this.state.errorMap?.[a]&&e!==`submit`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[a]:void 0}}));let o=Vr(`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=Sr(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||Z});this.state.isFormValidating||this.baseStore.setState(e=>({...e,isFormValidating:!0}));let r=[],i;for(let e of n){if(!e.validate)continue;let n=Vr(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}=Br(r);s&&(i=i?{...i,...s}:s);let c=Vr(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)??Q,r=i?.[e],{newErrorValue:a,newSource:o}=wr({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[c]===`form`,previousErrorValue:t?.[c]});t?.[c]!==a&&this.setFieldMeta(e,(e=Q)=>({...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})),q(()=>{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}),J.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}),J.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validate`,errors:this.state.errors});return}q(()=>{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}),q(()=>{this.baseStore.setState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),J.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),n()})}catch(e){throw this.baseStore.setState(e=>({...e,isSubmitSuccessful:!1})),J.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`inflight`,onError:e}),n(),e}},this.getFieldValue=e=>dr(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]:ur(t,n.fieldMetaBase[e])}}))},this.resetFieldMeta=e=>Object.keys(e).reduce((e,t)=>{let n=t;return e[n]=Q,e},{}),this.setFieldValue=(e,t,n)=>{let r=n?.dontUpdateMeta??!1,i=n?.dontRunListeners??!1,a=n?.dontValidate??!1;q(()=>{r||this.setFieldMeta(e,e=>({...e,isTouched:!0,isDirty:!0,errorMap:{...e?.errorMap,onMount:void 0}})),this.baseStore.setState(n=>({...n,values:fr(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=pr(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),Lr(this).bumpArrayVersion(e)},this.insertFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>[...e.slice(0,t),n,...e.slice(t)],X(r,{dontValidate:!0}));let i=r?.dontValidate??!1;i||await this.validateField(e,`change`),Lr(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),X(r,{dontValidate:!0})),Lr(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),X(n,{dontValidate:!0})),Lr(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 fr(fr(e,`${t}`,i),`${n}`,r)},X(r,{dontValidate:!0})),Lr(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},X(r,{dontValidate:!0})),Lr(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,[],X(t,{dontValidate:!0})),Lr(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=dr(this.options.defaultValues,e),i=n??r;return{...t,fieldMetaBase:{...t.fieldMetaBase,[e]:Q},values:i===void 0?t.values:fr(t.values,e,i)}})},this.setErrorMap=e=>{q(()=>{Object.entries(e).forEach(([e,t])=>{let n=e;if(Cr(t)){let{formError:e,fieldErrors:r}=Br(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=>Fr.validate({value:this.state.values,validationSource:`form`},e),this.parseValuesWithSchemaAsync=e=>Fr.validateAsync({value:this.state.values,validationSource:`form`},e),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=e?.formId??kr(),this._devtoolsSubmissionOverride=!1;let t=Rr({...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||!Cr(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=or(t);let n;this.fieldMetaDerived=or(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=dr(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=!br(u),f=!o.isDirty,p=Y(l,this.getFieldInfo(a)?.instance?.options.defaultValue??dr(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=or(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||!Mr(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&&Mr(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=or(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&&Cr(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&&Y(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 Ir(e.validate)?Fr[e.type](e.value,e.validate):e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function Br(e){return e?Cr(e)?{formError:Br(e.form).formError,fieldErrors:e.fields}:{formError:e}:{formError:void 0}}function Vr(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 Hr=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]:{...Q,isTouched:e.fieldMetaBase[this.name]?.isTouched??Q.isTouched,isBlurred:e.fieldMetaBase[this.name]?.isBlurred??Q.isBlurred,isDirty:e.fieldMetaBase[this.name]?.isDirty??Q.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&&(Y(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,X(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,X(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(e,t,n)=>{this.form.insertFieldValue(this.name,e,t,X(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(e,t,n)=>{this.form.replaceFieldValue(this.name,e,t,X(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(e,t)=>{this.form.removeFieldValue(this.name,e,X(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(e,t,n)=>{this.form.swapFieldValues(this.name,e,t,X(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(e,t,n)=>{this.form.moveFieldValues(this.name,e,t,X(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=e=>{this.form.clearFieldValues(this.name,X(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=xr(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||Z}),r=this.getLinkedFields(e).reduce((t,n)=>{let r=xr(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||Z});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),i=!1;q(()=>{let e=(e,n)=>{let r=Wr(n.cause),a=n.validate?Ur(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}=Tr({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=Wr(`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=Sr(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||Z}),r=await t,i=this.getLinkedFields(e).reduce((t,n)=>{let r=Sr(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||Z});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)));q(()=>{s&&this.startValidation();for(let e of c)e.startValidation()});let l=(e,t,n)=>{let i=Wr(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=Ur(a),c=r[e.name]?.[i],{newErrorValue:l,newSource:u}=Tr({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)),q(()=>{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=>Mr(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[Wr(e)]?.lastAbortController.abort();let t=[];for(let r of n)r.getInfo().validationMetaMap[Wr(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=>Fr.validate({value:this.state.value,validationSource:`field`},e),this.parseValueWithSchemaAsync=e=>Fr.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)Mr(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=or(e=>{this.form.store.get();let n=this.form.getFieldMeta(this.name)??{...Q,...t.defaultMeta},r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!Y(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 Ir(e.validate)?Fr[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 Ur(e){if(e)return e}function Wr(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 Gr(e){return{isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1}}function Kr(e){return{...Q,...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 qr=class e{constructor(t){this.options={},this.setFormGroupState=e=>{this.form.baseStore.setState(t=>{let n=t.formGroupStateBase[this.name]??Gr({});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&&(Y(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,{...Q,...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]??Gr({...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;Yr(t)&&(n=t.group,r=t.fields);let i=Jr(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]:Gr({})}})),this.fieldInfo.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,groupApi:this})}}},this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,X(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 Hr&&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&&Mr(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}=wr({newFormValidatorError:i,isPreviousErrorFromFormValidator:o?.errorSourceMap[e]===`form`,previousErrorValue:s});c&&(a=!0),(s!==c||o?.errorSourceMap[e]!==l)&&this.form.setFieldMeta(n,(t=Q)=>({...t,errorMap:{...t.errorMap,[e]:c},errorSourceMap:{...t.errorSourceMap,[e]:l}}))}return this._lastDistributedFieldNames[e]=r,a},this.validateSync=(t,n,r={})=>{let i=xr(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||Z}),a=(r.skipRelatedFieldValidation?[]:this.getRelatedFields()).reduce((e,n)=>{let r=xr(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||Z});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),o=!1;q(()=>{let t=(t,r)=>{let i=Zr(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&&Yr(s)&&(c=s.group,l=s.fields);let u=Jr(c),d=n[i],{newErrorValue:f,newSource:p}=Tr({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=Zr(`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=Sr(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||Z}),a=await n,o=r.skipRelatedFieldValidation?[]:this.getRelatedFields(),s=o.reduce((e,n)=>{let r=Sr(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||Z});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=Zr(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&&Yr(o)&&(l=o.group,u=o.fields);let d=Jr(l),f=a[t.name]?.[i],{newErrorValue:p,newSource:m}=Tr({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 q(()=>{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=>Mr(this.name,e)}),{hasErrored:r}=this.validateSync(e,n[this.name]??{},{skipRelatedFieldValidation:t?.skipRelatedFieldValidation});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[Zr(e)]?.lastAbortController.abort(),this.state.meta.errors;let i=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>Mr(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})),q(()=>{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}q(()=>{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}),q(()=>{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=or(e=>{this.form.formGroupMetaDerived.get(),this.form.baseStore.get();let n=this.form.getFormGroupMeta(this.name)??Kr(t.defaultMeta),r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!Y(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(Ir(e.validate)){let t=Fr[e.type](e.value,e.validate);return e.type===`validate`?Xr(t):t.then(Xr)}return e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function Jr(e){if(e)return e}function Yr(e){return!!e&&typeof e==`object`&&`fields`in e}function Xr(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 Zr(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 Qr(e,t){if(!t)return;let n=Object.assign({},e,{state:jr(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 q(()=>{Object.keys(r).length&&e.baseStore.setState(e=>({...e,...r})),n.state.errorMap!==e.state.errorMap&&e.setErrorMap(n.state.errorMap)}),n}var $r=C();function ei(e,t){return e===t}function $(e,t=e=>e,n){let r=n?.compare??ei,i=(0,I.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,I.useCallback)(()=>e.get(),[e]);return(0,$r.useSyncExternalStoreWithSelector)(i,a,a,t,r)}var ti=typeof window<`u`?I.useLayoutEffect:I.useEffect;function ni(e){let[t,n]=(0,I.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,I.useState)(()=>new Hr({...e})),a=r;(t.form!==e.form||t.name!==e.name)&&(a=new Hr({...e}),i(a),n({form:e.form,name:e.name}));let o=$(a.store,e.mode===`array`?e=>e.meta._arrayVersion||0:e=>e.value),s=$(a.store,e=>e.meta.isTouched),c=$(a.store,e=>e.meta.isBlurred),l=$(a.store,e=>e.meta.isDirty),u=$(a.store,e=>e.meta.errorMap),d=$(a.store,e=>e.meta.errorSourceMap),f=$(a.store,e=>e.meta.isValidating),p=(0,I.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 ti(a.mount,[a]),ti(()=>{a.update(e)}),p}var ri=(({children:e,...t})=>{let n=ni(t),r=(0,I.useMemo)(()=>ur(e,n),[e,n]);return(0,L.jsx)(L.Fragment,{children:r})});function ii(){return(0,I.useState)(()=>kr())[0]}var ai=I,oi=`18.3.1`.split(`.`)[0]===`17`?ii:ai.useId;function si(e){let[t,n]=(0,I.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,I.useState)(()=>new qr({...e}));(t.form!==e.form||t.name!==e.name)&&(i(new qr({...e})),n({form:e.form,name:e.name}));let a=$(r.store,e=>e.value),o=$(r.store,e=>e.meta.isTouched),s=$(r.store,e=>e.meta.isBlurred),c=$(r.store,e=>e.meta.isDirty),l=$(r.store,e=>e.meta.errorMap),u=$(r.store,e=>e.meta.errorSourceMap),d=$(r.store,e=>e.meta.isValidating),f=$(r.store,e=>e.meta.isSubmitting),p=$(r.store,e=>e.meta.isSubmitted),m=$(r.store,e=>e.meta.submissionAttempts),h=$(r.store,e=>e.meta.isSubmitSuccessful),g=$(r.store,e=>e.meta.canSubmit),_=$(r.store,e=>e.meta.isValid),v=$(r.store,e=>e.meta.isFieldsValid),y=$(r.store,e=>e.meta.isFieldsValidating),b=$(r.store,e=>e.meta.isGroupValid),x=(0,I.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 ti(r.mount,[r]),ti(()=>{r.update(e)}),x}var ci=(({children:e,...t})=>{let n=si(t),r=(0,I.useMemo)(()=>ur(e,n),[e,n]);return(0,L.jsx)(L.Fragment,{children:r})});function li({form:e,selector:t=e=>e,children:n}){let r=$(e.store,t);return(0,L.jsx)(L.Fragment,{children:ur(n,r)})}function ui(e){let t=oi(),[n,r]=(0,I.useState)(e?.formId),[i,a]=(0,I.useState)(()=>new zr({...e,formId:e?.formId??t}));if(n!==e?.formId){let n=e?.formId??t;a(new zr({...e,formId:n})),r(n)}let o=(0,I.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,L.jsx)(ri,{...e,form:i})},e.FormGroup=function(e){return(0,L.jsx)(ci,{...e,form:i})},e.Subscribe=function(e){return(0,L.jsx)(li,{form:i,selector:e.selector,children:e.children})},e},[i]);ti(i.mount,[]),ti(()=>{i.update(e)});let s=(0,I.useRef)(!1);return ti(()=>{s.current&&e?.transform&&Qr(i,e.transform)},[i,e?.transform]),ti(()=>{s.current=!0}),o}export{we as C,Ce as S,Xe as _,In as a,Ye as b,An as c,Tn as d,En as f,tn as g,yn as h,Y as i,Nn as l,Sn as m,ni as n,Pn as o,Cn as p,$ as r,jn as s,ui as t,Vn as u,Je as v,ve as w,Se as x,qe as y};
|