db-studio 1.14.0 → 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/web-dist/assets/{_pathlessLayout-wBh7gK9q.js → _pathlessLayout-BYQmoqT2.js} +6 -6
- package/dist/web-dist/assets/_pathlessLayout-CdSIARYp.js +1 -0
- package/dist/web-dist/assets/{_queryId-CZGDd4fs.js → _queryId-IoOxUaz6.js} +1 -1
- package/dist/web-dist/assets/{_table-j-6h6Om5.js → _table-BI9E6-Je.js} +1 -1
- package/dist/web-dist/assets/{_table-DZOIq7aF.js → _table-ClkqBjYZ.js} +1 -1
- package/dist/web-dist/assets/{badge-DiSuKlwP.js → badge-SEQODpjR.js} +1 -1
- package/dist/web-dist/assets/{browser-DdWTHJJW.js → browser-CHG4p052.js} +1 -1
- package/dist/web-dist/assets/{bundle-mjs-5mNXw8Uh.js → bundle-mjs-BZOM22--.js} +1 -1
- package/dist/web-dist/assets/code-editor-BIfiMFMb.js +9 -0
- package/dist/web-dist/assets/{database.store-DzuxpP71.js → database.store-OsasuLJl.js} +1 -1
- package/dist/web-dist/assets/{dist-Bcrd0PtF.js → dist-D_0esNxp.js} +1 -1
- package/dist/web-dist/assets/{format-cell-value-lejp1lDf.js → format-cell-value-D41tFXxV.js} +1 -1
- package/dist/web-dist/assets/{highlighted-body-OFNGDK62-Cb34z6at.js → highlighted-body-OFNGDK62-DBl3trdK.js} +1 -1
- package/dist/web-dist/assets/{icons-D6bNpzOL.js → icons-rRDRsZcq.js} +1 -1
- package/dist/web-dist/assets/index-Be5YdcX5.css +2 -0
- package/dist/web-dist/assets/index-CJ2YPwW4.js +36 -0
- package/dist/web-dist/assets/indexes-DMAVA8iJ.js +1 -0
- package/dist/web-dist/assets/logs-DCMuv22K.js +1 -0
- package/dist/web-dist/assets/{mermaid-GHXKKRXX-B5pqoNgJ.js → mermaid-GHXKKRXX-DJ7TvQxw.js} +1 -1
- package/dist/web-dist/assets/{middleware-CYbbS--7.js → middleware-Y6OdmOWR.js} +1 -1
- package/dist/web-dist/assets/{monaco-editor-C-DV5CL8.js → monaco-editor-BO3WVEVM.js} +280 -280
- package/dist/web-dist/assets/monaco-editor-IL9D_L0g.css +1 -0
- package/dist/web-dist/assets/{monitoring-DWzrlTkx.js → monitoring-BtlIcl3k.js} +1 -1
- package/dist/web-dist/assets/{overlay.store-TOgdd28d.js → overlay.store-DjYsesE7.js} +1 -1
- package/dist/web-dist/assets/{queries.store-Cul86O-l.js → queries.store-CxkLh1ra.js} +1 -1
- package/dist/web-dist/assets/{query-runner-BhGrHn5P.js → query-runner-keHo7IiI.js} +5 -5
- package/dist/web-dist/assets/{radix-ui-CtzftI1z.js → radix-ui-C1Z_SoKk.js} +1 -1
- package/dist/web-dist/assets/{react-B3nJmLdO.js → react-1gU4DcpZ.js} +1 -1
- package/dist/web-dist/assets/{react-dom-DOIt489g.js → react-dom-DkH0eaTq.js} +1 -1
- package/dist/web-dist/assets/{redis-value-B1T4ApeG.js → redis-value-BmLGJf9X.js} +1 -1
- package/dist/web-dist/assets/{rolldown-runtime-D2WZefnn.js → rolldown-runtime-DY1mqKjv.js} +1 -1
- package/dist/web-dist/assets/{runner-BI316iCf.js → runner-CvUPs6q4.js} +1 -1
- package/dist/web-dist/assets/schema-9nf0q_01.js +57 -0
- package/dist/web-dist/assets/schema-C-10JjXl.js +1 -0
- package/dist/web-dist/assets/table-C75Kr4aI.js +1 -0
- package/dist/web-dist/assets/tanstack-C3XvOIUf.js +11 -0
- package/dist/web-dist/assets/visualizer-CiiH2acP.js +1 -0
- package/dist/web-dist/index.html +19 -19
- package/package.json +2 -2
- package/dist/web-dist/assets/_pathlessLayout-BXxEoaJK.js +0 -1
- package/dist/web-dist/assets/code-editor-BXm3myTR.js +0 -9
- package/dist/web-dist/assets/index-B_H1M603.js +0 -36
- package/dist/web-dist/assets/index-DHb8byer.css +0 -2
- package/dist/web-dist/assets/indexes-DecPH1pX.js +0 -1
- package/dist/web-dist/assets/logs-CXbJheYV.js +0 -1
- package/dist/web-dist/assets/monaco-editor-DcHpHuJd.css +0 -1
- package/dist/web-dist/assets/schema-CwD_s_ox.js +0 -64
- package/dist/web-dist/assets/schema-D9V1P9K2.js +0 -1
- package/dist/web-dist/assets/table-DbvYpea0.js +0 -1
- package/dist/web-dist/assets/tanstack-DQKs7SF9.js +0 -11
- package/dist/web-dist/assets/visualizer-7aPZoUCc.js +0 -1
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{r as bi,t as tt}from"./rolldown-runtime-D2WZefnn.js";import{xt as Rs}from"./icons-D6bNpzOL.js";import{Ot as ca,kt as da}from"./radix-ui-CtzftI1z.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};e.SENTRY_RELEASE={id:"db-studio@1.14.0"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a872bcbc-08d9-46a5-87dd-56464b562b95",e._sentryDebugIdIdentifier="sentry-dbid-a872bcbc-08d9-46a5-87dd-56464b562b95")}catch{}})();var nt=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(){}},ha=class extends nt{#t;#e;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},Cs=new ha,fa={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},pa=class{#t=fa;#e=!1;setTimeoutProvider(e){this.#t=e}setTimeout(e,t){return this.#t.setTimeout(e,t)}clearTimeout(e){this.#t.clearTimeout(e)}setInterval(e,t){return this.#t.setInterval(e,t)}clearInterval(e){this.#t.clearInterval(e)}},ke=new pa;function ga(e){setTimeout(e,0)}var ma=typeof window>"u"||"Deno"in globalThis;function q(){}function va(e,t){return typeof e=="function"?e(t):e}function zn(e){return typeof e=="number"&&e>=0&&e!==1/0}function wi(e,t){return Math.max(e+(t||0)-Date.now(),0)}function be(e,t){return typeof e=="function"?e(t):e}function J(e,t){return typeof e=="function"?e(t):e}function Qs(e,t){const{type:n="all",exact:s,fetchStatus:r,predicate:i,queryKey:o,stale:a}=e;if(o){if(s){if(t.queryHash!==bs(o,t.options))return!1}else if(!vt(t.queryKey,o))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||r&&r!==t.state.fetchStatus||i&&!i(t))}function Ws(e,t){const{exact:n,status:s,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(De(t.options.mutationKey)!==De(i))return!1}else if(!vt(t.options.mutationKey,i))return!1}return!(s&&t.state.status!==s||r&&!r(t))}function bs(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>Vn(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function vt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>vt(e[n],t[n])):!1}var Sa=Object.prototype.hasOwnProperty;function Ei(e,t,n=0){if(e===t)return e;if(n>500)return t;const s=Js(e)&&Js(t);if(!s&&!(Vn(e)&&Vn(t)))return t;const r=(s?e:Object.keys(e)).length,i=s?t:Object.keys(t),o=i.length,a=s?new Array(o):{};let l=0;for(let u=0;u<o;u++){const c=s?u:i[u],h=e[c],d=t[c];if(h===d){a[c]=h,(s?u<r:Sa.call(e,c))&&l++;continue}if(h===null||d===null||typeof h!="object"||typeof d!="object"){a[c]=d;continue}const f=Ei(h,d,n+1);a[c]=f,f===h&&l++}return r===o&&l===r?e:a}function Yt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Js(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Vn(e){if(!Xs(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Xs(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Xs(e){return Object.prototype.toString.call(e)==="[object Object]"}function ya(e){return new Promise(t=>{ke.setTimeout(t,e)})}function qn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Ei(e,t):t}function Ia(e,t,n=0){const s=[...e,t];return n&&s.length>n?s.slice(1):s}function Ra(e,t,n=0){const s=[t,...e];return n&&s.length>n?s.slice(0,-1):s}var ws=Symbol();function _i(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ws?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Es(e,t){return typeof e=="function"?e(...t):!!e}function Ca(e,t,n){let s=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),s||(s=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),e}var St=(()=>{let e=()=>ma;return{isServer(){return e()},setIsServer(t){e=t}}})();function Kn(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),e(r)},n.reject=r=>{s({status:"rejected",reason:r}),t(r)},n}function Tf(e){return e.state.status==="success"}var ba=ga;function wa(){let e=[],t=0,n=a=>{a()},s=a=>{a()},r=ba;const i=a=>{t?e.push(a):r(()=>{n(a)})},o=()=>{const a=e;e=[],a.length&&r(()=>{s(()=>{a.forEach(l=>{n(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||o()}return l},batchCalls:a=>(...l)=>{i(()=>{a(...l)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{s=a},setScheduler:a=>{r=a}}}var H=wa(),Ea=class extends nt{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const 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.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#t}},Zt=new Ea;function _a(e){return Math.min(1e3*2**e,3e4)}function Ti(e){return(e??"online")==="online"?Zt.isOnline():!0}var Qn=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Ai(e){let t=!1,n=0,s;const r=Kn(),i=()=>r.status!=="pending",o=g=>{if(!i()){const m=new Qn(g);d(m),e.onCancel?.(m)}},a=()=>{t=!0},l=()=>{t=!1},u=()=>Cs.isFocused()&&(e.networkMode==="always"||Zt.isOnline())&&e.canRun(),c=()=>Ti(e.networkMode)&&e.canRun(),h=g=>{i()||(s?.(),r.resolve(g))},d=g=>{i()||(s?.(),r.reject(g))},f=()=>new Promise(g=>{s=m=>{(i()||u())&&g(m)},e.onPause?.()}).then(()=>{s=void 0,i()||e.onContinue?.()}),p=()=>{if(i())return;let g;const m=n===0?e.initialPromise:void 0;try{g=m??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(h).catch(v=>{if(i())return;const S=e.retry??(St.isServer()?0:3),C=e.retryDelay??_a,b=typeof C=="function"?C(n,v):C,w=S===!0||typeof S=="number"&&n<S||typeof S=="function"&&S(n,v);if(t||!w){d(v);return}n++,e.onFail?.(n,v),ya(b).then(()=>u()?void 0:f()).then(()=>{t?d(v):p()})})};return{promise:r,status:()=>r.status,cancel:o,continue:()=>(s?.(),r),cancelRetry:a,continueRetry:l,canStart:c,start:()=>(c()?p():f().then(p),r)}}var Mi=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),zn(this.gcTime)&&(this.#t=ke.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(St.isServer()?1/0:3e5))}clearGcTimeout(){this.#t!==void 0&&(ke.clearTimeout(this.#t),this.#t=void 0)}};function Ta(e){return{onFetch:(t,n)=>{const s=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let c=!1;const h=p=>{Ca(p,()=>t.signal,()=>c=!0)},d=_i(t.options,t.fetchOptions),f=async(p,g,m)=>{if(c)return Promise.reject(t.signal.reason);if(g==null&&p.pages.length)return Promise.resolve(p);const S=(()=>{const R={client:t.client,queryKey:t.queryKey,pageParam:g,direction:m?"backward":"forward",meta:t.options.meta};return h(R),R})(),C=await d(S),{maxPages:b}=t.options,w=m?Ra:Ia;return{pages:w(p.pages,C,b),pageParams:w(p.pageParams,g,b)}};if(r&&i.length){const p=r==="backward",g=p?Oi:Wn,m={pages:i,pageParams:o};a=await f(m,g(s,m),p)}else{const p=e??i.length;do{const g=l===0?o[0]??s.initialPageParam:Wn(s,a);if(l>0&&g==null)break;a=await f(a,g),l++}while(l<p)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function Wn(e,{pages:t,pageParams:n}){const s=t.length-1;return t.length>0?e.getNextPageParam(t[s],t,n[s],n):void 0}function Oi(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Aa(e,t){return t?Wn(e,t)!=null:!1}function Ma(e,t){return!t||!e.getPreviousPageParam?!1:Oi(e,t)!=null}var Oa=class extends Mi{#t;#e;#n;#s;#i;#r;#a;#l;constructor(e){super(),this.#l=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#s=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=Zs(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#t}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#a,...e},e?._type&&(this.#t=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Zs(this.options);t.data!==void 0&&(this.setState(Ys(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=qn(this.state.data,e,this.options);return this.#o({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#o({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#e}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>J(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ws||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>be(e.options.staleTime,this)==="static"):!1}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:!wi(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#l||this.#h()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#o({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const a=this.observers.find(l=>l.options.queryFn);a&&this.setOptions(a.options)}const n=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(this.#l=!0,n.signal)})},r=()=>{const a=_i(this.options,t),u=(()=>{const c={client:this.#i,queryKey:this.queryKey,meta:this.meta};return s(c),c})();return this.#l=!1,this.options.persister?this.options.persister(a,u,this):a(u)},o=(()=>{const a={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:r};return s(a),a})();(this.#t==="infinite"?Ta(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#o({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=Ai({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:a=>{a instanceof Qn&&a.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(a,l)=>{this.#o({type:"failed",failureCount:a,error:l})},onPause:()=>{this.#o({type:"pause"})},onContinue:()=>{this.#o({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0});try{const a=await this.#r.start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),this.#s.config.onSuccess?.(a,this),this.#s.config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof Qn){if(a.silent)return this.#r.promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw this.#o({type:"error",error:a}),this.#s.config.onError?.(a,this),this.#s.config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}#o(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...xi(n.data,this.options),fetchMeta:e.meta??null};case"success":const s={...n,...Ys(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?s:void 0,s;case"error":const r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),H.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function xi(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ti(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Ys(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Zs(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,s=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Pi=class extends nt{constructor(e,t){super(),this.options=t,this.#t=e,this.#l=null,this.#a=Kn(),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#s=void 0;#i;#r;#a;#l;#h;#o;#u;#f;#d;#p;#g=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),er(this.#e,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Jn(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Jn(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#I(),this.#R(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof J(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#C(),this.#e.setOptions(this.options),t._defaulted&&!Yt(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const s=this.hasListeners();s&&tr(this.#e,n,this.options,t)&&this.#m(),this.updateResult(),s&&(this.#e!==n||J(this.options.enabled,this.#e)!==J(t.enabled,this.#e)||be(this.options.staleTime,this.#e)!==be(t.staleTime,this.#e))&&this.#c();const r=this.#v();s&&(this.#e!==n||J(this.options.enabled,this.#e)!==J(t.enabled,this.#e)||r!==this.#p)&&this.#S(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return Pa(this,n)&&(this.#s=n,this.#r=this.options,this.#i=this.#e.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,s)=>(this.trackProp(s),t?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#a.status==="pending"&&this.#a.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,s))})}trackProp(e){this.#g.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#m(e){this.#C();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(q)),t}#c(){this.#I();const e=be(this.options.staleTime,this.#e);if(St.isServer()||this.#s.isStale||!zn(e))return;const t=wi(this.#s.dataUpdatedAt,e)+1;this.#f=ke.setTimeout(()=>{this.#s.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#S(e){this.#R(),this.#p=e,!(St.isServer()||J(this.options.enabled,this.#e)===!1||!zn(this.#p)||this.#p===0)&&(this.#d=ke.setInterval(()=>{(this.options.refetchIntervalInBackground||Cs.isFocused())&&this.#m()},this.#p))}#y(){this.#c(),this.#S(this.#v())}#I(){this.#f!==void 0&&(ke.clearTimeout(this.#f),this.#f=void 0)}#R(){this.#d!==void 0&&(ke.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,s=this.options,r=this.#s,i=this.#i,o=this.#r,a=e!==n?e.state:this.#n,{state:l}=e;let u={...l},c=!1,h;if(t._optimisticResults){const R=this.hasListeners(),y=!R&&er(e,t),_=R&&tr(e,n,t,s);(y||_)&&(u={...u,...xi(l.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:d,errorUpdatedAt:f,status:p}=u;h=u.data;let g=!1;if(t.placeholderData!==void 0&&h===void 0&&p==="pending"){let R;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(R=r.data,g=!0):R=typeof t.placeholderData=="function"?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,R!==void 0&&(p="success",h=qn(r?.data,R,t),c=!0)}if(t.select&&h!==void 0&&!g)if(r&&h===i?.data&&t.select===this.#h)h=this.#o;else try{this.#h=t.select,h=t.select(h),h=qn(r?.data,h,t),this.#o=h,this.#l=null}catch(R){this.#l=R}this.#l&&(d=this.#l,h=this.#o,f=Date.now(),p="error");const m=u.fetchStatus==="fetching",v=p==="pending",S=p==="error",C=v&&m,b=h!==void 0,w={status:p,fetchStatus:u.fetchStatus,isPending:v,isSuccess:p==="success",isError:S,isInitialLoading:C,isLoading:C,data:h,dataUpdatedAt:u.dataUpdatedAt,error:d,errorUpdatedAt:f,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>a.dataUpdateCount||u.errorUpdateCount>a.errorUpdateCount,isFetching:m,isRefetching:m&&!v,isLoadingError:S&&!b,isPaused:u.fetchStatus==="paused",isPlaceholderData:c,isRefetchError:S&&b,isStale:_s(e,t),refetch:this.refetch,promise:this.#a,isEnabled:J(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const R=w.data!==void 0,y=w.status==="error"&&!R,_=M=>{y?M.reject(w.error):R&&M.resolve(w.data)},O=()=>{const M=this.#a=w.promise=Kn();_(M)},T=this.#a;switch(T.status){case"pending":e.queryHash===n.queryHash&&_(T);break;case"fulfilled":(y||w.data!==T.value)&&O();break;case"rejected":(!y||w.error!==T.reason)&&O()}}return w}updateResult(){const e=this.#s,t=this.createResult(this.#e,this.options);if(this.#i=this.#e.state,this.#r=this.options,this.#i.data!==void 0&&(this.#u=this.#e),Yt(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,r=typeof s=="function"?s():s;if(r==="all"||!r&&!this.#g.size)return!0;const i=new Set(r??this.#g);return this.options.throwOnError&&i.add("error"),Object.keys(this.#s).some(o=>{const a=o;return this.#s[a]!==e[a]&&i.has(a)})};this.#b({listeners:n()})}#C(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#b(e){H.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function xa(e,t){return J(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&J(t.retryOnMount,e)===!1)}function er(e,t){return xa(e,t)||e.state.data!==void 0&&Jn(e,t,t.refetchOnMount)}function Jn(e,t,n){if(J(t.enabled,e)!==!1&&be(t.staleTime,e)!=="static"){const s=typeof n=="function"?n(e):n;return s==="always"||s!==!1&&_s(e,t)}return!1}function tr(e,t,n,s){return(e!==t||J(s.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&_s(e,n)}function _s(e,t){return J(t.enabled,e)!==!1&&e.isStaleByTime(be(t.staleTime,e))}function Pa(e,t){return!Yt(e.getCurrentResult(),t)}var ka=class extends Pi{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,s=super.createResult(e,t),{isFetching:r,isRefetching:i,isError:o,isRefetchError:a}=s,l=n.fetchMeta?.fetchMore?.direction,u=o&&l==="forward",c=r&&l==="forward",h=o&&l==="backward",d=r&&l==="backward";return{...s,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Aa(t,n.data),hasPreviousPage:Ma(t,n.data),isFetchNextPageError:u,isFetchingNextPage:c,isFetchPreviousPageError:h,isFetchingPreviousPage:d,isRefetchError:a&&!u&&!h,isRefetching:i&&!c&&!d}}},Fa=class extends Mi{#t;#e;#n;#s;constructor(e){super(),this.#t=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#e=[],this.state=e.state||ki(),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.#e.includes(e)||(this.#e.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#i({type:"continue"})},n={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=Ai({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(i,o)=>{this.#i({type:"failed",failureCount:i,error:o})},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)});const s=this.state.status==="pending",r=!this.#s.canStart();try{if(s)t();else{this.#i({type:"pending",variables:e,isPaused:r}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const o=await this.options.onMutate?.(e,n);o!==this.state.context&&this.#i({type:"pending",context:o,variables:e,isPaused:r})}const i=await this.#s.start();return await this.#n.config.onSuccess?.(i,e,this.state.context,this,n),await this.options.onSuccess?.(i,e,this.state.context,n),await this.#n.config.onSettled?.(i,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(i,null,e,this.state.context,n),this.#i({type:"success",data:i}),i}catch(i){try{await this.#n.config.onError?.(i,e,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onError?.(i,e,this.state.context,n)}catch(o){Promise.reject(o)}try{await this.#n.config.onSettled?.(void 0,i,this.state.variables,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,i,e,this.state.context,n)}catch(o){Promise.reject(o)}throw this.#i({type:"error",error:i}),i}finally{this.#n.runNext(this)}}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,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{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),H.batch(()=>{this.#e.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function ki(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var La=class extends nt{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const s=new Fa({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(s),s}add(e){this.#t.add(e);const t=Ot(e);if(typeof t=="string"){const n=this.#e.get(t);n?n.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=Ot(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const s=n.indexOf(e);s!==-1&&n.splice(s,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ot(e);if(typeof t=="string"){const n=this.#e.get(t)?.find(s=>s.state.status==="pending");return!n||n===e}else return!0}runNext(e){const t=Ot(e);return typeof t=="string"?this.#e.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){H.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Ws(t,n))}findAll(e={}){return this.getAll().filter(t=>Ws(e,t))}notify(e){H.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return H.batch(()=>Promise.all(e.map(t=>t.continue().catch(q))))}};function Ot(e){return e.options.scope?.id}var Na=class extends nt{#t;#e=void 0;#n;#s;constructor(e,t){super(),this.#t=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#t.defaultMutationOptions(e),Yt(this.options,t)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&De(t.mutationKey)!==De(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#r(e)}getCurrentResult(){return this.#e}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#r()}mutate(e,t){return this.#s=t,this.#n?.removeObserver(this),this.#n=this.#t.getMutationCache().build(this.#t,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){const e=this.#n?.state??ki();this.#e={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#r(e){H.batch(()=>{if(this.#s&&this.hasListeners()){const t=this.#e.variables,n=this.#e.context,s={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#s.onSuccess?.(e.data,t,n,s)}catch(r){Promise.reject(r)}try{this.#s.onSettled?.(e.data,null,t,n,s)}catch(r){Promise.reject(r)}}else if(e?.type==="error"){try{this.#s.onError?.(e.error,t,n,s)}catch(r){Promise.reject(r)}try{this.#s.onSettled?.(void 0,e.error,t,n,s)}catch(r){Promise.reject(r)}}}this.listeners.forEach(t=>{t(this.#e)})})}},Da=class extends nt{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const s=t.queryKey,r=t.queryHash??bs(s,t);let i=this.get(r);return i||(i=new Oa({client:e,queryKey:s,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(s)}),this.add(i)),i}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){H.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Qs(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Qs(e,n)):t}notify(e){H.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){H.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){H.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Af=class{#t;#e;#n;#s;#i;#r;#a;#l;constructor(e={}){this.#t=e.queryCache||new Da,this.#e=e.mutationCache||new La,this.#n=e.defaultOptions||{},this.#s=new Map,this.#i=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#a=Cs.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#l=Zt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#a?.(),this.#a=void 0,this.#l?.(),this.#l=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),s=n.state.data;return s===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(be(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(s))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(e,t,n){const s=this.defaultQueryOptions({queryKey:e}),r=this.#t.get(s.queryHash)?.state.data,i=va(t,r);if(i!==void 0)return this.#t.build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return H.batch(()=>this.#t.findAll(e).map(({queryKey:s})=>[s,this.setQueryData(s,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;H.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return H.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},s=H.batch(()=>this.#t.findAll(e).map(r=>r.cancel(n)));return Promise.all(s).then(q).catch(q)}invalidateQueries(e,t={}){return H.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},s=H.batch(()=>this.#t.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(q)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(be(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(q).catch(q)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Zt.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(s=>{vt(e,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#i.values()],n={};return t.forEach(s=>{vt(e,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=bs(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===ws&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},I=bi(Rs(),1),L=da(),Fi=I.createContext(void 0),Li=e=>{const t=I.useContext(Fi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Mf=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,L.jsx)(Fi.Provider,{value:e,children:t})),Ni=I.createContext(!1),ja=()=>I.useContext(Ni),Of=Ni.Provider;function Ga(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var $a=I.createContext(Ga()),Ba=()=>I.useContext($a),Ua=(e,t,n)=>{const s=n?.state.error&&typeof e.throwOnError=="function"?Es(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||s)&&(t.isReset()||(e.retryOnMount=!1))},Ha=e=>{I.useEffect(()=>{e.clearReset()},[e])},za=({result:e,errorResetBoundary:t,throwOnError:n,query:s,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&s&&(r&&e.data===void 0||Es(n,[e.error,s])),Va=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),s=e.staleTime;e.staleTime=typeof s=="function"?(...r)=>n(s(...r)):n(s),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},qa=(e,t)=>e.isLoading&&e.isFetching&&!t,Ka=(e,t)=>e?.suspense&&t.isPending,nr=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Di(e,t,n){const s=ja(),r=Ba(),i=Li(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const a=i.getQueryCache().get(o.queryHash);o._optimisticResults=s?"isRestoring":"optimistic",Va(o),Ua(o,r,a),Ha(r);const l=!i.getQueryCache().get(o.queryHash),[u]=I.useState(()=>new t(i,o)),c=u.getOptimisticResult(o),h=!s&&e.subscribed!==!1;if(I.useSyncExternalStore(I.useCallback(d=>{const f=h?u.subscribe(H.batchCalls(d)):q;return u.updateResult(),f},[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),I.useEffect(()=>{u.setOptions(o)},[o,u]),Ka(o,c))throw nr(o,u,r);if(za({result:c,errorResetBoundary:r,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw c.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,c),o.experimental_prefetchInRender&&!St.isServer()&&qa(c,s)&&(l?nr(o,u,r):a?.promise)?.catch(q).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?c:u.trackResult(c)}function xf(e,t){return Di(e,Pi,t)}function Pf(e,t){const n=Li(t),[s]=I.useState(()=>new Na(n,e));I.useEffect(()=>{s.setOptions(e)},[s,e]);const r=I.useSyncExternalStore(I.useCallback(o=>s.subscribe(H.batchCalls(o)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),i=I.useCallback((o,a)=>{s.mutate(o,a).catch(q)},[s]);if(r.error&&Es(s.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:i,mutateAsync:r.mutate}}function kf(e,t){return Di(e,ka,t)}var sr=I.use,Ts=I.useLayoutEffect;function _e(e){return e[e.length-1]}function ji(e,t){return typeof e=="function"?e(t):e}var As=Object.prototype.hasOwnProperty;function Gi(e){for(const t in e)if(As.call(e,t))return!0;return!1}var Kt=()=>Object.create(null),Ke=(e,t)=>we(e,t,!0);function we(e,t,n,s=0){if(e===t)return e;if(s++>500)return t;const r=Array.isArray(e)&&Array.isArray(t);if(!r&&!(en(e)&&en(t)))return t;const i=Object.keys(e),o=i.length,a=Object.keys(t),l=a.length;if(r?o!==e.length||l!==t.length||o&&_e(i)!==`${o-1}`||l&&_e(a)!==`${l-1}`:o!==Object.getOwnPropertyNames(e).length||l!==Object.getOwnPropertyNames(t).length||Object.getOwnPropertySymbols(t).length)return t;let u=0,c,h,d;if(r){for(;u<l&&(d=u,h=e[d],c=t[d],c=h===c?h:typeof h=="object"?we(h,c,n,s):c,c===h);u++);if(u===l&&o===l)return e}else{let p=o===l,g=!0;for(;u<l;u++){d=a[u],h=e[d];const m=t[d];c=h===m?h:typeof h=="object"?we(h,m,n,s):m,p&&=c===h&&(i[u]===d||As.call(e,d)),g&&=Object.is(c,m),i[u]=c}if(p)return Object.getOwnPropertySymbols(e).length?t:e;if(g)return t}const f=r?a.fill(0):n?Kt():{};for(let p=0;p<l;p++)d=r?p:a[p],r?(h=e[d],p>u&&(c=t[d],c=h===c?h:typeof h=="object"?we(h,c,n,s):c),f[d]=p<u?h:c):f[d]=i[p];return f}function en(e){return!e||typeof e!="object"?!1:(Object.getPrototypeOf(e)?.constructor??Object)===Object}function ve(e,t,n,s){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++){const o=e[r],a=t[r];if(o!==a&&!ve(o,a,n,s))return!1}return!0}if(en(e)&&en(t)){if(n){for(const i in t)if((s||t[i]!==void 0)&&!ve(e[i],t[i],n,s))return!1;return!0}let r=0;if(s)r=Object.keys(e).length;else for(const i in e)e[i]!==void 0&&r++;for(const i in t)if((s||t[i]!==void 0)&&(r--===0||!ve(e[i],t[i],n,s)))return!1;return r===0}return!1}function Qa(e){return typeof e?.message!="string"?!1:e.message.startsWith("Failed to fetch dynamically imported module")||e.message.startsWith("error loading dynamically imported module")||e.message.startsWith("Importing a module script failed")}var Wa=/[\x00-\x1f\x7f"<>`{}]/g;function Ja(e){return e.replace(Wa,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function rr(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,n=>{try{return decodeURI(n)}catch{return n}})}return Ja(t)}var Xa=["http:","https:","mailto:","tel:"];function yt(e){if(e[0]!=="/"&&e.includes(":"))return/^[\x00-\x20]*([a-z][a-z\d+.\t\n\r-]*:)/i.exec(e)?.[1]?.replace(/[\t\n\r]/g,"").toLowerCase()}var $i=/^[\x00-\x20]*[\\/][\t\n\r]*[\\/]/;function Bi(e,t){if(!e)return!1;if($i.test(e))return!0;const n=yt(e);return n?!t.has(n):!1}function at(e){if(!e)return e;let t=e;if(/[%\\\x00-\x1f\x7f]/.test(e)){const n=/%25|%5C/gi;let s=0,r;for(t="";(r=n.exec(e))!==null;)t+=rr(e.slice(s,r.index))+r[0],s=n.lastIndex;t+=rr(s?e.slice(s):e)}return t}function Ya(e){return/[\s\u0080-\uFFFF]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function Za(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Ms(){throw new Error("Invariant failed")}function Ye(e){return e.replace(/\/{2,}/g,"/")}function Ui(e){return e==="/"?e:e.replace(/^\/+/,"")}function de(e){const t=e.length;return t>1&&e[t-1]==="/"?e.replace(/\/+$/,""):e}function Hi(e){return de(Ui(e))}function ir(e,t){return e?.endsWith("/")&&e!=="/"&&e!==`${t}/`?e.slice(0,-1):e}function or(e,t,n="never",s){if(t.includes("//")&&(t=Ye(t)),t.startsWith("/"))return t.length===1||n==="preserve"?t:n==="always"?t.endsWith("/")?t:`${t}/`:t.endsWith("/")?t.slice(0,-1):t;const r=t===".";let i;if(s){i=r?e:e+"\0"+t;const u=s.get(i);if(u)return u}let o;if(r)o=e.split("/");else{for(e.includes("//")&&(e=Ye(e)),o=e.split("/");o.length>1&&_e(o)==="";)o.pop();const u=t.split("/");for(let c=0,h=u.length;c<h;c++){const d=u[c];d===""?c?c===h-1&&o.push(d):o=[d]:d===".."?o.length>1?o.pop():o=[""]:d==="."||o.push(d)}}o.length>1&&(_e(o)===""?n==="never"&&o.pop():n==="always"&&o.push(""));const a=o.join("/"),l=(r?Ye(a):a)||"/";return i&&s&&s.set(i,l),l}function el(e){const t=new Map(e.map(s=>[encodeURIComponent(s),s])),n=new RegExp([...t.keys()].join("|").replace(/[.*()]/g,"\\$&"),"g");return s=>s.replace(n,r=>t.get(r)??r)}function tl(e){return e==null||e===""}function nl(e,t,n){if(typeof t!="string")return""+(t??void 0);const s=e==="_splat";if(s&&(!t||/^[a-zA-Z0-9\-._~!/]*$/.test(t)))return t;let r=encodeURIComponent(t);return s&&(r=r.replaceAll("%2F","/")),n?n(r):r}function ar(e,t,n,s,r){const i=e.endsWith("/")?"/":"";let o="";for(const a of t){if(typeof a=="string"){o+=a;continue}const[l,u,c,h]=a,d=l===2,f=d&&h!==void 0?h+i:h;let p=n[u];if(!(l===3&&p==null)){if(r&&(r[u]=p,d&&(r["*"]=p)),d&&tl(p)){if(c==="/"&&!f)continue;p=""}o+=c+nl(u,p,s)+(f||"")}}return o+i||"/"}function et(e){return e?.isNotFound===!0}function sl(){try{return sessionStorage}catch{return}}var rl="tsr-scroll-restoration-v1_3",zi=sl();function il(){try{return JSON.parse(zi?.getItem("tsr-scroll-restoration-v1_3")||"{}")}catch{return{}}}function ol(){try{zi?.setItem(rl,JSON.stringify(Je))}catch{}}var Je=il(),lr="data-scroll-restoration-id",al=e=>e.state.__TSR_key||e.href;function ll(e){const t=e.getAttribute(lr);if(t)return`[${lr}="${t}"]`;let n="",s=e,r;for(;r=s.parentNode;){let i=1,o=s;for(;o=o.previousElementSibling;)i++;const a=`${s.localName}:nth-child(${i})`;n=n?`${a} > ${n}`:a,s=r}return n}var xt=!1,Qt="window";function Xn(e){try{return typeof e=="function"?e():document.querySelector(e)}catch{}}function ur(e){const t=new Set;for(const n of e){if(n===Qt)continue;const s=Xn(n);s&&t.add(s)}return t}function ul(e,t){const n=t??e.options.scrollRestoration,s=e._scroll;n&&(s.restoring=!0);const r=e.options.getScrollRestorationKey||al,i=new Set,o=a=>{const l=Je[a]||={};for(const u of i)u===document?l[Qt]={scrollX,scrollY}:u.isConnected&&(l[ll(u)]={scrollX:u.scrollLeft,scrollY:u.scrollTop})};n&&!s.restoration&&(s.restoration=!0,xt=!1,history.scrollRestoration="manual",document.addEventListener("scroll",a=>{xt||i.add(a.target)},!0),e.subscribe("onBeforeLoad",a=>{a.fromLocation&&o(r(a.fromLocation)),i.clear()}),addEventListener("pagehide",()=>{o(r(e.stores.resolvedLocation.get()??e.stores.location.get())),ol()})),!s.reset&&(s.reset=!0,e.subscribe("onRendered",a=>{const l=e.options.scrollRestorationBehavior,u=e.options.scrollToTopSelectors,c=s.next,h=s.hash;let d;if(i.clear(),s.next=!0,s.hash=!1,typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation}))return;const f=r(a.toLocation),p=a.fromLocation&&r(a.fromLocation);if(s.restoring&&p&&p!==f){const g=Je[p];if(g){let m=Je[f];for(const v in g){if(v===Qt){if(c)continue}else{const S=Xn(v);if(!S||c&&u&&(d??=ur(u),d.has(S)))continue}m||(m=Je[f]={}),m[v]??=g[v]}}}xt=!0;try{const g=a.toLocation.hash,m=a.toLocation.state.__hashScrollIntoViewOptions??!0;let v=!1;if(c){!g&&u&&(d??=ur(u));const S=g&&m&&h,C=s.restoring?Je[f]:void 0;if(C)for(const b in C){const{scrollX:w,scrollY:R}=C[b];if(b===Qt){if(S)continue;scrollTo({top:R,left:w,behavior:l}),v=!0}else{const y=Xn(b);y&&(y.scrollLeft=w,y.scrollTop=R,d?.delete(y))}}if(!g){const b={top:0,left:0,behavior:l};if(v||scrollTo(b),d)for(const w of d)w.scrollTo(b)}}!v&&g&&m&&document.getElementById(g)?.scrollIntoView(m)}finally{xt=!1}}))}function cl(e,t=String){let n;for(const s in e){const r=e[s];r!==void 0&&(n||=new URLSearchParams).set(s,t(r))}return n?n.toString():""}function Cn(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function dl(e){const t=new URLSearchParams(e),n=Object.create(null);for(const[s,r]of t.entries()){const i=n[s];i==null?n[s]=Cn(r):Array.isArray(i)?i.push(Cn(r)):n[s]=[i,Cn(r)]}return n}var Vi=/^(?:\s|["[{\d-]|fa|nu|tr)/,hl=pl(JSON.parse),fl=gl(JSON.stringify,JSON.parse);function pl(e){const t=e===JSON.parse;return n=>{n[0]==="?"&&(n=n.substring(1));const s=dl(n);for(const r in s){const i=s[r];if(typeof i=="string"){if(t&&!Vi.test(i))continue;try{s[r]=e(i)}catch{}}}return s}}function gl(e,t){const n=t===JSON.parse;function s(r){if(r&&typeof r=="object")try{return e(r)}catch{}else if(t&&typeof r=="string"){if(n&&!Vi.test(r))return r;try{return t(r),e(r)}catch{}}return r}return r=>{const i=cl(r,s);return i?`?${i}`:""}}var ft="__root__";function ml(e){e.statusCode=e.statusCode||e.code||307;const t=new Headers(e.headers);e.href&&t.get("Location")===null&&t.set("Location",e.href);const n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function qi(e){return e instanceof Response&&!!e.options}function tn(e){const t=new Map;let n,s;return{get(r){const i=t.get(r);if(i)return i.visited=!0,i.value},set(r,i){const o=t.get(r);if(o){o.value=i;return}if(t.size>=e){let l=n?.next().value;for(;!l||l.visited;)l?l.visited=!1:n=t.values(),l=n.next().value;l===s&&(n=void 0),t.delete(l.key)}const a={key:r,value:i,visited:!1};s=a,t.set(r,a)},clear(){t.clear(),n=void 0,s=void 0}}}var Re=4,Ki=5;function vl(e){const t=e.names;if(t)return t;const n=[];for(const s of e)typeof s!="string"&&n.push(s[1]);return e.names=n}function Sl(e,t,n){const s=e.substring(t,n);if(s.charCodeAt(0)===36)return s.length===1?[2,"_splat","",void 0]:[1,s.substring(1),"",""];const r=s.indexOf("{");if(r>=0){const i=s.indexOf("}",r),o=s.charCodeAt(r+1)===45,a=r+(o?3:2);if(i>=0&&s.charCodeAt(a-1)===36&&(!o||a<i)){const l=s.substring(a,i);return[o?3:l?1:2,l||"_splat",s.substring(0,r),e.substring(t+i+1,l?n:e.length)]}}return s}function It(e,t,n,s,r,i){let o=n;const a=t.fullPath??t.from,l=t.options,u=a.length,c=a.endsWith("/")?u-1:u,h=l?.caseSensitive??e,d=l?.params?.parse??l?.parseParams;let f,p=i?n-1:0;if(!s||a.includes("$")){f=i?.slice()??[];const v=_e(f);v&&typeof v!="string"&&v[0]===2&&(f[f.length-1]=[v[0],v[1],v[2],v[3]===void 0?void 0:v[3]+a.substring(n-(a[n-2]==="/"?2:1),c)],p=u)}for(;o<u;){const v=o,S=a.indexOf("/",v);let C=S===-1?u:S;const b=Sl(a,v,C);o=C+1;let w;if(typeof b=="string"){if(!s)continue;let R=b,y;h?y=s.static??=new Map:(R=b.toLowerCase(),y=s.staticInsensitive??=new Map);const _=y.get(R);if(_)w=_;else{const O=Fe(s);w=O,y.set(R,O)}}else{const R=b[0];let y=b[2],_=b[3]??"";if(R===2&&(C=u,o=C+1),f&&p<C&&(p<v-1&&f.push(a.substring(p,v-1)),b[2]="/"+y,R===2&&b[3]!==void 0&&c<u&&(b[3]=_.slice(0,-1)),f.push(b),p=C),!s)continue;const O=h&&!!(y||_);h||(y=y.toLowerCase(),_=_.toLowerCase());const T=R===1?s.dynamic??=[]:R===3?s.optional??=[]:s.wildcard??=[],M=R!==2&&!d&&T.find(A=>!A.parse&&A.caseSensitive===O&&A.prefix===y&&A.suffix===_);if(M)w=M;else{const A=Fe(s,R,O,y,_);w=A,T.push(A),T.length===2&&r?.push(T)}}s=w}f&&p<c&&f.push(a.substring(p,c));const g=f?.slice();if(!s)return g;if(d&&t.children&&!t.isRoot&&t.id&&t.id.charCodeAt(t.id.lastIndexOf("/")+1)===95){const v=Fe(s,Ki);(s.pathless??=[]).push(v),s=v}const m=(t.path||!t.children)&&!t.isRoot;if(m&&c<u){const v=Fe(s,Re);s.index=v,s=v}return s.parse=d??null,s.priority=l?.params?.priority??0,s.route||(s.data=g,m&&(s.route=t)),[s,o,g]}function Qi(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function Fe(e,t=0,n,s,r){return{kind:t,depth:e?e.depth+1:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,data:void 0,parent:e,parse:null,priority:0,caseSensitive:n,prefix:s,suffix:r}}function yl(e,t){const n=Fe(),s=[];function r(i,o,a,l){const[u,c,h]=It(!1,i,o,a,s,l);if(i.children)for(const d of i.children)r(d,c,u,h)}for(const i of e)r(i,1,n);for(const i of s)i.sort(Qi);t.masksTree=n,t.flatCache=tn(1e3)}function Il(e,t){e||="/";const n=t.flatCache.get(e);if(n!==void 0)return n;const s=Os(e,t.masksTree);return t.flatCache.set(e,s),s}function Rl(e,t,n,s,r){e||="/",s||="/";const i=t?`case\0${e}`:e;let o=r.singleCache.get(i);return o||(o=Fe(),It(t,{from:e},1,o),r.singleCache.set(i,o)),Os(s,o,n)}function Cl(e,t,n=!1){const s=n?e:`nofuzz\0${e}`,r=t.matchCache.get(s);if(r!==void 0)return r;e||="/";let i;try{i=Os(e,t.segmentTree,n)}catch(o){if(o instanceof URIError)i=null;else throw o}return i&&(i.branch=Ji(i.route)),t.matchCache.set(s,i),i}function bl(e,t=!1){const n=Fe(),s=[],r={},i={};let o=0;function a(l,u,c,h){if(l.init(o),l.id in r&&Ms(),r[l.id]=l,o!==0&&l.path){const g=de(l.fullPath);(!i[g]||l.fullPath.endsWith("/"))&&(i[g]=l)}o++;const[d,f,p]=It(t,l,u,c,s,h);if(l._interpolation=p,l.children)for(const g of l.children)a(g,f,d,p)}a(e,1,n);for(const l of s)l.sort(Qi);return{processedTree:{segmentTree:n,singleCache:tn(1e3),matchCache:tn(1e3),flatCache:null,masksTree:null},routesById:r,routesByPath:i}}function Os(e,t,n=!1){const s=e.split("/"),r=El(e,s,t,n);if(!r)return null;const[i]=Wi(e,s,r);return{route:r.node.route,rawParams:i}}function Wi(e,t,n){const s=wl(n.node),r=n.node.data&&vl(n.node.data),i=Object.create(null);let o=n.extract?.part??0,a=n.extract?.node??0,l=n.extract?.path??0,u=n.extract?.param??0;for(;a<s.length;o++,a++,l++){const c=s[a];if(c.kind===Re)break;if(c.kind===Ki){o--,l--;continue}const h=t[o],d=l;if(h&&(l+=h.length),c.kind===1||c.kind===3){const f=r[u++];if(c.kind===3&&n.skipped&1<<a){o--,l=d-1;continue}const p=c.suffix||c.prefix?h.substring(c.prefix.length,h.length-c.suffix.length):h;(p||c.kind===1)&&(i[f]=decodeURIComponent(p))}else if(c.kind===2){const f=c,p=e.substring(d+f.prefix.length,e.length-f.suffix.length),g=decodeURIComponent(p);i["*"]=g,i._splat=g;break}}return n.rawParams&&Object.assign(i,n.rawParams),[i,{part:o,node:a,path:l,param:u}]}function Ji(e){const t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function wl(e){const t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function El(e,t,n,s){if(e==="/"&&n.index)return{node:n.index,skipped:0};const r=!_e(t),i=r&&e!=="/",o=t.length-(r?1:0),a=[{node:n,index:1,skipped:0,statics:0,dynamics:0,optionals:0}];let l=null,u=null;for(;a.length;){const c=a.pop(),{node:h,index:d,skipped:f,statics:p,dynamics:g,optionals:m}=c;let{extract:v,rawParams:S}=c;if(h.kind===2&&h.route&&!kt(u,c))continue;if(h.parse){if(!cr(e,t,c))continue;S=c.rawParams,v=c.extract}s&&h.route&&h.kind!==Re&&kt(l,c)&&(l=c);const C=d===o;if(C&&(h.route&&(!i||h.kind===Re||h.kind===2)&&kt(u,c)&&(u=c),!h.optional&&!h.wildcard&&!h.index&&!h.pathless))continue;const b=C?void 0:t[d];let w;if(C&&h.index){const R={node:h.index,index:d,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S};let y=!0;if(h.index.parse&&(cr(e,t,R)||(y=!1)),y){if(!g&&!m&&!f&&_l(p,o))return R;kt(u,R)&&(u=R)}}if(h.wildcard)for(let R=h.wildcard.length-1;R>=0;R--){const y=h.wildcard[R],{prefix:_,suffix:O}=y;if(!(_&&(C||!(y.caseSensitive?b:w??=b.toLowerCase()).startsWith(_)))){if(O){if(C)continue;const T=t.slice(d).join("/"),M=T.slice(-O.length);if((y.caseSensitive?M:M.toLowerCase())!==O||T.length-O.length<_.length)continue}a.push({node:y,index:o,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}}if(h.optional){const R=f|1<<h.depth+1;for(let y=h.optional.length-1;y>=0;y--){const _=h.optional[y];a.push({node:_,index:d,skipped:R,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}if(!C)for(let y=h.optional.length-1;y>=0;y--){const _=h.optional[y],{prefix:O,suffix:T}=_;if(O||T){const M=_.caseSensitive?b:w??=b.toLowerCase();if(O&&!M.startsWith(O)||T&&M.indexOf(T,M.length-T.length)<O.length)continue}a.push({node:_,index:d+1,skipped:f,statics:p,dynamics:g,optionals:m+Pt(o,d),extract:v,rawParams:S})}}if(!C&&h.dynamic&&b)for(let R=h.dynamic.length-1;R>=0;R--){const y=h.dynamic[R],{prefix:_,suffix:O}=y;if(_||O){const T=y.caseSensitive?b:w??=b.toLowerCase();if(_&&!T.startsWith(_)||O&&T.indexOf(O,T.length-O.length)<_.length)continue}a.push({node:y,index:d+1,skipped:f,statics:p,dynamics:g+Pt(o,d),optionals:m,extract:v,rawParams:S})}if(!C&&h.staticInsensitive){const R=h.staticInsensitive.get(w??=b.toLowerCase());R&&a.push({node:R,index:d+1,skipped:f,statics:p+Pt(o,d),dynamics:g,optionals:m,extract:v,rawParams:S})}if(!C&&h.static){const R=h.static.get(b);R&&a.push({node:R,index:d+1,skipped:f,statics:p+Pt(o,d),dynamics:g,optionals:m,extract:v,rawParams:S})}if(h.pathless)for(let R=h.pathless.length-1;R>=0;R--){const y=h.pathless[R];a.push({node:y,index:d,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}}if(u)return u;if(s&&l){let c=l.index;for(let d=0;d<l.index;d++)c+=t[d].length;const h=c===e.length?"/":e.slice(c);return l.rawParams??=Object.create(null),l.rawParams["**"]=decodeURIComponent(h),l}return null}function Pt(e,t){return 2**(e-t-1)}function _l(e,t){return e===2**(t-1)-1}function cr(e,t,n){let s,r;try{[s,r]=Wi(e,t,n)}catch{return null}if(n.rawParams=s,n.extract=r,!n.node.parse)return!0;try{if(n.node.parse(s)===!1)return null}catch{}return!0}function kt(e,t){return e?t.statics>e.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===Re)>(e.node.kind===Re)||t.node.kind===Re==(e.node.kind===Re)&&t.node.depth>e.node.depth))):!0}function Tl(e,t,n){const s=Hi(e),r=`/${s}`,i=t?r:r.toLowerCase(),o=`${i}/`,a={input:({url:l})=>{const u=t?l.pathname:l.pathname.toLowerCase();return u===i?l.pathname="/":u.startsWith(o)&&(l.pathname=l.pathname.slice(r.length)),l},output:({url:l})=>(l.pathname=Ye(`/${s}${l.pathname}`),l)};return n?{input:({url:l})=>Yn(n,a.input({url:l})),output:({url:l})=>a.output({url:Xi(n,l)})}:a}function Yn(e,t){const n=e?.input?.({url:t});if(n){if(typeof n=="string")return new URL(n);if(n instanceof URL)return n}return t}function Xi(e,t){const n=e?.output?.({url:t});if(n){if(typeof n=="string")return new URL(n);if(n instanceof URL)return n}return t}function Al(e,t){const{createMutableStore:n,createReadonlyStore:s,batch:r}=t,i=new Map,o=n("idle"),a=n(e),l=n(void 0),u=n([]),c=s(()=>u.get().map(g=>i.get(g).get())),h=s(()=>({status:o.get(),isLoading:o.get()==="pending",matches:c.get(),location:a.get(),resolvedLocation:l.get()}));function d(g){let m=i.get(g);return m||(m=n(void 0),i.set(g,m)),m}const f={status:o,location:a,resolvedLocation:l,ids:u,matches:c,byRoute:i,__store:h,getMatchStore:d,setMatches:p};function p(g){const m=u.get(),v=g.map(S=>S.routeId);r(()=>{Za(m,v)||u.set(v);for(const S of m)v.includes(S)||i.get(S).set(()=>{});for(const S of g){const C=d(S.routeId);C.get()!==S&&C.set(S)}})}return f}var Ee="__TSR_index",dr="popstate",hr="beforeunload",Ml=/^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/;function Wt(e){const t=Ml.exec(e);return t?"/"+e.slice(t[0].length):e}function Yi(e){return/[\x00-\x1f\x7f]/.test(e)&&(e=e.replace(/[\x00-\x1f\x7f]/g,t=>`
|
|
2
|
-
\r`.includes(t)?"":encodeURIComponent(t))),Wt(e)}function Ol(e){let t=e.getLocation();const n=new Set,s=o=>{t=e.getLocation(),n.forEach(a=>a({location:t,action:o}))},r=o=>{e.notifyOnIndexChange??!0?s(o):t=e.getLocation()},i=async({task:o,navigateOpts:a,...l})=>{if(a?.ignoreBlocker??!1){o();return}const u=e.getBlockers?.()??[],c=l.type==="PUSH"||l.type==="REPLACE";if(typeof document<"u"&&u.length&&c)for(const h of u){const d=nn(l.path,l.state);if(await h.blockerFn({currentLocation:t,nextLocation:d,action:l.type})){e.onBlocked?.();return}}o()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:o=>(n.add(o),()=>{n.delete(o)}),push:(o,a,l)=>{const u=t.state[Ee];a=fr(u+1,a),i({task:()=>{e.pushState(o,a),s({type:"PUSH"})},navigateOpts:l,type:"PUSH",path:o,state:a})},replace:(o,a,l)=>{const u=t.state[Ee];a=fr(u,a),i({task:()=>{e.replaceState(o,a),s({type:"REPLACE"})},navigateOpts:l,type:"REPLACE",path:o,state:a})},go:(o,a)=>{i({task:()=>{e.go(o,a?.ignoreBlocker??!1),r({type:"GO",index:o})},navigateOpts:a,type:"GO"})},back:o=>{i({task:()=>{e.back(o?.ignoreBlocker??!1),r({type:"BACK"})},navigateOpts:o,type:"BACK"})},forward:o=>{i({task:()=>{e.forward(o?.ignoreBlocker??!1),r({type:"FORWARD"})},navigateOpts:o,type:"FORWARD"})},canGoBack:()=>t.state[Ee]!==0,createHref:o=>e.createHref(o),block:o=>{if(!e.setBlockers)return()=>{};const a=e.getBlockers?.()??[];return e.setBlockers([...a,o]),()=>{const l=e.getBlockers?.()??[];e.setBlockers?.(l.filter(u=>u!==o))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:s,_getBlockers:()=>e.getBlockers?.()??[]}}function fr(e,t){const n=xs();return{...t,key:n,__TSR_key:n,[Ee]:e}}function xl(e){const t=e?.window??(typeof document<"u"?window:void 0),n=t.history.pushState,s=t.history.replaceState;let r=[];const i=()=>r,o=y=>r=y,a=y=>Yi(e?.createHref?e.createHref(y):y),l=e?.parseLocation??(()=>nn(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){const y=xs();t.history.replaceState({[Ee]:0,key:y,__TSR_key:y},"")}let u=l(),c,h=!1,d=!1,f=!1,p=!1;const g=()=>u;let m;const v=()=>{m&&(R._ignoreSubscribers=!0,(m[2]?t.history.pushState:t.history.replaceState)(m[1],"",m[0]),R._ignoreSubscribers=!1,m=void 0,c=void 0)},S=(y,_,O)=>{const T=e?.createHref?a(_):void 0,M=!!m;M||(c=u),u=nn(_,O),m=[T??u.href,O,m?.[2]||y],M||queueMicrotask(()=>v())},C=y=>{u=l(),R.notify({type:y})},b=async()=>{if(p=!1,d){d=!1;return}const y=l(),_=y.state[Ee]-u.state[Ee],O=_===1,T=_===-1,M=!O&&!T||h;h=!1;const A=M?"GO":T?"BACK":"FORWARD",x=M?{type:"GO",index:_}:{type:T?"BACK":"FORWARD"};if(f)f=!1;else{const P=i();if(typeof document<"u"&&P.length){for(const E of P)if(await E.blockerFn({currentLocation:u,nextLocation:y,action:A})){d=!0,t.history.go(-_),R.notify(x);return}}}u=l(),R.notify(x)},w=y=>{if(p){p=!1;return}let _=!1;const O=i();if(typeof document<"u"&&O.length)for(const T of O){const M=T.enableBeforeUnload??!0;if(M===!0){_=!0;break}if(typeof M=="function"&&M()===!0){_=!0;break}}if(_)return y.preventDefault(),y.returnValue=""},R=Ol({getLocation:g,getLength:()=>t.history.length,pushState:(y,_)=>S(!0,y,_),replaceState:(y,_)=>S(!1,y,_),back:y=>(y&&(f=!0,p=!0),t.history.back()),forward:y=>{y&&(f=!0,p=!0),t.history.forward()},go:(y,_)=>{h=!0,_&&(f=!0,p=!0),t.history.go(y)},createHref:y=>a(y),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=s,t.removeEventListener(hr,w,{capture:!0}),t.removeEventListener(dr,b)},onBlocked:()=>{c&&u!==c&&(u=c)},getBlockers:i,setBlockers:o,notifyOnIndexChange:!1});return R._ignoreNextBeforeUnload=y=>{p=!1;try{y=new URL(y,t.document.baseURI).href,p=/^https?:/.test(y)&&(!y.includes("#")||y.split("#")[0]!==t.location.href.split("#")[0])}catch{}},t.addEventListener(hr,w,{capture:!0}),t.addEventListener(dr,b),t.history.pushState=function(...y){const _=n.apply(t.history,y);return R._ignoreSubscribers||C("PUSH"),_},t.history.replaceState=function(...y){const _=s.apply(t.history,y);return R._ignoreSubscribers||C("REPLACE"),_},R}function nn(e,t){const n=Yi(e),s=n.indexOf("#"),r=n.indexOf("?");if(!t){const i=xs();t={[Ee]:0,key:i,__TSR_key:i}}return{href:n,pathname:n.substring(0,s>0?r>0?Math.min(s,r):s:r>0?r:n.length),hash:s>-1?n.substring(s):"",search:r>-1?n.slice(r,s===-1?void 0:s):"",state:t}}function xs(){return(Math.random()+1).toString(36).substring(7)}function bn(e,t){return e.protocol!=="http:"&&e.protocol!=="https:"||e.origin!==t||!!e.username||!!e.password}function wn(e){return e.pathname+e.search+e.hash}function pr(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function cn(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function gr({key:e,__TSR_key:t,__TSR_index:n,__hashScrollIntoViewOptions:s,...r}){return r}function Pl(e){return e.findIndex(t=>t.status==="error"||t.status==="notFound"||t._notFound)+1}function kl(e,t,n,s,r,i){s&&(t=t.slice(0,s)),r&&(n=n.slice(0,r));for(const o of t){if(i&&e._tx!==i)return;n.some(a=>a.routeId===o.routeId)||e.routesById[o.routeId].options.onLeave?.(o)}for(const o of n){if(i&&e._tx!==i)return;e.routesById[o.routeId].options[t.some(a=>a.routeId===o.routeId)?"onStay":"onEnter"]?.(o)}}var Fl=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.subscribers=new Set,this._cache=new Map,this._committed=[],this.startTransition=async n=>(n(),!1),this.update=n=>{const s=this.options;this.options={...s,...n},this.isServer=this.options.isServer??!1??typeof document>"u",this.staticLocations=new WeakMap,this.protocolAllowlist=new Set(this.options.protocolAllowlist),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=xl()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost");const r=this.options.basepath??"/",i=this.options.rewrite,o=this.basepath!==r||s?.rewrite!==i||s?.caseSensitive!==this.options.caseSensitive;if(o&&(this.basepath=r,this.rewrite=r!=="/"&&Hi(r)?Tl(r,this.options.caseSensitive,i):i),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let a;a=this.buildRouteTree(),this.setRoutes(a)}if(this.stores)o&&this.stores.location.set(this.latestLocation);else if(this.latestLocation){const a=this.getStoreConfig(this);this.batch=a.batch,this.stores=Al(this.latestLocation,a),ul(this)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const n=bl(this.routeTree,this.options.caseSensitive);return this.options.routeMasks&&yl(this.options.routeMasks,n.processedTree),{...n,resolvePathCache:tn(1e3)}},this.subscribe=(n,s)=>{const r={eventType:n,fn:s};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=n=>{for(const s of this.subscribers)if(s.eventType===n.type)try{s.fn(n)}catch(r){console.error(r)}},this.parseLocation=(n,s)=>{const r=({pathname:l,search:u,hash:c,href:h},d)=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(l)){const m=this.options.parseSearch(u),v=this.options.stringifySearch(m);return{href:l+v+c,publicHref:l+v+c,pathname:at(l),external:!1,searchStr:v,search:Ke(s?.search,m),hash:at(c.slice(1)),state:we(s?.state,d)}}const f=Yn(this.rewrite,new URL(h,this.origin)),p=this.options.parseSearch(f.search),g=this.options.stringifySearch(p);return f.search=g,{href:f.href.replace(f.origin,""),publicHref:h,pathname:at(Wt(f.pathname)),external:!!this.rewrite&&bn(f,this.origin),searchStr:g,search:Ke(s?.search,p),hash:at(f.hash.slice(1)),state:we(s?.state,d)}},i=r(n,n.state),{__tempLocation:o,__tempKey:a}=i.state;if(o&&(!a||a===this.tempLocationKey)){const l=r(o,{...o.state,__tempLocation:void 0,key:i.state.key,__TSR_key:i.state.__TSR_key});return l.maskedLocation=i,l}return i},this.matchRoutes=(n,s,r)=>typeof n=="string"?this.matchRoutesInternal({pathname:n,search:s},r):this.matchRoutesInternal(n,s),this.getMatchedRoutes=n=>{const s=Object.create(null),r=Cl(de(n),this.processedTree,!0);return r&&Object.assign(s,r.rawParams),[r?.branch||[this.routesById.__root__],s,r?.route]},this.buildLocation=n=>{{const o=this.staticLocations.get(n);if(o)return o}let s=!1;const r=(o={})=>{if(o.href){const P=nn(o.href,{});o={...o,to:Yn(this.rewrite,new URL(P.pathname,this.origin)).pathname,search:this.options.parseSearch(P.search),hash:P.hash.slice(1)}}const a=o._fromLocation||this._pendingLocation||this.latestLocation;let l;const u=()=>(s=!0,a),c=()=>(s=!0,l??=this.matchRoutesLightweight(a)),h=o.to?`${o.to}`:".",d=or(h[0]==="/"?"":o.unsafeRelative==="path"?u().pathname:o.from??c()[1],h,this.options.trailingSlash,this.resolvePathCache),f=this.routesByPath[de(d)],p=d.includes("$");let g;if(f)g=f._branch??=Ji(f);else if(p)g=[];else{const[P,E,G]=this.getMatchedRoutes(d);g=P,this.options.notFoundRoute&&(!G||G.path!=="/"&&E["**"])&&(g=[...g,this.options.notFoundRoute])}const m=p?f?._interpolation??It(!1,{fullPath:d},0):void 0;let v;for(const P of g){const E=P.options.params?.stringify??P.options.stringifyParams;if(E){const G=c()[3];if(v??=En(o.params,G),!Gi(v))break;v===G&&(v=Object.assign(Kt(),v));try{Object.assign(v,E(v))}catch{}}}v??=En(o.params,Nl(o.params,m)?c()[3]:_n);const S=n.leaveParams?d:Wt(at(m?ar(d,m,v,this.pathParamsDecoder):d)),C=Dl(g,n._includeValidateSearch),b=()=>{let P=c()[2];if(n._includeValidateSearch&&this.options.search?.strict){const E={};g.forEach(G=>{if(G.options.validateSearch)try{Object.assign(E,Jt(G.options.validateSearch,{...E,...P}))}catch{}}),P=E}return P},w=C.length?jl(C,b(),o):o.search===!0?b():typeof o.search=="function"?o.search(b()):o.search||_n,R=this.options.stringifySearch(w),y=o.hash===!0?u().hash:typeof o.hash=="function"?o.hash(u().hash):o.hash||void 0,_=y?`#${y}`:"",O=o.state?o.state===!0?u().state:typeof o.state=="function"?o.state(u().state):o.state:_n,T=`${S}${R}${_}`;let M,A,x=!1;if(this.rewrite){const P=new URL(T,this.origin),E=P.origin,G=Xi(this.rewrite,P);M=wn(P),bn(G,E)?(A=G.href,x=!0):A=Wt(wn(G))}else M=Ya(T),A=M;return{publicHref:A,href:M,pathname:S,search:w,searchStr:R,state:O,hash:y??"",external:x,unmaskOnReload:o.unmaskOnReload}},i=r(n);if(n.mask)i.maskedLocation=r({from:n.from,...n.mask});else if(this.options.routeMasks){const o=Il(i.pathname,this.processedTree);if(o){const a=Object.assign(Kt(),o.rawParams),{from:l,params:u,...c}=o.route,h=En(u,a);i.maskedLocation=r({from:n.from,...c,params:h})}}return!s&&n._fromLocation&&!i.maskedLocation&&this.staticLocations.set(n,i),i},this.commitLocation=async({viewTransition:n,ignoreBlocker:s,...r})=>{const i=r.maskedLocation??r;if(i.external)return mr(this,i.publicHref,{replace:r.replace,ignoreBlocker:s});let o;const a=de(this.latestLocation.href)===de(r.href)&&ve(gr(r.state),gr(this.latestLocation.state)),l=this._commitPromise;let u;const c=new Promise(h=>{u=h});if(c.resolve=()=>{u(),l?.resolve()},this._commitPromise=c,a)this.load();else{let{maskedLocation:h,hashScrollIntoView:d,...f}=r;h&&(f={...h,state:{...h.state,__tempKey:void 0,__tempLocation:{...f,search:f.searchStr,state:{...f.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(f.unmaskOnReload??this.options.unmaskOnReload??!1)&&(f.state.__tempKey=this.tempLocationKey)),f.state={...f.state,__hashScrollIntoViewOptions:d??this.options.defaultHashScrollIntoView??!0},this.shouldViewTransition=n,o=r.replace?"REPLACE":"PUSH",this.history[o==="REPLACE"?"replace":"push"](f.publicHref,f.state,{ignoreBlocker:s}),this.history.subscribers.size||this.load({action:{type:o}})}return this._scroll.next=r.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:n,resetScroll:s,hashScrollIntoView:r,viewTransition:i,ignoreBlocker:o,...a}={})=>{const l=this.buildLocation({...a,_includeValidateSearch:!0});this._pendingLocation=l;const u=this.commitLocation({...l,viewTransition:i,replace:n,resetScroll:s,hashScrollIntoView:r,ignoreBlocker:o});return queueMicrotask(()=>{this._pendingLocation===l&&(this._pendingLocation=void 0)}),u},this.navigate=async({to:n,reloadDocument:s,href:r,publicHref:i,...o})=>{const a=r?yt(r):void 0;if(a||s){if(n!==void 0||!r){const u=this.buildLocation({to:n,...o}),c=u.maskedLocation??u;r??=c.publicHref,i??=c.publicHref}return mr(this,!a&&i?i:r,o)}return this.buildAndCommitLocation({...o,href:r,to:n,_isNavigate:!0})},this.load=async n=>{this.updateLatestLocation(),n?.action&&(this._scroll.hash=n.action.type==="PUSH"||n.action.type==="REPLACE"),await Kl(this,n)},this.startViewTransition=n=>{const s=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,s&&typeof document.startViewTransition=="function"){let r;if(typeof s=="object"&&window.CSS?.supports?.("selector(:active-view-transition-type(a))")){const i=this.latestLocation,o=this.stores.resolvedLocation.get(),a=typeof s.types=="function"?s.types(cn(i,o)):s.types;if(a===!1)return n();r={update:n,types:a}}else r=n;return document.startViewTransition(r).updateCallbackDone}return n()},this.invalidate=n=>{const s=this._committed,r=n?.filter,i=this._preloads,o=new Set,a=c=>{(!r||r(c))&&o.add(c.id)};s.forEach(a),this._cache.forEach(a),i?.forEach(c=>c.forEach(a)),this._tx?.[3].forEach(a);const l=[];for(const[c,h]of i??[])h.some(d=>o.has(d.id))&&(i.delete(c),l.push(c));const u=c=>{if(o.has(c.id)){const h=this.routesById[c.routeId],d={...c,invalid:!0,...(n?.forcePending||c.status==="error"||c.status==="notFound")&&pr(h)?{status:"pending",error:void 0}:void 0};return c._flight=void 0,d}return c};this._committed=s.map(u);for(const[c,h]of this._cache)o.has(c)&&(h.invalid=!0,n?.forcePending&&(h.status="pending"));for(const c of o)this._flights?.delete(c);for(const c of l)c.abort();return this.shouldViewTransition=!1,this.load({sync:n?.sync})},this.resolveRedirect=n=>{const s=n.options;let r=n.headers.get("Location")||s.href;if(!r){const o=this.buildLocation(s);r=(o.maskedLocation??o).publicHref||"/"}let i;if($i.test(r)||(i=yt(r))&&!this.protocolAllowlist.has(i))throw new Error("Redirect blocked: unsafe protocol");if(i==="http:"||i==="https:"){const o=new URL(r);o.pathname.startsWith("//")?r=o.href:bn(o,this.origin)||(r=wn(o),i=void 0)}return i&&(s.reloadDocument=!0),s.href=r,n.headers.set("Location",r),n},this.clearCache=n=>{const s=this._cache,r=this._preloads,i=n?.filter,o=[],a=[];for(const[u,c]of s)(!i||i(c))&&(a.push(u),o.push(c));const l=[];for(const[u,c]of r??[])(!i||c.some(i))&&(l.push(u),o.push(...c));for(const u of a)s.delete(u);for(const u of l)r.delete(u);for(const u of o){const c=u._flight;u._flight=void 0,c&&!--c[2]&&(this._flights?.get(u.id)===c&&this._flights.delete(u.id),l.push(c[1]))}for(const u of l)u.abort()},this.loadRouteChunk=Ze,this.preloadRoute=n=>Ql(this,n),this.matchRoute=(n,s)=>{const r={...n,to:n.to?or(n.from||"",n.to,this.options.trailingSlash,this.resolvePathCache):void 0,params:n.params||{},leaveParams:!0},i=this.buildLocation(r),o=this.stores.status.get()==="pending";if(s?.pending&&!o)return!1;const a=s?.pending??!o?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),l=Rl(i.pathname,s?.caseSensitive??!1,s?.fuzzy??!1,a.pathname,this.processedTree);return!l||n.params&&!ve(l.rawParams,n.params,!0)?!1:s?.includeSearch??!0?ve(a.search,i.search,!0)?l.rawParams:!1:l.rawParams},this.getStoreConfig=t,e.pathParamsAllowedCharacters?.length&&(this.pathParamsDecoder=el(e.pathParamsAllowedCharacters)),this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??"fuzzy",stringifySearch:e.stringifySearch??fl,parseSearch:e.parseSearch??hl,protocolAllowlist:e.protocolAllowlist??Xa}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes(e){Object.assign(this,e),this.lightweightCache=new WeakMap,this.staticLocations=new WeakMap;const t=this.options.notFoundRoute;t&&(t.init(99999999999),this.routesById[t.id]!==t&&(t._interpolation=It(!1,t,0)),this.routesById[t.id]=t)}matchRoutesInternal(e,t){const[n,s,r]=this.getMatchedRoutes(e.pathname);let i=n,o=!1;(r?r.path!=="/"&&s["**"]:de(e.pathname))&&(this.options.notFoundRoute?i=[...i,this.options.notFoundRoute]:o=!0);const a=o?Gl(this.options.notFoundMode,i):void 0,l=new Array(i.length),u=this._committed,c=(d,f)=>{const p=u[f];return p?.routeId===d.id?p:d===this.options.notFoundRoute?u.find(g=>g.routeId===d.id):void 0};let h;for(let d=0;d<i.length;d++){const f=i[d],p=l[d-1];let g,m,v;{const x=p?.search??e.search,P=p?._strictSearch??void 0;try{const E=Jt(f.options.validateSearch,{...x})??void 0;g={...x,...E},m={...P,...E}}catch(E){let G=E;if(E instanceof sn||(G=new sn(E.message,{cause:E})),t?.throwOnError)throw G;g=x,m={},v=G}}let S="",C="";try{S=f.options.loaderDeps?.({search:g})??"",C=S&&JSON.stringify(S)||""}catch(x){if(t?.throwOnError)throw x;v??=x}const b=Kt(),w=f._interpolation?ar(f.fullPath,f._interpolation,s,this.pathParamsDecoder,b):f.fullPath,R=f.id+w+C,y=c(f,d),_=this._cache.get(R)??(y?.id===R?y:void 0);h=_?._strictParams??Object.assign(b,h);let O;if(!_)try{vr(f,h)}catch(x){if(et(x)||qi(x)?O=x:O=new Ll(x.message,{cause:x}),t?.throwOnError)throw O}const T=y?"stay":"enter";let M;if(_)M={..._,cause:T,search:Ke(y?y.search:_.search,g),_strictSearch:m,searchError:v};else{const x=pr(f)?"pending":"success";M={id:R,ssr:f.options.ssr,index:d,routeId:f.id,params:y?.params??h,_strictParams:h,pathname:w,updatedAt:Date.now(),search:y?Ke(y.search,g):g,_strictSearch:m,searchError:v,status:x,isFetching:!1,error:void 0,paramsError:O,context:{},abortController:t?._controller??new AbortController,cause:T,loaderDeps:y?we(y.loaderDeps,S):S,invalid:!1,preload:!1,staticData:f.options.staticData||{},fullPath:f.fullPath}}const A=a===f.id;M._notFound&&!A&&(M.error=void 0),M._notFound=A,l[d]=M}for(let d=0;d<l.length;d++){const f=l[d];f.params=f.cause==="stay"?Ke(f.params,h):h,t?._controller&&(f.context={})}return l}matchRoutesLightweight(e){const t=_e(this.stores.ids.get()),n=t?this.stores.byRoute.get(t).get():void 0,s=n?.id,r=this.lightweightCache.get(e);if(r&&r[0]===s)return r[1];const[i,o]=this.getMatchedRoutes(e.pathname),a=_e(i),l={...e.search};for(const d of i)try{Object.assign(l,Jt(d.options.validateSearch,l))}catch{}const u=n&&n.routeId===a.id&&n.pathname===e.pathname;let c;if(u)c=n.params;else{const d=o;for(const f of i)try{vr(f,d)}catch{}c=d}const h=[i,a.fullPath,l,c];return this.lightweightCache.set(e,[s,h]),h}};async function mr(e,t,{replace:n,ignoreBlocker:s}){if(!Bi(t,e.protocolAllowlist)){if(!s){const r=e.history._getBlockers();for(const i of r)if(i?.blockerFn&&await i.blockerFn({currentLocation:e.history.location,nextLocation:e.history.location,action:n?"REPLACE":"PUSH"}))return}e.history._ignoreNextBeforeUnload?.(t),n?window.location.replace(t):window.location.href=t}}var sn=class extends Error{},Ll=class extends Error{};function Jt(e,t){if(e==null)return{};if("~standard"in e){const n=e["~standard"].validate(t);if(n instanceof Promise)throw new sn("Async validation not supported");if(n.issues)throw new sn(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return"parse"in e?e.parse(t):typeof e=="function"?e(t):{}}function En(e,t){if(e===void 0||e===!0)return t;const n=Object.create(null);return e===!1||e===null?n:typeof e=="function"?(Object.assign(n,t),Object.assign(n,e(n))):Object.assign(n,t,e)}function Nl(e,t){return typeof e=="function"?!0:!t||e===!1||e===null?!1:e===void 0||e===!0||t.some(n=>typeof n!="string"&&!As.call(e,n[1]))}var _n=Object.freeze({});function Dl(e,t){const n=[];for(let s=0;s<e.length;s++){const r=e[s].options;if("search"in r)r.search?.middlewares&&n.push(...r.search.middlewares);else if(r.preSearchFilters||r.postSearchFilters){const o=({search:a,next:l})=>{const u=l(r.preSearchFilters?r.preSearchFilters.reduce((c,h)=>h(c),a):a);return r.postSearchFilters?r.postSearchFilters.reduce((c,h)=>h(c),u):u};n.push(o)}const i=r.validateSearch;if(t&&i){const o=({search:a,next:l,meta:u})=>{const c=l(a);try{const h=Jt(i,c);if(u&&h)for(const d in h)d in c||(u.defaulted||=new Map).set(d,h[d]);return{...c,...h}}catch{}return c};n.push(o)}}return n}function jl(e,t,n){const s=(r,i,o)=>{if(r>=e.length){if(!n.search)return{};if(n.search===!0)return i;const l=ji(n.search,i);return o&&(o.explicit=l),l}const a=(l,u)=>{if(u){const c=o||{};return{search:s(r+1,l,c),meta:c}}return s(r+1,l,o)};return e[r]({search:i,next:a,meta:o})};return s(0,t)}function Gl(e,t){if(e!=="root"){let n;for(let s=t.length-1;s>=0;s--){const r=t[s];if(r.options.notFoundComponent)return r.id;n||=r.children&&r.id}if(n)return n}return ft}function vr(e,t){const n=e.options.params?.parse??e.options.parseParams;n&&Object.assign(t,n(t))}function Zn(e,t){return e.options[t]?.preload?.()}function $l(e,t){const n=Zn(e,"component");let s=Zn(e,"pendingComponent");return t&&(s?s=s.then(t):t()),n&&s?Promise.all([n,s]).then(()=>{}):n??s}function Ze(e,t,n){const s=()=>t===!1?void 0:t?Zn(e,t):$l(e,n),r=e._lazy;if(r)return r===!0?s():r.then(s);if(!e.lazyFn)return s();const i=e.lazyFn().then(o=>{{const{id:a,...l}=o.options;Object.assign(e.options,l),e._lazy=!0}},o=>{throw e._lazy=void 0,o});return e._lazy=i,i.then(s)}function Ps(e){const t=e.findIndex(n=>n.status!=="success"||n._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var he=0,Se=1,dn=2,K=3,Te=[4];function Rt(e){return typeof e[0]=="number"}function $e(e,t){return t.aborted?Promise.race([Promise.reject(t),e]):new Promise((n,s)=>{const r=()=>s(t);t.addEventListener("abort",r,{once:!0}),Promise.resolve(e).then(n,s).then(()=>t.removeEventListener("abort",r))})}function Be(e,t){return e.routesById[t.routeId]}function Ct(e,t,n){return qi(e)?[K,e]:et(e)?(e.routeId||=n,[dn,e]):t?(typeof e?.then=="function"&&(e=new Error("A Promise was thrown",{cause:e})),[Se,e]):[he,e]}function ks(e,t){let n=Ct(t,!0,e.id);if(n[0]!==Se)return n;try{e.options.onError?.(n[1])}catch(s){n=Ct(s,!0,e.id)}return n}function pt(e,t,n,s,r){return r[0].signal.aborted?Te:Ns(e,t,n,ks(n,s),r)}async function Bl(e,t,n,s,r,i){const[o,a]=t,l=n[0].signal,u=!!n[3];for(let c=n[6]??0;c<s;c++){const h=a[c],d=Be(e,h);h.abortController=n[0];const f=a[c-1]?.context??e.options.context??{},p={params:h.params,location:o,navigate:S=>e.navigate({...S,_fromLocation:o}),buildLocation:e.buildLocation,cause:u?"preload":h.cause,abortController:n[0],preload:u,matches:a,routeId:d.id};try{const S=h._ctx||=d.options.context?d.options.context({...p,deps:h.loaderDeps,context:f})||{}:void 0;h.context={...f,...S}}catch(S){return me(e,h),[c,pt(e,t,d,S,n)]}if(l.aborted)return[c,Te];const g=h.paramsError??h.searchError;if(g!==void 0)return me(e,h),[c,pt(e,t,d,g,n)];const m=d.options.beforeLoad;if(!m)continue;const v=h.status;c>=i&&(h.status="pending",n[7]?.());try{bt(e,h,"beforeLoad",n[0]);const S=m({...p,search:h.search,context:h.context,...e.options.additionalContext}),C=await(typeof S?.then=="function"?$e(S,l):S);if(l.aborted)return[c,Te];const b=Ns(e,t,d,Ct(C,!1,d.id),n);if(b[0]!==he)return me(e,h),[c,b];h.context={...h.context,...C}}catch(S){return me(e,h),[c,pt(e,t,d,S,n)]}finally{h.status=v,bt(e,h,!1,n[0])}}r()}function Fs(e,t,n){if(!(!n||--n[2])){if(e._flights?.get(t.id)===n){const s=e._tx;if(s&&!s[0].signal.aborted&&!s[3].includes(t)&&s[3].some(r=>r.id===t.id)&&s[3].some(r=>r.isFetching==="beforeLoad"))return;e._flights.delete(t.id)}return n[1]}}function me(e,t){const n=t._flight;t._flight=void 0,Fs(e,t,n)?.abort()}function W(e,t,n,s){const r=[];for(const i of t)if(!n?.includes(i)){const o=i._flight;if(i._flight=void 0,s&&o?.[2]===1&&e._flights?.get(i.id)===o&&n?.some(a=>a.id===i.id))o[2]=0;else{const a=Fs(e,i,o);a&&r.push(a)}}for(const i of r)i.abort()}function Ls(e){for(const t of e){const n=t._flight;n&&n[2]++}}function bt(e,t,n,s){if(t.isFetching=n,s&&e._tx?.[0]!==s)return;const r=e.stores.byRoute.get(t.routeId),i=r?.get();i?.id===t.id&&r.set({...i,isFetching:n})}function Zi(e,t,n,s,r,i,o){const a=t[0];return{params:n.params,location:a,navigate:l=>e.navigate({...l,_fromLocation:a}),cause:o?"preload":n.cause,abortController:r,preload:o,deps:n.loaderDeps,parentMatchPromise:i,context:n.context,route:s,...e.options.additionalContext}}async function Sr(e,t,n,s,r,i,o){const a=o[0],l=a.signal;if(l.aborted)return Te;if(!r)return[he,void 0];let u=n._flight;bt(e,n,"loader",a);try{if(!u){const c=new AbortController;u=[Promise.resolve().then(()=>r(Zi(e,t,n,s,c,i,!!o[3]))).then(h=>Ct(h,!1,s.id),h=>Ct(h,!0,s.id)).then(h=>(h[0]!==he&&e._flights?.get(n.id)===u&&(e._flights.delete(n.id),u[2]||c.abort()),h[0]===Se&&u[2]?ks(s,h[1]):h)),c,1],(e._flights??=new Map).set(n.id,u)}return n._flight=u,n.abortController=u[1],Ns(e,t,s,await $e(u[0],l),o)}catch(c){if(c!==l||!l.aborted)throw c;return me(e,n),Te}finally{bt(e,n,!1,a)}}function yr(e,t,n){t[0]!==K&&(e.status="success",e.error=void 0,t[0]===he?(e.loaderData=t[1],e.invalid=!1,e.updatedAt=Date.now(),e.preload=n):e.invalid=!0)}function Ul(e,t,n){const s=e._cache.get(t.id);if(s!==n||e._committed.some(i=>i.id===t.id&&i._flight===t._flight))return;const r={...t,_notFound:void 0,context:{}};r._flight&&r._flight[2]++,e._cache.set(t.id,r),s&&me(e,s)}function Ir(e,t){return t[0]===Se||t[0]===dn?{...e,status:t[0]===Se?"error":"notFound",error:t[1],_flight:void 0}:e}function Hl(e,t,n,s,r,i,o){const a=t[1][n],l=Be(e,a),u=!!i[3],c=e._cache.get(a.id);let h,d=!1,f;try{if(a.status==="success"&&(h=l.options.shouldReload,typeof h=="function"&&(h=h(Zi(e,t,a,l,i[0],r,u))),i[0].signal.aborted&&(f=Te)),!f)if(a.status!=="success")d=!0;else{const A=u||a.preload?l.options.preloadStaleTime??e.options.defaultPreloadStaleTime??3e4:l.options.staleTime??e.options.defaultStaleTime??0;d=!!(a.invalid||h||h===void 0&&Date.now()-a.updatedAt>=A&&(i[5]||a.cause==="enter"||i[2].some(x=>x.routeId===a.routeId&&x.id!==a.id)))}}catch(A){a.invalid=!0,me(e,a),f=pt(e,t,l,A,i)}const p=l.options.loader,g=typeof p=="function",m=g?p:p?.handler,v=!u||l.options.preload!==!1;let S=v&&p?e._flights?.get(a.id):void 0;S===a._flight||f?S=void 0:S&&!d&&!u&&h===void 0?d=!0:d||(S=void 0);const C=!!(p&&d&&a.status==="success"&&!u&&!i[4]&&((g?void 0:p.staleReloadMode)??e.options.defaultStaleReloadMode)!=="blocking"),b=d&&v,w=b&&!C&&(a.status!=="success"||!!p),R=n>=o?i[7]:void 0,y=l.lazyFn&&l._lazy!==!0?R:void 0;if(b&&!p&&(a.invalid=!1,a.updatedAt=Date.now()),S&&S[2]++,w){const A=a._flight;a._flight=S,Fs(e,a,A)?.abort(),n>=o&&(a.status="pending"),R?.()}b||(a.isFetching=!1);const _=!f&&w?Sr(e,t,a,l,m,r,i).then(A=>(yr(a,A,u),A[0]===he&&(p&&!i[0].signal.aborted&&Ul(e,a,c),n>=o&&(a.status="pending")),A)):Promise.resolve(f??[he,a.loaderData]),O=(async()=>{try{const x=Ze(l,void 0,y);x&&await $e(x,i[0].signal)}catch(x){if(!t[1].some((P,E)=>E<=n&&(P.status==="error"||P.status==="notFound"||P._notFound)))return[n,pt(e,t,l,x,i)]}const A=await _;w&&A[0]===he&&a.status==="pending"&&!i[0].signal.aborted&&(a.status="success",R?.())})();if(s.push([n,_,O]),!C)return _.then(A=>Ir(a,A));const T={...a,status:"pending",preload:!1,_flight:S};a.invalid=!1,a.isFetching="loader";const M=Sr(e,t,T,l,m,r,i).then(A=>(a.isFetching=!1,yr(T,A,!1),A));return(t[2]??=[]).push([n,M,O,T]),M.then(A=>Ir(T,A))}async function es(e,t,n,s,r=0){const i=n?.[1][1];let o=i?.routeId?t.findIndex(a=>a.routeId===i.routeId):n?.[0]??t.length-1;o<0&&(o=0);for(let a=o;a>=0;a--){const l=Be(e,t[a]);try{const u=Ze(l,!1);u&&await $e(u,s)}catch(u){if(u===s&&s.aborted)throw u}if(l.options.notFoundComponent)return a}return i?.routeId?o:r}function Le(e,t){t[2]&&(W(e,t[2].map(n=>n[3])),t[2]=void 0)}async function Rr(e,t,n,s){let r;try{await Promise.all(e.map(i=>i[1].then(async o=>{const a=i[0];if(!(s&&a>=await s)){if(o[0]>=K)throw[a,o];!r&&o[0]!==he&&(r=[a,o],await Promise.all((n??[]).map(l=>{if(!(l[0]<=a))return l[1].then(u=>{if(u[0]===K)throw[l[0],u]})})))}})))}catch(i){return i}return t??r}function Ns(e,t,n,s,r,i){for(;s[0]===K;){const o=s[1],a=o.options;try{if((a.href||o.headers.has("Location"))&&(e.resolveRedirect(o),a.reloadDocument)||(a.reloadDocument?r[3]:r[1]>=20))return s;const l=e.buildLocation({...a,_fromLocation:t[0],_includeValidateSearch:!0}),u=l.maskedLocation??l;if(u.external){const c=o.clone();return c.options={...a},c.headers.set("Location",u.publicHref),e.resolveRedirect(c),r[3]?[K,c]:[K,c,u]}return[K,o,l]}catch(l){s=i?[Se,l]:ks(n,l),i=!0}}return s}async function eo(e,t,n,s,r,i){const o=t[1];let a=await r,l=!1;const u=o.findIndex(f=>f._notFound),c=f=>f[1][0]===dn?es(e,o,f,s.signal):f[0];let h=u<0?o.length:u;if((a?.[1][0]??0)>=K)h=0;else if(a){h=a[2]??=await c(a);for(const f of n){if(f[0]>=h)break;const p=await f[1];if(p[0]!==he&&p[0]<K&&!("loaderData"in o[f[0]])){a=[f[0],p],h=a[2]=await c(a);break}}}for(const f of n){if(f[0]>=h)break;const p=await f[2];if(p){a=p;break}}if((a?.[1][0]??0)>=K){const f=a[1];if(f[0]!==K||f[1].options.reloadDocument||f[2])return Le(e,t),f;l=!0,a=[0,[Se,new Error("Too many redirects")]]}const d=a?a[2]??await c(a):u;if(d>=0){const f=a?.[1],p=f?.[0],g=o[d],m=f?.[1],v=()=>{f&&(g._notFound=void 0,p===Se?g.status="error":(m.routeId=g.routeId,g.routeId===e.routeTree.id?(g.status="success",g._notFound=!0):g.status="notFound"),g.error=m,g.isFetching=!1)};v(),f||i?.();const S=Be(e,g);try{await $e(f?Promise.resolve().then(()=>Ze(S,p===Se?"errorComponent":"notFoundComponent")):Promise.all([Ze(S),Ze(S,"notFoundComponent")]),s.signal)}catch(C){if(C===s.signal&&s.signal.aborted)return Le(e,t),Te}f?l&&(s.abort(),await Promise.all([...n.map(C=>C[1]),...n.map(C=>C[2]),...(t[2]??[]).map(C=>C[1])]),Le(e,t),W(e,o),v()):g.status="success"}return t}async function to(e,t,n,s=0,r=t[1].length){const i=t[1];for(let o=s;o<r;o++){const a=i[o],l=Be(e,a).options;if(l.head||l.scripts)try{const u={ssr:e.options.ssr,matches:i,match:a,params:a.params,loaderData:a.loaderData},[c,h]=await $e(Promise.all([l.head?.(u),l.scripts?.(u)]),n);a.meta=c?.meta,a.links=c?.links,a.headScripts=c?.scripts,a.styles=c?.styles,a.scripts=h}catch(u){if(u===n&&n.aborted)break;console.error(u)}if(a.status!=="success"||a._notFound)break}return t}async function no(e,t,n,s){const r=[t,n],i=s[0].signal;let o;try{const a=e.stores.matches.get();let l=n.findIndex(v=>v._notFound);if(e.options.notFoundMode!=="root"&&l>=0){const v=await es(e,n,void 0,i,l);n[l]._notFound=void 0,n[v]._notFound=!0,l=v}let u=l<0?n.length:l+1,c=0;for(;c<u&&c!==l;){const v=n[c],S=s[2][c],C=a[c];if(S?.id!==v.id||S.status!=="success"||v.preload||C?.id!==v.id||C.status!=="success"||(c++,S._notFound||C._notFound))break}const h=[],d=s[6]??0;let f=d?Promise.resolve(n[d-1]):void 0;const p=()=>{for(let v=d;v<u&&!i.aborted;v++)f=Hl(e,r,v,h,f,s,c)},g=await Bl(e,r,s,u,p,c);if(g){if(s[4]=!0,u=g[0],g[1][0]===dn){const v=await es(e,n,g,i);g[2]=v,u=Math.min(u,v+1)}else g[1][0]>=K&&(u=0);p()}if(!i.aborted&&!s[3]){const v=[];for(const[S,C]of e._flights??[])C[2]||(e._flights.delete(S),v.push(C[1]));for(const S of v)S.abort()}const m=eo(e,r,h,s[0],Rr(h,g,r[2]),s[7]);r[2]?.length&&(r[3]=Rr(r[2],void 0,void 0,m.then(v=>Rt(v)?0:Ps(n).length,()=>0))),o=await m}catch(a){if(Le(e,r),a===i&&i.aborted)return Te;throw a}return Rt(o)?o:to(e,o,i,s[6]===n.length?s[6]:0)}function ts(e,t){if(e._tx!==t)return;const n=t[3],s=e.stores.matches.get();let r=e._pending;for(let i=0;i<n.length;i++){const o=n[i],a=o.status==="success"&&!o._notFound,l=s[i]?.id===o.id&&s[i]?.status==="pending";if(a&&!l)continue;const u=Be(e,o),c=a||o.invalid?0:u.options.pendingMs??e.options.defaultPendingMs,h=u.options.pendingComponent??e.options.defaultPendingComponent;if(!h||typeof c!="number"||c===1/0){r&&(r[0]=t,r[2]=0,r[4]=!0);return}const d=u.options.pendingMinMs??e.options.defaultPendingMinMs??0;let f=!1;if(r?.[1]===o.id?(f=r[0]!==t,r[0]=t):(clearTimeout(r?.[3]),e._pending=r=void 0),r||(e._pending=r=[t,o.id,l?Date.now()+d:t[4]+c,void 0,l||void 0,h]),r[4]&&!f&&r[5]===h)return;if(r[5]=h,!r[4]){clearTimeout(r[3]);const m=r[2]-Date.now();if(m>0){r[3]=setTimeout(()=>ts(e,t),m);return}r[2]=0}const p=n.map(m=>({...m,_flight:void 0}));p[i].status="pending";const g=r[4]=e.startTransition(()=>e.stores.setMatches(p),p).then(m=>(m&&e._pending===r&&r[4]===g&&!r[2]&&(r[2]=Date.now()+d),m));return}}function lt(e,t){const n=e._pending;(e._tx===t||!e._tx?.[3].some(s=>s.id===n?.[1]))&&(clearTimeout(n?.[3]),e._pending=void 0)}async function Cr(e,t){const n=e._pending;if(!n)return;clearTimeout(n[3]);const s=n[2]-Date.now();if(!n[4]||s<=0||!Ps(t[3]).some(i=>i.id===n[1]))return;let r;try{await $e(new Promise(i=>{r=setTimeout(i,s)}),t[0].signal)}catch{}clearTimeout(r)}function so(e,t){e._committed=t,e.stores.setMatches(t)}function zl(e,t,n,s){const r=e._committed,i=e._lifecycleEnd,o=e._cache;for(const c of n)c.preload=!1,s&&(c._assetEnd=void 0);const a=Ps(n).length,l=new Map;{const c=Date.now(),h=new Set;for(let d=0;d<n.length;d++){const f=n[d];(d<a||f.status==="success")&&h.add(f.id)}for(const d of[...r,...o.values()]){if(d.status!=="success"||h.has(d.id))continue;const f=Be(e,d);!f.options.loader||c-d.updatedAt>=(d.preload?f.options.preloadGcTime??e.options.defaultPreloadGcTime??3e5:f.options.gcTime??e.options.defaultGcTime??3e5)||l.set(d.id,o.get(d.id)===d?d:{...d,_flight:void 0,isFetching:!1,context:{}})}}t[3]=[],e._cache=l;const u=e._lifecycleEnd=Pl(n);so(e,n),W(e,[...o.values(),...r].filter(c=>c._flight&&l.get(c.id)!==c),n),kl(e,r,n,i,u,t)}async function Ft(e,t){let n=e._tx;for(;n&&n!==t;)t=n,await n[5],n=e._tx}function ro(e,t,n){const s=n[1].options,r=n[2];if(!r)return e.navigate({...s,replace:!0,ignoreBlocker:!0});if(s.reloadDocument)return e.navigate({href:(r.maskedLocation??r).publicHref,reloadDocument:!0,replace:!0,ignoreBlocker:!0});r._redirects=t[1]+1,e._pendingLocation=r;const i=e.commitLocation({...r,viewTransition:s.viewTransition,replace:!0,resetScroll:s.resetScroll,hashScrollIntoView:s.hashScrollIntoView,ignoreBlocker:!0});return queueMicrotask(()=>{e._pendingLocation===r&&(e._pendingLocation=void 0)}),i}async function Vl(e,t,n,s,r){const i=n.map(l=>({...l}));Ls(i);for(const l of s)me(e,i[l[0]]),i[l[0]]=l[3];const o=[t[2],i];let a;try{a=await eo(e,o,s,t[0],r)}catch(l){throw W(e,i),l}if(Rt(a)){W(e,i),a[0]===K&&e._tx===t&&e._committed===n&&await ro(e,t,a);return}if(await to(e,a,t[0].signal),e._tx!==t||e._committed!==n){W(e,i);return}for(const l of i){const u=e._cache.get(l.id);u?._flight&&u._flight===l._flight&&(e._cache.delete(l.id),me(e,u))}so(e,i),W(e,n,i)}async function ql(e,t,n,s,r,i){const o=await no(e,t[2],t[3],[t[0],t[1],e._committed,void 0,r,n,i,s]);if(Rt(o)){const h=o[0]===K&&e._tx===t;if((!h||o[1].options.reloadDocument)&<(e,t),W(e,t[3]),t[3]=[],!h)return;if(e._tx!==t){lt(e,t);return}await ro(e,t,o);return}const a=o[1];if(e._tx===t&&await Cr(e,t),e._tx!==t){lt(e,t),W(e,a),Le(e,o);return}const l=t[2],u=cn(l,e.stores.resolvedLocation.get()),c=o[2];await e.startViewTransition(async()=>{if(e._tx===t&&await Cr(e,t),e._tx!==t){lt(e,t),W(e,a),Le(e,o);return}const h=()=>{lt(e,t),zl(e,t,a,i),e._tx===t&&(e.emit({type:"onLoad",...u}),e._tx===t&&e.emit({type:"onBeforeRouteMount",...u}))},d=await e.startTransition(h,a);if(e._tx!==t){Le(e,o);return}c?.length&&Vl(e,t,a,c,o[3]).catch(console.error),e.batch(()=>{e.stores.resolvedLocation.set(l),e.stores.status.set("idle"),e._tx===t&&e.emit({type:"onResolved",...u}),d&&e._tx===t&&e.emit({type:"onRendered",...u})}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0)})}async function Kl(e,t){const n=e._tx,s=e.stores.resolvedLocation.get(),r=s??e.stores.location.get(),i=e.latestLocation,o=e._pendingLocation,a=o?.href===i.href?o._redirects??0:0,l=e._handoff,u=l?.[0](),c=new AbortController,h=e._preflight;if(e._preflight=c,u||l?.[1](),h?.abort(),!c.signal.aborted){const b=cn(i,s);e.emit({type:"onBeforeNavigate",...b}),c.signal.aborted||e.emit({type:"onBeforeLoad",...b})}if(c.signal.aborted){await Ft(e,n);return}const d=r.href===i.href;let f=c;const p=e.matchRoutes(i,{_controller:c});Ls(p);const g=u?l[1](p):void 0;if(g?f=u:u?.abort(),c.signal.aborted){W(e,p),await Ft(e,n);return}e._preflight=void 0;let m;const v=()=>ql(e,C,d,()=>ts(e,C),t?.sync,g),S=t?.sync?new Promise(b=>m=b):Promise.resolve().then(v),C=[f,a,i,p,Date.now(),S.then(()=>Ft(e,C))];if(e._tx=C,n){for(const b of e.stores.matches.get()){if(e._tx!==C)break;b.isFetching&&bt(e,b,!1)}n[0].abort(),W(e,n[3],C[3],!0)}if(e._tx!==C){W(e,C[3]),C[3]=[],m?.(),await Ft(e,C);return}e.batch(()=>{e.stores.status.set("pending"),e.stores.location.set(i)}),(g||!e._committed.length&&p[0]?.status!=="success"&&!p.some(b=>b._notFound))&&ts(e,C),m?.(v()),await C[5]}async function Ql(e,t){let n=e.buildLocation(t);for(let s=0;;s++){const r=e._committed,i=new AbortController;let o,a,l;try{try{o=e.matchRoutes(n,{_controller:i}),Ls(o),a=(e._preloads??=new Map).set(i,o),l=await no(e,n,o,[i,s,r,!0])}finally{a&&(a=a.delete(i),W(e,o)),i.abort()}if(!Rt(l))return l[1];if(!a||l.length<3)return;n=l[2]}catch(u){et(u)||console.error(u);return}}}var Wl="Error preloading route! ☝️",io=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=t=>{this.originalIndex=t,this._branch=void 0;const n=this.options,s=!n?.path&&!n?.id;this.parentRoute=this.options.getParentRoute?.(),s?this._path=ft:this.parentRoute||Ms();let r=s?ft:n?.path;r&&r!=="/"&&(r=Ui(r));const i=n?.id||r,o=s?ft:Ye((this.parentRoute.id==="__root__"?"":this.parentRoute.id)+"/"+(i??""));r==="__root__"&&(r="/");const a=o==="__root__"?"/":r===void 0?this.parentRoute.fullPath:Ye(this.parentRoute.fullPath+"/"+r);this._path=r,this._id=o,this._fullPath=a,this._to=de(a)},this.addChildren=t=>this._addFileChildren(t),this._addFileChildren=t=>(Array.isArray(t)&&(this.children=t),typeof t=="object"&&t!==null&&(this.children=Object.values(t)),this),this._addFileTypes=()=>this,this.updateLoader=t=>(Object.assign(this.options,t),this),this.update=t=>(Object.assign(this.options,t),this),this.lazy=t=>(this.lazyFn=t,this),this.redirect=t=>ml({from:this.fullPath,...t}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw new Error("Route cannot have both an 'id' and a 'path' option.")}},Jl=class extends io{constructor(e){super(e)}},Ds=class extends I.Component{constructor(...e){super(...e),this.state={error:0},this.reset=()=>{this.setState({error:0})}}static getDerivedStateFromProps(e,t){const n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:0}:{resetKey:n}}static getDerivedStateFromError(e){return{error:[e]}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){const e=this.state.error;return e?I.createElement(this.props.errorComponent??Xl,{error:e[0],reset:this.reset}):this.props.children}};function Xl({error:e}){const[t,n]=I.useState(!1);return(0,L.jsxs)("div",{style:{padding:".5rem",maxWidth:"100%"},children:[(0,L.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:".5rem"},children:[(0,L.jsx)("strong",{style:{fontSize:"1rem"},children:"Something went wrong!"}),(0,L.jsx)("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:()=>n(s=>!s),children:t?"Hide Error":"Show Error"})]}),(0,L.jsx)("div",{style:{height:".25rem"}}),t?(0,L.jsx)("div",{children:(0,L.jsx)("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"},children:e?.message?(0,L.jsx)("code",{children:e.message}):null})}):null]})}var Yl=()=>!0,Zl=()=>!1;function eu({children:e,fallback:t=null}){return(0,L.jsx)(I.Fragment,{children:oo()?e:t})}function oo(){return I.useSyncExternalStore(tu,Yl,Zl)}function tu(){return()=>{}}var ao=I.createContext(null);function Z(e){const t=I.useContext(ao);return t||void 0,t}var hn=I.createContext(void 0),nu=I.createContext(void 0);function su({update:e,notify:t,unwatched:n}){return{link:s,unlink:r,propagate:i,checkDirty:o,shallowPropagate:a};function s(u,c,h){const d=c.depsTail;if(d!==void 0&&d.dep===u)return;const f=d!==void 0?d.nextDep:c.deps;if(f!==void 0&&f.dep===u){f.version=h,c.depsTail=f;return}const p=u.subsTail;if(p!==void 0&&p.version===h&&p.sub===c)return;const g=c.depsTail=u.subsTail={version:h,dep:u,sub:c,prevDep:d,nextDep:f,prevSub:p,nextSub:void 0};f!==void 0&&(f.prevDep=g),d!==void 0?d.nextDep=g:c.deps=g,p!==void 0?p.nextSub=g:u.subs=g}function r(u,c=u.sub){const h=u.dep,d=u.prevDep,f=u.nextDep,p=u.nextSub,g=u.prevSub;return f!==void 0?f.prevDep=d:c.depsTail=d,d!==void 0?d.nextDep=f:c.deps=f,p!==void 0?p.prevSub=g:h.subsTail=g,g!==void 0?g.nextSub=p:(h.subs=p)===void 0&&n(h),f}function i(u){let c=u.nextSub,h;e:do{const d=u.sub;let f=d.flags;if(f&60?f&12?f&4?!(f&48)&&l(u,d)?(d.flags=f|40,f&=1):f=0:d.flags=f&-9|32:f=0:d.flags=f|32,f&2&&t(d),f&1){const p=d.subs;if(p!==void 0){const g=(u=p).nextSub;g!==void 0&&(h={value:c,prev:h},c=g);continue}}if((u=c)!==void 0){c=u.nextSub;continue}for(;h!==void 0;)if(u=h.value,h=h.prev,u!==void 0){c=u.nextSub;continue e}break}while(!0)}function o(u,c){let h,d=0,f=!1;e:do{const p=u.dep,g=p.flags;if(c.flags&16)f=!0;else if((g&17)===17){if(e(p)){const m=p.subs;m.nextSub!==void 0&&a(m),f=!0}}else if((g&33)===33){(u.nextSub!==void 0||u.prevSub!==void 0)&&(h={value:u,prev:h}),u=p.deps,c=p,++d;continue}if(!f){const m=u.nextDep;if(m!==void 0){u=m;continue}}for(;d--;){const m=c.subs,v=m.nextSub!==void 0;if(v?(u=h.value,h=h.prev):u=m,f){if(e(c)){v&&a(m),c=u.sub;continue}f=!1}else c.flags&=-33;c=u.sub;const S=u.nextDep;if(S!==void 0){u=S;continue e}}return f}while(!0)}function a(u){do{const c=u.sub,h=c.flags;(h&48)===32&&(c.flags=h|16,(h&6)===2&&t(c))}while((u=u.nextSub)!==void 0)}function l(u,c){let h=c.depsTail;for(;h!==void 0;){if(h===u)return!0;h=h.prevDep}return!1}}function ru(e,t,n){const s=typeof e=="object",r=s?e:void 0;return{next:(s?e.next:e)?.bind(r),error:(s?e.error:t)?.bind(r),complete:(s?e.complete:n)?.bind(r)}}var ns=[],Xt=0,{link:br,unlink:iu,propagate:ou,checkDirty:lo,shallowPropagate:wr}=su({update(e){return e._update()},notify(e){ns[ss++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,rn(e))}}),Lt=0,ss=0,ce,rs=0;function au(e){try{++rs,e()}finally{--rs||uo()}}function rn(e){const t=e.depsTail;let n=t!==void 0?t.nextDep:e.deps;for(;n!==void 0;)n=iu(n,e)}function uo(){if(!(rs>0)){for(;Lt<ss;){const e=ns[Lt];ns[Lt++]=void 0,e.notify()}Lt=0,ss=0}}function Er(e,t){const n=typeof e=="function",s=e,r={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?0:1,get(){return ce!==void 0&&br(r,ce,Xt),r._snapshot},subscribe(i){const o=ru(i),a={current:!1},l=lu(()=>{r.get(),a.current?o.next?.(r._snapshot):a.current=!0});return{unsubscribe:()=>{l.stop()}}},_update(i){const o=ce,a=t?.compare??Object.is;if(n)ce=r,++Xt,r.depsTail=void 0;else if(i===void 0)return!1;n&&(r.flags=5);try{const l=r._snapshot,u=typeof i=="function"?i(l):i===void 0&&n?s(l):i;return l===void 0||!a(l,u)?(r._snapshot=u,!0):!1}finally{ce=o,n&&(r.flags&=-5),rn(r)}}};return n?(r.flags=17,r.get=function(){const i=r.flags;if(i&16||i&32&&lo(r.deps,r)){if(r._update()){const o=r.subs;o!==void 0&&wr(o)}}else i&32&&(r.flags=i&-33);return ce!==void 0&&br(r,ce,Xt),r._snapshot}):r.set=function(i){if(r._update(i)){const o=r.subs;o!==void 0&&(ou(o),wr(o),uo())}},r}function lu(e){const t=()=>{const s=ce;ce=n,++Xt,n.depsTail=void 0,n.flags=6;try{return e()}finally{ce=s,n.flags&=-5,rn(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){const s=this.flags;s&16||s&32&&lo(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,rn(this)}};return t(),n}var uu=tt((e=>{var t=Rs();function n(d,f){return d===f&&(d!==0||1/d===1/f)||d!==d&&f!==f}var s=typeof Object.is=="function"?Object.is:n,r=t.useState,i=t.useEffect,o=t.useLayoutEffect,a=t.useDebugValue;function l(d,f){var p=f(),g=r({inst:{value:p,getSnapshot:f}}),m=g[0].inst,v=g[1];return o(function(){m.value=p,m.getSnapshot=f,u(m)&&v({inst:m})},[d,p,f]),i(function(){return u(m)&&v({inst:m}),d(function(){u(m)&&v({inst:m})})},[d]),a(p),p}function u(d){var f=d.getSnapshot;d=d.value;try{var p=f();return!s(d,p)}catch{return!0}}function c(d,f){return f()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:l;e.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:h})),cu=tt(((e,t)=>{t.exports=uu()})),du=tt((e=>{var t=Rs(),n=cu();function s(c,h){return c===h&&(c!==0||1/c===1/h)||c!==c&&h!==h}var r=typeof Object.is=="function"?Object.is:s,i=n.useSyncExternalStore,o=t.useRef,a=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(c,h,d,f,p){var g=o(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=l(function(){function S(y){if(!C){if(C=!0,b=y,y=f(y),p!==void 0&&m.hasValue){var _=m.value;if(p(_,y))return w=_}return w=y}if(_=w,r(b,y))return _;var O=f(y);return p!==void 0&&p(_,O)?(b=y,_):(b=y,w=O)}var C=!1,b,w,R=d===void 0?null:d;return[function(){return S(h())},R===null?void 0:function(){return S(R())}]},[h,d,f,p]);var v=i(c,g[0],g[1]);return a(function(){m.hasValue=!0,m.value=v},[v]),u(v),v}})),hu=tt(((e,t)=>{t.exports=du()})),fu=hu();function pu(e,t){return e===t}function ye(e,t=s=>s,n){const s=n?.compare??pu,r=(0,I.useCallback)(o=>{const{unsubscribe:a}=e.subscribe(o);return a},[e]),i=(0,I.useCallback)(()=>e.get(),[e]);return(0,fu.useSyncExternalStoreWithSelector)(r,i,i,t,s)}var _r={};function co(e,t){const n=I.useRef();return s=>{const r=e?.select?e.select(s):s;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=we(n.current,r):r}}function Ue(e){const t=Z(),n=I.useContext(e.from?nu:hn),s=e.from??n,r=t.stores.getMatchStore(s),i=co(e,t),o=ye(r,a=>a?i(a):_r);if(o!==_r)return o;(e.shouldThrow??!0)&&Ms()}function ho(e){return Ue({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function fo(e){const{select:t,...n}=e;return Ue({...n,select:s=>t?t(s.loaderDeps):s.loaderDeps})}function po(e){return Ue({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function go(e){return Ue({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function js(e){const t=Z();return I.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function Ff(e){const t=Z(),n=js(),s=I.useRef(null);return Ts(()=>{s.current!==e&&(n(e),s.current=e)},[t,e,n]),null}function mo(e){return Ue({...e,select:t=>e.select?e.select(t.context):t.context})}function gu(...e){const t=I.useRef(e),n=t.current;return e.forEach((s,r)=>{ve(n[r],s,!1,!0)||(n[r]=s)}),t.current}function Nt(e,t){e.preloadRoute(t).catch(n=>{console.warn(n),console.warn(Wl)})}var mu={compare:(e,t)=>e[0]===t[0]&&e[1]===t[1]};function vu(e,t){const n=typeof e=="string"&&yt(e);if(n)return t.has(n)?e:null}function Su(e,t,n,s,r){const i=ir(e.pathname,s),o=ir(t.pathname,s);return(n?.exact?i!==o:!(i.startsWith(o)&&(i.length===o.length||i[o.length]==="/")))||(n?.includeSearch??!0)&&!ve(e.search,t.search,!n?.exact,n?.explicitUndefined)?!1:n?.includeHash?r&&e.hash===t.hash:!0}function yu(e,t,n){const s=Z(),r=I.useRef(null),i=I.useCallback($=>{if(r.current=$,typeof t=="function")return t($);t&&(t.current=$)},[t]),{activeOptions:o,to:a,preload:l,preloadDelay:u,hashScrollIntoView:c,replace:h,startTransition:d,resetScroll:f,viewTransition:p,ignoreBlocker:g,disabled:m,target:v,onClick:S,onBlur:C,onFocus:b,onMouseEnter:w,onMouseLeave:R,onTouchStart:y}=e,_=oo(),[O,T,M]=gu(e.search,e.params,o),[A,x]=I.useMemo(()=>[e,{...e}],[s,e.from,e._fromLocation,e.hash,e.to,O,T,e.state,e.mask,e.unsafeRelative]),P=I.useCallback($=>{const te=vu(a,s.protocolAllowlist);if(te!==void 0)return[te??void 0];A._fromLocation||(x._fromLocation=$);const At=s.buildLocation(x),ot=wu(At,s,m);return[ot,!m&&(!ot||yt(ot))?void 0:Su($,At,M,s.basepath,_)]},[M,m,_,A,x,s,a]),[E,G]=ye(s.stores.location,P,mu),st=G===void 0?E:void 0,rt=m||E===void 0,_t=I.useRef(!1),fe=e.reloadDocument||st||rt?!1:l??s.options.defaultPreload,it=u??s.options.defaultPreloadDelay??0,He=I.useCallback($=>{const te=$?.isIntersecting;if(!(te??fe==="intent")){te===!1&&Tn(r);return}if(!it){Nt(s,A);return}gt.has(r)||gt.set(r,setTimeout(()=>{gt.delete(r),Nt(s,A)},it))},[s,A,r,fe,it]);I.useEffect(()=>{fe==="render"&&!_t.current&&(_t.current=!0,Nt(s,A));let $;return fe==="viewport"&&r.current&&typeof IntersectionObserver=="function"&&($=new IntersectionObserver(te=>He(te.pop()),{rootMargin:"100px"}),$.observe(r.current)),()=>{$?.disconnect(),Tn(r)}},[s,A,fe,He,r]);const ee=Cu(e,n);if(ee.ref=t?i:r,st)return ee.href=st,ee;const Sn=$=>{const te=v??$.currentTarget.getAttribute("target");!rt&&!($.metaKey||$.altKey||$.ctrlKey||$.shiftKey)&&!$.defaultPrevented&&(!te||te==="_self")&&$.button===0&&($.preventDefault(),s.navigate({...A,replace:h,resetScroll:f,hashScrollIntoView:c,startTransition:d,viewTransition:p,ignoreBlocker:g}))},yn=()=>{fe==="intent"&&Nt(s,A)},Tt=()=>{fe==="intent"&&Tn(r)};return ee.onClick=Qe(S,Sn),ee.onBlur=Qe(C,Tt),ee.onFocus=Qe(b,He),ee.onMouseEnter=Qe(w,He),ee.onMouseLeave=Qe(R,Tt),ee.onTouchStart=Qe(y,yn),bu(ee,e,G,E,rt,n)}var Iu={},Ru={className:"active"},vo=new Set(["to","params","search","hash","state","mask","from","unsafeRelative","_fromLocation","reloadDocument","preload","preloadDelay","preloadIntentProximity","hashScrollIntoView","replace","startTransition","resetScroll","viewTransition","ignoreBlocker","activeProps","inactiveProps","activeOptions","_asChild"]);function Cu(e,t){const n={};for(const s in e)vo.has(s)||s==="type"&&t!==void 0||s==="disabled"&&t==="a"||(n[s]=e[s]);return n}function bu(e,t,n,s,r,i){const{activeProps:o,inactiveProps:a,className:l,style:u,target:c}=t,h=ji(n?o:a,{})??(n?Ru:Iu);Object.assign(e,h),e.href=s,i!=="a"&&(e.disabled=r),e.target=c;const d=h.style;(u||d)&&(e.style=u&&d?{...u,...d}:u||d);const f=h.className;return(l||f)&&(e.className=l?f?`${l} ${f}`:l:f),r&&(e.role="link",e["aria-disabled"]=!0),n&&(e["data-status"]="active",e["aria-current"]="page"),e}var gt=new WeakMap,Tn=e=>{clearTimeout(gt.get(e)),gt.delete(e)},Qe=(e,t)=>e?n=>n.defaultPrevented||(e(n),n.defaultPrevented||t(n)):t;function wu(e,t,n){if(n)return;const s=e.maskedLocation??e,r=s.external?s.publicHref:t.history.createHref(s.publicHref)||"/";if(!((s.external||r!==s.publicHref)&&Bi(r,t.protocolAllowlist)))return r}var So=I.memo(I.forwardRef((e,t)=>{const n=e._asChild||"a",s=yu(e,t,n),r=typeof e.children=="function"?e.children({isActive:s["data-status"]==="active"}):e.children;return I.createElement(n,s,r)}),Eu);function Eu(e,t){let n=0;for(const s in t)if(n++,e[s]!==t[s]&&(!vo.has(s)||!ve(e[s],t[s],!1,!0)))return!1;for(const s in e)n--;return n===0}var _u=class extends io{constructor(e){super(e),this.useMatch=t=>Ue({...t,from:this.id}),this.useRouteContext=t=>mo({...t,from:this.id}),this.useSearch=t=>go({...t,from:this.id}),this.useParams=t=>po({...t,from:this.id}),this.useLoaderDeps=t=>fo({...t,from:this.id}),this.useLoaderData=t=>ho({...t,from:this.id}),this.useNavigate=()=>js({from:this.fullPath}),this.Link=I.forwardRef((t,n)=>(0,L.jsx)(So,{ref:n,from:this.fullPath,...t}))}};function Tu(e){return new _u(e)}var Au=class extends Jl{constructor(e){super(e),this.useMatch=t=>Ue({...t,from:this.id}),this.useRouteContext=t=>mo({...t,from:this.id}),this.useSearch=t=>go({...t,from:this.id}),this.useParams=t=>po({...t,from:this.id}),this.useLoaderDeps=t=>fo({...t,from:this.id}),this.useLoaderData=t=>ho({...t,from:this.id}),this.useNavigate=()=>js({from:this.fullPath}),this.Link=I.forwardRef((t,n)=>(0,L.jsx)(So,{ref:n,from:this.fullPath,...t}))}};function Lf(e){return new Au(e)}function Nf(e){return t=>{const n=Tu(t);return n.isRoot=!1,n}}function Df(e,t){let n,s,r;const i=()=>(n||(r=void 0,n=e().then(a=>{n=void 0,o.preload=void 0,s=a[t??"default"]}).catch(a=>{n=void 0,r=a})),n),o=function(l){if(r){if(Qa(r)&&typeof sessionStorage<"u"){const u=`tanstack_router_reload:${r.message}`;if(!sessionStorage.getItem(u))throw sessionStorage.setItem(u,"1"),window.location.reload(),new Promise(()=>{})}throw r}if(!s)if(sr)sr(i());else throw i();return I.createElement(s,l)};return o.preload=i,o}function Mu(e){const t=Z(),n=`not-found-${ye(t.stores.location,s=>s.pathname)}-${ye(t.stores.status)}`;return(0,L.jsx)(Ds,{getResetKey:()=>n,onCatch:(s,r)=>{if(et(s))e.onCatch?.(s,r);else throw s},errorComponent:({error:s})=>{if(et(s))return e.fallback?.(s);throw s},children:e.children})}function Ou(){return(0,L.jsx)("p",{children:"Not Found"})}function Xe(e){return(0,L.jsx)(L.Fragment,{children:e.children})}function yo(e,t,n){return t.options.notFoundComponent?(0,L.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,L.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,L.jsx)(Ou,{})}function fn(e,t){const n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,L.jsx)(n,{}):null}var xu=(e,t)=>e[0]===t[0]&&e[1]===t[1],Io=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n==="data-only"||!e.ssr,Ro=I.memo(function({routeId:t}){const n=Z();return(0,L.jsx)(Pu,{router:n,match:ye(n.stores.getMatchStore(t))})});function Pu({router:e,match:t}){const n=e.routesById[t.routeId],s=fn(e,n),r=n.options.errorComponent??e.options.defaultErrorComponent,i=n.options.onCatch??e.options.defaultOnCatch,o=n.isRoot?n.options.notFoundComponent??e.options.notFoundRoute?.options.component:n.options.notFoundComponent,a=t.ssr===!1||t.ssr==="data-only",l=Io(e,n,t.ssr)&&(n.options.wrapInSuspense??s??(n.options.errorComponent?.preload||a))?I.Suspense:Xe,u=r?Ds:Xe,c=o?Mu:Xe;return(0,L.jsxs)(n.isRoot?n.options.shellComponent??Xe:Xe,{children:[(0,L.jsx)(hn.Provider,{value:t.routeId,children:(0,L.jsx)(l,{fallback:s,children:(0,L.jsx)(u,{getResetKey:()=>t,errorComponent:r,onCatch:(h,d)=>{if(et(h))throw h.routeId??=t.routeId,h;i?.(h,d)},children:(0,L.jsx)(c,{fallback:h=>{if(h.routeId??=t.routeId,h.routeId!==t.routeId)throw h;return I.createElement(o,h)},children:a?(0,L.jsx)(eu,{fallback:s,children:(0,L.jsx)(Tr,{match:t})}):(0,L.jsx)(Tr,{match:t})})})})}),null]})}var Tr=I.memo(function({match:t}){const n=Z(),s=t.routeId,r=n.routesById[s],i=I.useMemo(()=>{const a=(r.options.remountDeps??n.options.defaultRemountDeps)?.({routeId:s,loaderDeps:t.loaderDeps,params:t._strictParams,search:t._strictSearch});return a?JSON.stringify(a):void 0},[s,t.loaderDeps,t._strictParams,t._strictSearch,r.options.remountDeps,n.options.defaultRemountDeps]),o=I.useMemo(()=>{const a=r.options.component??n.options.defaultComponent;return a?(0,L.jsx)(a,{},i):(0,L.jsx)(ku,{})},[i,r.options.component,n.options.defaultComponent]);if(t.status==="pending"){if(n.ssr&&!Io(n,r,t.ssr))return o;if(n._tx)throw n._tx[5];return fn(n,r)}if(t.status==="notFound")return yo(n,r,t.error);if(t.status==="error")throw t.error;return o}),ku=I.memo(function(){const t=Z(),n=I.useContext(hn);let s,r,i;{const a=t.stores.getMatchStore(n);[s,r]=ye(a,l=>[!!l._notFound,l.error],{compare:xu}),i=ye(t.stores.ids,l=>l[l.indexOf(n)+1])}if(s)return yo(t,t.routesById[n],r);if(!i)return null;const o=(0,L.jsx)(Ro,{routeId:i});return n==="__root__"?(0,L.jsx)(I.Suspense,{fallback:fn(t),children:o}):o});function Co(e,t){const n=e[1];e.length=0,n?.(t)}function Fu({t:e}){const t=Z(),n=t._rendered??=[];return t.startTransition=(s,r)=>new Promise(i=>{Co(n,!1),n.push(r,i),e(t),I.startTransition(s)}),Ts(()=>{const s=t.history.subscribe(t.load);t.updateLatestLocation();const r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(de(r.publicHref)!==de(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),s;const o=t.stores.resolvedLocation.get();return o?.href===r.href&&o.state.__TSR_key===r.state.__TSR_key?n.push(t.stores.matches.get(),a=>{a&&t.emit({type:"onRendered",...cn(o,o)})}):t._tx||t.load({sync:!0}).catch(console.error),s},[t,t.history]),null}function Lu(){const e=Z(),t=e.routesById[ft],n=fn(e,t),s=e.ssr?Xe:I.Suspense,r=(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(Fu,{t:I.useState()[1]}),(0,L.jsx)(s,{fallback:n,children:(0,L.jsx)(Nu,{})})]});return e.options.InnerWrap?(0,L.jsx)(e.options.InnerWrap,{children:r}):r}function Nu(){const e=Z(),t=e._rendered,n=ye(e.stores.matches,o=>t[0]??o),s=n[0],r=s?.routeId;Ts(()=>{t[0]===n&&Co(t,!0)},[t,n]);const i=r?(0,L.jsx)(Ro,{routeId:r}):null;return(0,L.jsx)(hn.Provider,{value:r,children:e.options.disableGlobalCatchBoundary?i:(0,L.jsx)(Ds,{getResetKey:()=>s,onCatch:void 0,children:i})})}var Du=e=>({createMutableStore:Er,createReadonlyStore:Er,batch:au}),jf=e=>new ju(e),ju=class extends Fl{constructor(e){super(e,Du)}};function Gu({router:e,children:t,...n}){Gi(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});const s=(0,L.jsx)(ao.Provider,{value:e,children:t});return e.options.Wrap?(0,L.jsx)(e.options.Wrap,{children:s}):s}function Gf({router:e,...t}){return(0,L.jsx)(Gu,{router:e,...t,children:(0,L.jsx)(Lu,{})})}function $u(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function"){const i=!!(t??!0);return{shouldBlockFn:async()=>i?await e():!1,enableBeforeUnload:i,withResolver:!1}}const n=!!(e.condition??!0),s=e.blockerFn;return{shouldBlockFn:async()=>n&&s!==void 0?await s():n,enableBeforeUnload:n,withResolver:s===void 0}}function $f(e,t){const{shouldBlockFn:n,enableBeforeUnload:s=!0,disabled:r=!1,withResolver:i=!1}=$u(e,t),o=Z(),{history:a}=o,[l,u]=I.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return I.useEffect(()=>{const c=async h=>{function d(v){const S=o.parseLocation(v),[,C,b]=o.getMatchedRoutes(S.pathname);return b===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:C,search:o.options.parseSearch(v.search)}:{routeId:b.id,fullPath:b.fullPath,pathname:S.pathname,params:C,search:o.options.parseSearch(v.search)}}const f=d(h.currentLocation),p=d(h.nextLocation);if(f.routeId==="__notFound__"&&p.routeId!=="__notFound__")return!1;const g=await n({action:h.action,current:f,next:p});if(!i)return g;if(!g)return!1;const m=await new Promise(v=>{u({status:"blocked",current:f,next:p,action:h.action,proceed:()=>v(!1),reset:()=>v(!0)})});return u({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),m};return r?void 0:a.block({blockerFn:c,enableBeforeUnload:s})},[n,s,r,i,a,o]),l}function Bf(e){const t=Z();return ye(t.stores.location,co(e,t))}function Ce(e,t){return typeof e=="function"?e(t):e}function Y(e,t){return n=>{t.setState(s=>({...s,[e]:Ce(n,s[e])}))}}function pn(e){return e instanceof Function}function Bu(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Uu(e,t){const n=[],s=r=>{r.forEach(i=>{n.push(i);const o=t(i);o!=null&&o.length&&s(o)})};return s(e),n}function k(e,t,n){let s=[],r;return i=>{let o;n.key&&n.debug&&(o=Date.now());const a=e(i);if(!(a.length!==s.length||a.some((u,c)=>s[c]!==u)))return r;s=a;let l;if(n.key&&n.debug&&(l=Date.now()),r=t(...a),n==null||n.onChange==null||n.onChange(r),n.key&&n.debug&&n!=null&&n.debug()){const u=Math.round((Date.now()-o)*100)/100,c=Math.round((Date.now()-l)*100)/100,h=c/16,d=(f,p)=>{for(f=String(f);f.length<p;)f=" "+f;return f};console.info(`%c⏱ ${d(c,5)} /${d(u,5)} ms`,`
|
|
3
|
-
font-size: .6rem;
|
|
4
|
-
font-weight: bold;
|
|
5
|
-
color: hsl(${Math.max(0,Math.min(120-120*h,120))}deg 100% 31%);`,n?.key)}return r}}function F(e,t,n,s){return{debug:()=>{var r;return(r=e?.debugAll)!=null?r:e[t]},key:!1,onChange:s}}function Hu(e,t,n,s){const r=()=>{var o;return(o=i.getValue())!=null?o:e.options.renderFallbackValue},i={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(s),renderValue:r,getContext:k(()=>[e,n,t,i],(o,a,l,u)=>({table:o,column:a,row:l,cell:u,getValue:u.getValue,renderValue:u.renderValue}),F(e.options,"debugCells","cell.getContext"))};return e._features.forEach(o=>{o.createCell==null||o.createCell(i,n,t,e)},{}),i}function zu(e,t,n,s){var r,i;const o={...e._getDefaultColumnDef(),...t},a=o.accessorKey;let l=(r=(i=o.id)!=null?i:a?typeof String.prototype.replaceAll=="function"?a.replaceAll(".","_"):a.replace(/\./g,"_"):void 0)!=null?r:typeof o.header=="string"?o.header:void 0,u;if(o.accessorFn?u=o.accessorFn:a&&(a.includes(".")?u=h=>{let d=h;for(const p of a.split(".")){var f;d=(f=d)==null?void 0:f[p]}return d}:u=h=>h[o.accessorKey]),!l)throw new Error;let c={id:`${String(l)}`,accessorFn:u,parent:s,depth:n,columnDef:o,columns:[],getFlatColumns:k(()=>[!0],()=>{var h;return[c,...(h=c.columns)==null?void 0:h.flatMap(d=>d.getFlatColumns())]},F(e.options,"debugColumns","column.getFlatColumns")),getLeafColumns:k(()=>[e._getOrderColumnsFn()],h=>{var d;return(d=c.columns)!=null&&d.length?h(c.columns.flatMap(f=>f.getLeafColumns())):[c]},F(e.options,"debugColumns","column.getLeafColumns"))};for(const h of e._features)h.createColumn==null||h.createColumn(c,e);return c}var z="debugHeaders";function Ar(e,t,n){var s;let r={id:(s=n.id)!=null?s:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],o=a=>{a.subHeaders&&a.subHeaders.length&&a.subHeaders.map(o),i.push(a)};return o(r),i},getContext:()=>({table:e,header:r,column:t})};return e._features.forEach(i=>{i.createHeader==null||i.createHeader(r,e)}),r}var Vu={createTable:e=>{e.getHeaderGroups=k(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,s,r)=>{var i,o;const a=(i=s?.map(c=>n.find(h=>h.id===c)).filter(Boolean))!=null?i:[],l=(o=r?.map(c=>n.find(h=>h.id===c)).filter(Boolean))!=null?o:[],u=n.filter(c=>!(s!=null&&s.includes(c.id))&&!(r!=null&&r.includes(c.id)));return Dt(t,[...a,...u,...l],e)},F(e.options,z,"getHeaderGroups")),e.getCenterHeaderGroups=k(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,s,r)=>(n=n.filter(i=>!(s!=null&&s.includes(i.id))&&!(r!=null&&r.includes(i.id))),Dt(t,n,e,"center")),F(e.options,z,"getCenterHeaderGroups")),e.getLeftHeaderGroups=k(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,s)=>{var r;return Dt(t,(r=s?.map(i=>n.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"left")},F(e.options,z,"getLeftHeaderGroups")),e.getRightHeaderGroups=k(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,s)=>{var r;return Dt(t,(r=s?.map(i=>n.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"right")},F(e.options,z,"getRightHeaderGroups")),e.getFooterGroups=k(()=>[e.getHeaderGroups()],t=>[...t].reverse(),F(e.options,z,"getFooterGroups")),e.getLeftFooterGroups=k(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),F(e.options,z,"getLeftFooterGroups")),e.getCenterFooterGroups=k(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),F(e.options,z,"getCenterFooterGroups")),e.getRightFooterGroups=k(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),F(e.options,z,"getRightFooterGroups")),e.getFlatHeaders=k(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),F(e.options,z,"getFlatHeaders")),e.getLeftFlatHeaders=k(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),F(e.options,z,"getLeftFlatHeaders")),e.getCenterFlatHeaders=k(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),F(e.options,z,"getCenterFlatHeaders")),e.getRightFlatHeaders=k(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),F(e.options,z,"getRightFlatHeaders")),e.getCenterLeafHeaders=k(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var s;return!((s=n.subHeaders)!=null&&s.length)}),F(e.options,z,"getCenterLeafHeaders")),e.getLeftLeafHeaders=k(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var s;return!((s=n.subHeaders)!=null&&s.length)}),F(e.options,z,"getLeftLeafHeaders")),e.getRightLeafHeaders=k(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var s;return!((s=n.subHeaders)!=null&&s.length)}),F(e.options,z,"getRightLeafHeaders")),e.getLeafHeaders=k(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,s)=>{var r,i,o,a,l,u;return[...(r=(i=t[0])==null?void 0:i.headers)!=null?r:[],...(o=(a=n[0])==null?void 0:a.headers)!=null?o:[],...(l=(u=s[0])==null?void 0:u.headers)!=null?l:[]].map(c=>c.getLeafHeaders()).flat()},F(e.options,z,"getLeafHeaders"))}};function Dt(e,t,n,s){var r,i;let o=0;const a=function(h,d){d===void 0&&(d=1),o=Math.max(o,d),h.filter(f=>f.getIsVisible()).forEach(f=>{var p;(p=f.columns)!=null&&p.length&&a(f.columns,d+1)},0)};a(e);let l=[];const u=(h,d)=>{const f={depth:d,id:[s,`${d}`].filter(Boolean).join("_"),headers:[]},p=[];h.forEach(g=>{const m=[...p].reverse()[0],v=g.column.depth===f.depth;let S,C=!1;if(v&&g.column.parent?S=g.column.parent:(S=g.column,C=!0),m&&m?.column===S)m.subHeaders.push(g);else{const b=Ar(n,S,{id:[s,d,S.id,g?.id].filter(Boolean).join("_"),isPlaceholder:C,placeholderId:C?`${p.filter(w=>w.column===S).length}`:void 0,depth:d,index:p.length});b.subHeaders.push(g),p.push(b)}f.headers.push(g),g.headerGroup=f}),l.push(f),d>0&&u(p,d-1)};u(t.map((h,d)=>Ar(n,h,{depth:o,index:d})),o-1),l.reverse();const c=h=>h.filter(d=>d.column.getIsVisible()).map(d=>{let f=0,p=0,g=[0];d.subHeaders&&d.subHeaders.length?(g=[],c(d.subHeaders).forEach(v=>{let{colSpan:S,rowSpan:C}=v;f+=S,g.push(C)})):f=1;const m=Math.min(...g);return p=p+m,d.colSpan=f,d.rowSpan=p,{colSpan:f,rowSpan:p}});return c((r=(i=l[0])==null?void 0:i.headers)!=null?r:[]),l}var qu=(e,t,n,s,r,i,o)=>{let a={id:t,index:s,original:n,depth:r,parentId:o,_valuesCache:{},_uniqueValuesCache:{},getValue:l=>{if(a._valuesCache.hasOwnProperty(l))return a._valuesCache[l];const u=e.getColumn(l);if(u!=null&&u.accessorFn)return a._valuesCache[l]=u.accessorFn(a.original,s),a._valuesCache[l]},getUniqueValues:l=>{if(a._uniqueValuesCache.hasOwnProperty(l))return a._uniqueValuesCache[l];const u=e.getColumn(l);if(u!=null&&u.accessorFn)return u.columnDef.getUniqueValues?(a._uniqueValuesCache[l]=u.columnDef.getUniqueValues(a.original,s),a._uniqueValuesCache[l]):(a._uniqueValuesCache[l]=[a.getValue(l)],a._uniqueValuesCache[l])},renderValue:l=>{var u;return(u=a.getValue(l))!=null?u:e.options.renderFallbackValue},subRows:i??[],getLeafRows:()=>Uu(a.subRows,l=>l.subRows),getParentRow:()=>a.parentId?e.getRow(a.parentId,!0):void 0,getParentRows:()=>{let l=[],u=a;for(;;){const c=u.getParentRow();if(!c)break;l.push(c),u=c}return l.reverse()},getAllCells:k(()=>[e.getAllLeafColumns()],l=>l.map(u=>Hu(e,a,u,u.id)),F(e.options,"debugRows","getAllCells")),_getAllCellsByColumnId:k(()=>[a.getAllCells()],l=>l.reduce((u,c)=>(u[c.column.id]=c,u),{}),F(e.options,"debugRows","getAllCellsByColumnId"))};for(let l=0;l<e._features.length;l++){const u=e._features[l];u==null||u.createRow==null||u.createRow(a,e)}return a},Ku={createColumn:(e,t)=>{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},bo=(e,t,n)=>{var s,r;const i=n==null||(s=n.toString())==null?void 0:s.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(i))};bo.autoRemove=e=>oe(e);var wo=(e,t,n)=>{var s;return!!(!((s=e.getValue(t))==null||(s=s.toString())==null)&&s.includes(n))};wo.autoRemove=e=>oe(e);var Eo=(e,t,n)=>{var s;return((s=e.getValue(t))==null||(s=s.toString())==null?void 0:s.toLowerCase())===n?.toLowerCase()};Eo.autoRemove=e=>oe(e);var _o=(e,t,n)=>{var s;return(s=e.getValue(t))==null?void 0:s.includes(n)};_o.autoRemove=e=>oe(e);var To=(e,t,n)=>!n.some(s=>{var r;return!((r=e.getValue(t))!=null&&r.includes(s))});To.autoRemove=e=>oe(e)||!(e!=null&&e.length);var Ao=(e,t,n)=>n.some(s=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(s)});Ao.autoRemove=e=>oe(e)||!(e!=null&&e.length);var Mo=(e,t,n)=>e.getValue(t)===n;Mo.autoRemove=e=>oe(e);var Oo=(e,t,n)=>e.getValue(t)==n;Oo.autoRemove=e=>oe(e);var Gs=(e,t,n)=>{let[s,r]=n;const i=e.getValue(t);return i>=s&&i<=r};Gs.resolveFilterValue=e=>{let[t,n]=e,s=typeof t!="number"?parseFloat(t):t,r=typeof n!="number"?parseFloat(n):n,i=t===null||Number.isNaN(s)?-1/0:s,o=n===null||Number.isNaN(r)?1/0:r;if(i>o){const a=i;i=o,o=a}return[i,o]};Gs.autoRemove=e=>oe(e)||oe(e[0])&&oe(e[1]);var ge={includesString:bo,includesStringSensitive:wo,equalsString:Eo,arrIncludes:_o,arrIncludesAll:To,arrIncludesSome:Ao,equals:Mo,weakEquals:Oo,inNumberRange:Gs};function oe(e){return e==null||e===""}var Qu={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:Y("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],s=n?.getValue(e.id);return typeof s=="string"?ge.includesString:typeof s=="number"?ge.inNumberRange:typeof s=="boolean"||s!==null&&typeof s=="object"?ge.equals:Array.isArray(s)?ge.arrIncludes:ge.weakEquals},e.getFilterFn=()=>{var n,s;return pn(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(s=t.options.filterFns)==null?void 0:s[e.columnDef.filterFn])!=null?n:ge[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,s,r;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((s=t.options.enableColumnFilters)!=null?s:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(s=>s.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,s;return(n=(s=t.getState().columnFilters)==null?void 0:s.findIndex(r=>r.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(s=>{const r=e.getFilterFn(),i=s?.find(c=>c.id===e.id),o=Ce(n,i?i.value:void 0);if(Mr(r,o,e)){var a;return(a=s?.filter(c=>c.id!==e.id))!=null?a:[]}const l={id:e.id,value:o};if(i){var u;return(u=s?.map(c=>c.id===e.id?l:c))!=null?u:[]}return s!=null&&s.length?[...s,l]:[l]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),s=r=>{var i;return(i=Ce(t,r))==null?void 0:i.filter(o=>{const a=n.find(l=>l.id===o.id);return!(a&&Mr(a.getFilterFn(),o.value,a))})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(s)},e.resetColumnFilters=t=>{var n,s;e.setColumnFilters(t?[]:(n=(s=e.initialState)==null?void 0:s.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function Mr(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}var Wu=(e,t,n)=>n.reduce((s,r)=>{const i=r.getValue(e);return s+(typeof i=="number"?i:0)},0),Ju=(e,t,n)=>{let s;return n.forEach(r=>{const i=r.getValue(e);i!=null&&(s>i||s===void 0&&i>=i)&&(s=i)}),s},Xu=(e,t,n)=>{let s;return n.forEach(r=>{const i=r.getValue(e);i!=null&&(s<i||s===void 0&&i>=i)&&(s=i)}),s},Yu=(e,t,n)=>{let s,r;return n.forEach(i=>{const o=i.getValue(e);o!=null&&(s===void 0?o>=o&&(s=r=o):(s>o&&(s=o),r<o&&(r=o)))}),[s,r]},Zu=(e,t)=>{let n=0,s=0;if(t.forEach(r=>{let i=r.getValue(e);i!=null&&(i=+i)>=i&&(++n,s+=i)}),n)return s/n},ec=(e,t)=>{if(!t.length)return;const n=t.map(i=>i.getValue(e));if(!Bu(n))return;if(n.length===1)return n[0];const s=Math.floor(n.length/2),r=n.sort((i,o)=>i-o);return n.length%2!==0?r[s]:(r[s-1]+r[s])/2},tc=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),nc=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,sc=(e,t)=>t.length,An={sum:Wu,min:Ju,max:Xu,extent:Yu,mean:Zu,median:ec,unique:tc,uniqueCount:nc,count:sc},rc={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:Y("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(s=>s!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,s;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((s=t.options.enableGrouping)!=null?s:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],s=n?.getValue(e.id);if(typeof s=="number")return An.sum;if(Object.prototype.toString.call(s)==="[object Date]")return An.extent},e.getAggregationFn=()=>{var n,s;if(!e)throw new Error;return pn(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(s=t.options.aggregationFns)==null?void 0:s[e.columnDef.aggregationFn])!=null?n:An[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,s;e.setGrouping(t?[]:(n=(s=e.initialState)==null?void 0:s.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const s=t.getColumn(n);return s!=null&&s.columnDef.getGroupingValue?(e._groupingValuesCache[n]=s.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,s)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var r;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((r=n.subRows)!=null&&r.length)}}};function ic(e,t,n){if(!(t!=null&&t.length)||!n)return e;const s=e.filter(r=>!t.includes(r.id));return n==="remove"?s:[...t.map(r=>e.find(i=>i.id===r)).filter(Boolean),...s]}var oc={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:Y("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=k(n=>[mt(t,n)],n=>n.findIndex(s=>s.id===e.id),F(t.options,"debugColumns","getIndex")),e.getIsFirstColumn=n=>{var s;return((s=mt(t,n)[0])==null?void 0:s.id)===e.id},e.getIsLastColumn=n=>{var s;const r=mt(t,n);return((s=r[r.length-1])==null?void 0:s.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=k(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,s)=>r=>{let i=[];if(!(t!=null&&t.length))i=r;else{const o=[...t],a=[...r];for(;a.length&&o.length;){const l=o.shift(),u=a.findIndex(c=>c.id===l);u>-1&&i.push(a.splice(u,1)[0])}i=[...i,...a]}return ic(i,n,s)},F(e.options,"debugTable","_getOrderColumnsFn"))}},Mn=()=>({left:[],right:[]}),ac={getInitialState:e=>({columnPinning:Mn(),...e}),getDefaultOptions:e=>({onColumnPinningChange:Y("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const s=e.getLeafColumns().map(r=>r.id).filter(Boolean);t.setColumnPinning(r=>{var i,o;if(n==="right"){var a,l;return{left:((a=r?.left)!=null?a:[]).filter(h=>!(s!=null&&s.includes(h))),right:[...((l=r?.right)!=null?l:[]).filter(h=>!(s!=null&&s.includes(h))),...s]}}if(n==="left"){var u,c;return{left:[...((u=r?.left)!=null?u:[]).filter(h=>!(s!=null&&s.includes(h))),...s],right:((c=r?.right)!=null?c:[]).filter(h=>!(s!=null&&s.includes(h)))}}return{left:((i=r?.left)!=null?i:[]).filter(h=>!(s!=null&&s.includes(h))),right:((o=r?.right)!=null?o:[]).filter(h=>!(s!=null&&s.includes(h)))}})},e.getCanPin=()=>e.getLeafColumns().some(n=>{var s,r,i;return((s=n.columnDef.enablePinning)!=null?s:!0)&&((r=(i=t.options.enableColumnPinning)!=null?i:t.options.enablePinning)!=null?r:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(a=>a.id),{left:s,right:r}=t.getState().columnPinning,i=n.some(a=>s?.includes(a)),o=n.some(a=>r?.includes(a));return i?"left":o?"right":!1},e.getPinnedIndex=()=>{var n,s;const r=e.getIsPinned();return r?(n=(s=t.getState().columnPinning)==null||(s=s[r])==null?void 0:s.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=k(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,s,r)=>{const i=[...s??[],...r??[]];return n.filter(o=>!i.includes(o.column.id))},F(t.options,"debugRows","getCenterVisibleCells")),e.getLeftVisibleCells=k(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,s)=>(s??[]).map(r=>n.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"left"})),F(t.options,"debugRows","getLeftVisibleCells")),e.getRightVisibleCells=k(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,s)=>(s??[]).map(r=>n.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"right"})),F(t.options,"debugRows","getRightVisibleCells"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,s;return e.setColumnPinning(t?Mn():(n=(s=e.initialState)==null?void 0:s.columnPinning)!=null?n:Mn())},e.getIsSomeColumnsPinned=t=>{var n;const s=e.getState().columnPinning;if(!t){var r,i;return!!((r=s.left)!=null&&r.length||(i=s.right)!=null&&i.length)}return!!((n=s[t])!=null&&n.length)},e.getLeftLeafColumns=k(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(s=>t.find(r=>r.id===s)).filter(Boolean),F(e.options,"debugColumns","getLeftLeafColumns")),e.getRightLeafColumns=k(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(s=>t.find(r=>r.id===s)).filter(Boolean),F(e.options,"debugColumns","getRightLeafColumns")),e.getCenterLeafColumns=k(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,s)=>{const r=[...n??[],...s??[]];return t.filter(i=>!r.includes(i.id))},F(e.options,"debugColumns","getCenterLeafColumns"))}};function lc(e){return e||(typeof document<"u"?document:null)}var jt={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},On=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),uc={getDefaultColumnDef:()=>jt,getInitialState:e=>({columnSizing:{},columnSizingInfo:On(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:Y("columnSizing",e),onColumnSizingInfoChange:Y("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,s,r;const i=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:jt.minSize,(s=i??e.columnDef.size)!=null?s:jt.size),(r=e.columnDef.maxSize)!=null?r:jt.maxSize)},e.getStart=k(n=>[n,mt(t,n),t.getState().columnSizing],(n,s)=>s.slice(0,e.getIndex(n)).reduce((r,i)=>r+i.getSize(),0),F(t.options,"debugColumns","getStart")),e.getAfter=k(n=>[n,mt(t,n),t.getState().columnSizing],(n,s)=>s.slice(e.getIndex(n)+1).reduce((r,i)=>r+i.getSize(),0),F(t.options,"debugColumns","getAfter")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:s,...r}=n;return r})},e.getCanResize=()=>{var n,s;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((s=t.options.enableColumnResizing)!=null?s:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const s=r=>{if(r.subHeaders.length)r.subHeaders.forEach(s);else{var i;n+=(i=r.column.getSize())!=null?i:0}};return s(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const s=t.getColumn(e.column.id),r=s?.getCanResize();return i=>{if(!s||!r||(i.persist==null||i.persist(),xn(i)&&i.touches&&i.touches.length>1))return;const o=e.getSize(),a=e?e.getLeafHeaders().map(v=>[v.column.id,v.column.getSize()]):[[s.id,s.getSize()]],l=xn(i)?Math.round(i.touches[0].clientX):i.clientX,u={},c=(v,S)=>{typeof S=="number"&&(t.setColumnSizingInfo(C=>{var b,w;const R=t.options.columnResizeDirection==="rtl"?-1:1,y=(S-((b=C?.startOffset)!=null?b:0))*R,_=Math.max(y/((w=C?.startSize)!=null?w:0),-.999999);return C.columnSizingStart.forEach(O=>{let[T,M]=O;u[T]=Math.round(Math.max(M+M*_,0)*100)/100}),{...C,deltaOffset:y,deltaPercentage:_}}),(t.options.columnResizeMode==="onChange"||v==="end")&&t.setColumnSizing(C=>({...C,...u})))},h=v=>c("move",v),d=v=>{c("end",v),t.setColumnSizingInfo(S=>({...S,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},f=lc(n),p={moveHandler:v=>h(v.clientX),upHandler:v=>{f?.removeEventListener("mousemove",p.moveHandler),f?.removeEventListener("mouseup",p.upHandler),d(v.clientX)}},g={moveHandler:v=>(v.cancelable&&(v.preventDefault(),v.stopPropagation()),h(v.touches[0].clientX),!1),upHandler:v=>{var S;f?.removeEventListener("touchmove",g.moveHandler),f?.removeEventListener("touchend",g.upHandler),v.cancelable&&(v.preventDefault(),v.stopPropagation()),d((S=v.touches[0])==null?void 0:S.clientX)}},m=cc()?{passive:!1}:!1;xn(i)?(f?.addEventListener("touchmove",g.moveHandler,m),f?.addEventListener("touchend",g.upHandler,m)):(f?.addEventListener("mousemove",p.moveHandler,m),f?.addEventListener("mouseup",p.upHandler,m)),t.setColumnSizingInfo(v=>({...v,startOffset:l,startSize:o,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:s.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?On():(n=e.initialState.columnSizingInfo)!=null?n:On())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0}}},Gt=null;function cc(){if(typeof Gt=="boolean")return Gt;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Gt=e,Gt}function xn(e){return e.type==="touchstart"}var dc={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:Y("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(s=>({...s,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,s;const r=e.columns;return(n=r.length?r.some(i=>i.getIsVisible()):(s=t.getState().columnVisibility)==null?void 0:s[e.id])!=null?n:!0},e.getCanHide=()=>{var n,s;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((s=t.options.enableHiding)!=null?s:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=k(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(s=>s.column.getIsVisible()),F(t.options,"debugRows","_getAllVisibleCells")),e.getVisibleCells=k(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,s,r)=>[...n,...s,...r],F(t.options,"debugRows","getVisibleCells"))},createTable:e=>{const t=(n,s)=>k(()=>[s(),s().filter(r=>r.getIsVisible()).map(r=>r.id).join("_")],r=>r.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),F(e.options,"debugColumns",n));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var s;e.setColumnVisibility(n?{}:(s=e.initialState.columnVisibility)!=null?s:{})},e.toggleAllColumnsVisible=n=>{var s;n=(s=n)!=null?s:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((r,i)=>({...r,[i.id]:n||!(i.getCanHide!=null&&i.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var s;e.toggleAllColumnsVisible((s=n.target)==null?void 0:s.checked)}}};function mt(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}var hc={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},fc={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:Y("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const s=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof s=="string"||typeof s=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,s,r,i;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((s=t.options.enableGlobalFilter)!=null?s:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&((i=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?i:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>ge.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:s}=e.options;return pn(s)?s:s==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[s])!=null?t:ge[s]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},pc={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:Y("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var s,r;if(!t){e._queue(()=>{t=!0});return}if((s=(r=e.options.autoResetAll)!=null?r:e.options.autoResetExpanded)!=null?s:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=s=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(s),e.toggleAllRowsExpanded=s=>{s??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=s=>{var r,i;e.setExpanded(s?{}:(r=(i=e.initialState)==null?void 0:i.expanded)!=null?r:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(s=>s.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>s=>{s.persist==null||s.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const s=e.getState().expanded;return s===!0||Object.values(s).some(Boolean)},e.getIsAllRowsExpanded=()=>{const s=e.getState().expanded;return typeof s=="boolean"?s===!0:!(!Object.keys(s).length||e.getRowModel().flatRows.some(r=>!r.getIsExpanded()))},e.getExpandedDepth=()=>{let s=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(r=>{const i=r.split(".");s=Math.max(s,i.length)}),s},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(s=>{var r;const i=s===!0?!0:!!(s!=null&&s[e.id]);let o={};if(s===!0?Object.keys(t.getRowModel().rowsById).forEach(a=>{o[a]=!0}):o=s,n=(r=n)!=null?r:!i,!i&&n)return{...o,[e.id]:!0};if(i&&!n){const{[e.id]:a,...l}=o;return l}return s})},e.getIsExpanded=()=>{var n;const s=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:s===!0||s?.[e.id])},e.getCanExpand=()=>{var n,s,r;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((s=t.options.enableExpanding)!=null?s:!0)&&!!((r=e.subRows)!=null&&r.length)},e.getIsAllParentsExpanded=()=>{let n=!0,s=e;for(;n&&s.parentId;)s=t.getRow(s.parentId,!0),n=s.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},is=0,os=10,Pn=()=>({pageIndex:is,pageSize:os}),gc={getInitialState:e=>({...e,pagination:{...Pn(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:Y("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var s,r;if(!t){e._queue(()=>{t=!0});return}if((s=(r=e.options.autoResetAll)!=null?r:e.options.autoResetPageIndex)!=null?s:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=s=>{const r=i=>Ce(s,i);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(r)},e.resetPagination=s=>{var r;e.setPagination(s?Pn():(r=e.initialState.pagination)!=null?r:Pn())},e.setPageIndex=s=>{e.setPagination(r=>{let i=Ce(s,r.pageIndex);const o=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return i=Math.max(0,Math.min(i,o)),{...r,pageIndex:i}})},e.resetPageIndex=s=>{var r,i;e.setPageIndex(s?is:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageIndex)!=null?r:is)},e.resetPageSize=s=>{var r,i;e.setPageSize(s?os:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageSize)!=null?r:os)},e.setPageSize=s=>{e.setPagination(r=>{const i=Math.max(1,Ce(s,r.pageSize)),o=r.pageSize*r.pageIndex,a=Math.floor(o/i);return{...r,pageIndex:a,pageSize:i}})},e.setPageCount=s=>e.setPagination(r=>{var i;let o=Ce(s,(i=e.options.pageCount)!=null?i:-1);return typeof o=="number"&&(o=Math.max(-1,o)),{...r,pageCount:o}}),e.getPageOptions=k(()=>[e.getPageCount()],s=>{let r=[];return s&&s>0&&(r=[...new Array(s)].fill(null).map((i,o)=>o)),r},F(e.options,"debugTable","getPageOptions")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:s}=e.getState().pagination,r=e.getPageCount();return r===-1?!0:r===0?!1:s<r-1},e.previousPage=()=>e.setPageIndex(s=>s-1),e.nextPage=()=>e.setPageIndex(s=>s+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var s;return(s=e.options.pageCount)!=null?s:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var s;return(s=e.options.rowCount)!=null?s:e.getPrePaginationRowModel().rows.length}}},kn=()=>({top:[],bottom:[]}),mc={getInitialState:e=>({rowPinning:kn(),...e}),getDefaultOptions:e=>({onRowPinningChange:Y("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,s,r)=>{const i=s?e.getLeafRows().map(l=>{let{id:u}=l;return u}):[],o=r?e.getParentRows().map(l=>{let{id:u}=l;return u}):[],a=new Set([...o,e.id,...i]);t.setRowPinning(l=>{var u,c;if(n==="bottom"){var h,d;return{top:((h=l?.top)!=null?h:[]).filter(g=>!(a!=null&&a.has(g))),bottom:[...((d=l?.bottom)!=null?d:[]).filter(g=>!(a!=null&&a.has(g))),...Array.from(a)]}}if(n==="top"){var f,p;return{top:[...((f=l?.top)!=null?f:[]).filter(g=>!(a!=null&&a.has(g))),...Array.from(a)],bottom:((p=l?.bottom)!=null?p:[]).filter(g=>!(a!=null&&a.has(g)))}}return{top:((u=l?.top)!=null?u:[]).filter(g=>!(a!=null&&a.has(g))),bottom:((c=l?.bottom)!=null?c:[]).filter(g=>!(a!=null&&a.has(g)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:s,enablePinning:r}=t.options;return typeof s=="function"?s(e):(n=s??r)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:s,bottom:r}=t.getState().rowPinning,i=n.some(a=>s?.includes(a)),o=n.some(a=>r?.includes(a));return i?"top":o?"bottom":!1},e.getPinnedIndex=()=>{var n,s;const r=e.getIsPinned();if(!r)return-1;const i=(n=r==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(o=>{let{id:a}=o;return a});return(s=i?.indexOf(e.id))!=null?s:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,s;return e.setRowPinning(t?kn():(n=(s=e.initialState)==null?void 0:s.rowPinning)!=null?n:kn())},e.getIsSomeRowsPinned=t=>{var n;const s=e.getState().rowPinning;if(!t){var r,i;return!!((r=s.top)!=null&&r.length||(i=s.bottom)!=null&&i.length)}return!!((n=s[t])!=null&&n.length)},e._getPinnedRows=(t,n,s)=>{var r;return((r=e.options.keepPinnedRows)==null||r?(n??[]).map(i=>{const o=e.getRow(i,!0);return o.getIsAllParentsExpanded()?o:null}):(n??[]).map(i=>t.find(o=>o.id===i))).filter(Boolean).map(i=>({...i,position:s}))},e.getTopRows=k(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),F(e.options,"debugRows","getTopRows")),e.getBottomRows=k(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),F(e.options,"debugRows","getBottomRows")),e.getCenterRows=k(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,s)=>{const r=new Set([...n??[],...s??[]]);return t.filter(i=>!r.has(i.id))},F(e.options,"debugRows","getCenterRows"))}},vc={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:Y("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const s={...n},r=e.getPreGroupedRowModel().flatRows;return t?r.forEach(i=>{i.getCanSelect()&&(s[i.id]=!0)}):r.forEach(i=>{delete s[i.id]}),s})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const s=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),r={...n};return e.getRowModel().rows.forEach(i=>{as(r,i.id,s,!0,e)}),r}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=k(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?Fn(e,n):{rows:[],flatRows:[],rowsById:{}},F(e.options,"debugTable","getSelectedRowModel")),e.getFilteredSelectedRowModel=k(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?Fn(e,n):{rows:[],flatRows:[],rowsById:{}},F(e.options,"debugTable","getFilteredSelectedRowModel")),e.getGroupedSelectedRowModel=k(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?Fn(e,n):{rows:[],flatRows:[],rowsById:{}},F(e.options,"debugTable","getGroupedSelectedRowModel")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let s=!!(t.length&&Object.keys(n).length);return s&&t.some(r=>r.getCanSelect()&&!n[r.id])&&(s=!1),s},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(r=>r.getCanSelect()),{rowSelection:n}=e.getState();let s=!!t.length;return s&&t.some(r=>!n[r.id])&&(s=!1),s},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n<e.getFilteredRowModel().flatRows.length},e.getIsSomePageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,s)=>{const r=e.getIsSelected();t.setRowSelection(i=>{var o;if(n=typeof n<"u"?n:!r,e.getCanSelect()&&r===n)return i;const a={...i};return as(a,e.id,n,(o=s?.selectChildren)!=null?o:!0,t),a})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return $s(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return ls(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return ls(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return s=>{var r;n&&e.toggleSelected((r=s.target)==null?void 0:r.checked)}}}},as=(e,t,n,s,r)=>{var i;const o=r.getRow(t,!0);n?(o.getCanMultiSelect()||Object.keys(e).forEach(a=>delete e[a]),o.getCanSelect()&&(e[t]=!0)):delete e[t],s&&(i=o.subRows)!=null&&i.length&&o.getCanSelectSubRows()&&o.subRows.forEach(a=>as(e,a.id,n,s,r))};function Fn(e,t){const n=e.getState().rowSelection,s=[],r={},i=function(o,a){return o.map(l=>{var u;const c=$s(l,n);if(c&&(s.push(l),r[l.id]=l),(u=l.subRows)!=null&&u.length&&(l={...l,subRows:i(l.subRows)}),c)return l}).filter(Boolean)};return{rows:i(t.rows),flatRows:s,rowsById:r}}function $s(e,t){var n;return(n=t[e.id])!=null?n:!1}function ls(e,t,n){var s;if(!((s=e.subRows)!=null&&s.length))return!1;let r=!0,i=!1;return e.subRows.forEach(o=>{if(!(i&&!r)&&(o.getCanSelect()&&($s(o,t)?i=!0:r=!1),o.subRows&&o.subRows.length)){const a=ls(o,t);a==="all"?i=!0:(a==="some"&&(i=!0),r=!1)}}),r?"all":i?"some":!1}var us=/([0-9]+)/gm,Sc=(e,t,n)=>xo(Ae(e.getValue(n)).toLowerCase(),Ae(t.getValue(n)).toLowerCase()),yc=(e,t,n)=>xo(Ae(e.getValue(n)),Ae(t.getValue(n))),Ic=(e,t,n)=>Bs(Ae(e.getValue(n)).toLowerCase(),Ae(t.getValue(n)).toLowerCase()),Rc=(e,t,n)=>Bs(Ae(e.getValue(n)),Ae(t.getValue(n))),Cc=(e,t,n)=>{const s=e.getValue(n),r=t.getValue(n);return s>r?1:s<r?-1:0},bc=(e,t,n)=>Bs(e.getValue(n),t.getValue(n));function Bs(e,t){return e===t?0:e>t?1:-1}function Ae(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function xo(e,t){const n=e.split(us).filter(Boolean),s=t.split(us).filter(Boolean);for(;n.length&&s.length;){const r=n.shift(),i=s.shift(),o=parseInt(r,10),a=parseInt(i,10),l=[o,a].sort();if(isNaN(l[0])){if(r>i)return 1;if(i>r)return-1;continue}if(isNaN(l[1]))return isNaN(o)?-1:1;if(o>a)return 1;if(a>o)return-1}return n.length-s.length}var ut={alphanumeric:Sc,alphanumericCaseSensitive:yc,text:Ic,textCaseSensitive:Rc,datetime:Cc,basic:bc},wc={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:Y("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let s=!1;for(const r of n){const i=r?.getValue(e.id);if(Object.prototype.toString.call(i)==="[object Date]")return ut.datetime;if(typeof i=="string"&&(s=!0,i.split(us).length>1))return ut.alphanumeric}return s?ut.text:ut.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,s;if(!e)throw new Error;return pn(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(s=t.options.sortingFns)==null?void 0:s[e.columnDef.sortingFn])!=null?n:ut[e.columnDef.sortingFn]},e.toggleSorting=(n,s)=>{const r=e.getNextSortingOrder(),i=typeof n<"u"&&n!==null;t.setSorting(o=>{const a=o?.find(f=>f.id===e.id),l=o?.findIndex(f=>f.id===e.id);let u=[],c,h=i?n:r==="desc";if(o!=null&&o.length&&e.getCanMultiSort()&&s?a?c="toggle":c="add":o!=null&&o.length&&l!==o.length-1?c="replace":a?c="toggle":c="replace",c==="toggle"&&(i||r||(c="remove")),c==="add"){var d;u=[...o,{id:e.id,desc:h}],u.splice(0,u.length-((d=t.options.maxMultiSortColCount)!=null?d:Number.MAX_SAFE_INTEGER))}else c==="toggle"?u=o.map(f=>f.id===e.id?{...f,desc:h}:f):c==="remove"?u=o.filter(f=>f.id!==e.id):u=[{id:e.id,desc:h}];return u})},e.getFirstSortDir=()=>{var n,s;return((n=(s=e.columnDef.sortDescFirst)!=null?s:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var s,r;const i=e.getFirstSortDir(),o=e.getIsSorted();return o?o!==i&&((s=t.options.enableSortingRemoval)==null||s)&&(!(n&&(r=t.options.enableMultiRemove)!=null)||r)?!1:o==="desc"?"asc":"desc":i},e.getCanSort=()=>{var n,s;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((s=t.options.enableSorting)!=null?s:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,s;return(n=(s=e.columnDef.enableMultiSort)!=null?s:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const s=(n=t.getState().sorting)==null?void 0:n.find(r=>r.id===e.id);return s?s.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,s;return(n=(s=t.getState().sorting)==null?void 0:s.findIndex(r=>r.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(s=>s.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return s=>{n&&(s.persist==null||s.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(s):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,s;e.setSorting(t?[]:(n=(s=e.initialState)==null?void 0:s.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Ec=[Vu,dc,oc,ac,Ku,Qu,hc,fc,wc,rc,pc,gc,mc,vc,uc];function _c(e){var t,n;const s=[...Ec,...(t=e._features)!=null?t:[]];let r={_features:s};const i=r._features.reduce((h,d)=>Object.assign(h,d.getDefaultOptions==null?void 0:d.getDefaultOptions(r)),{}),o=h=>r.options.mergeOptions?r.options.mergeOptions(i,h):{...i,...h};let a={...(n=e.initialState)!=null?n:{}};r._features.forEach(h=>{var d;a=(d=h.getInitialState==null?void 0:h.getInitialState(a))!=null?d:a});const l=[];let u=!1;const c={_features:s,options:{...i,...e},initialState:a,_queue:h=>{l.push(h),u||(u=!0,Promise.resolve().then(()=>{for(;l.length;)l.shift()();u=!1}).catch(d=>setTimeout(()=>{throw d})))},reset:()=>{r.setState(r.initialState)},setOptions:h=>{const d=Ce(h,r.options);r.options=o(d)},getState:()=>r.options.state,setState:h=>{r.options.onStateChange==null||r.options.onStateChange(h)},_getRowId:(h,d,f)=>{var p;return(p=r.options.getRowId==null?void 0:r.options.getRowId(h,d,f))!=null?p:`${f?[f.id,d].join("."):d}`},getCoreRowModel:()=>(r._getCoreRowModel||(r._getCoreRowModel=r.options.getCoreRowModel(r)),r._getCoreRowModel()),getRowModel:()=>r.getPaginationRowModel(),getRow:(h,d)=>{let f=(d?r.getPrePaginationRowModel():r.getRowModel()).rowsById[h];if(!f&&(f=r.getCoreRowModel().rowsById[h],!f))throw new Error;return f},_getDefaultColumnDef:k(()=>[r.options.defaultColumn],h=>{var d;return h=(d=h)!=null?d:{},{header:f=>{const p=f.header.column.columnDef;return p.accessorKey?p.accessorKey:p.accessorFn?p.id:null},cell:f=>{var p,g;return(p=(g=f.renderValue())==null||g.toString==null?void 0:g.toString())!=null?p:null},...r._features.reduce((f,p)=>Object.assign(f,p.getDefaultColumnDef==null?void 0:p.getDefaultColumnDef()),{}),...h}},F(e,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>r.options.columns,getAllColumns:k(()=>[r._getColumnDefs()],h=>{const d=function(f,p,g){return g===void 0&&(g=0),f.map(m=>{const v=zu(r,m,g,p),S=m;return v.columns=S.columns?d(S.columns,v,g+1):[],v})};return d(h)},F(e,"debugColumns","getAllColumns")),getAllFlatColumns:k(()=>[r.getAllColumns()],h=>h.flatMap(d=>d.getFlatColumns()),F(e,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:k(()=>[r.getAllFlatColumns()],h=>h.reduce((d,f)=>(d[f.id]=f,d),{}),F(e,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:k(()=>[r.getAllColumns(),r._getOrderColumnsFn()],(h,d)=>d(h.flatMap(f=>f.getLeafColumns())),F(e,"debugColumns","getAllLeafColumns")),getColumn:h=>r._getAllFlatColumnsById()[h]};Object.assign(r,c);for(let h=0;h<r._features.length;h++){const d=r._features[h];d==null||d.createTable==null||d.createTable(r)}return r}function Uf(){return e=>k(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},s=function(r,i,o){i===void 0&&(i=0);const a=[];for(let u=0;u<r.length;u++){const c=qu(e,e._getRowId(r[u],u,o),r[u],u,i,void 0,o?.id);if(n.flatRows.push(c),n.rowsById[c.id]=c,a.push(c),e.options.getSubRows){var l;c.originalSubRows=e.options.getSubRows(r[u],u),(l=c.originalSubRows)!=null&&l.length&&(c.subRows=s(c.originalSubRows,i+1,c))}}return a};return n.rows=s(t),n},F(e.options,"debugTable","getRowModel",()=>e._autoResetPageIndex()))}function Hf(){return e=>k(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const s=e.getState().sorting,r=[],i=s.filter(l=>{var u;return(u=e.getColumn(l.id))==null?void 0:u.getCanSort()}),o={};i.forEach(l=>{const u=e.getColumn(l.id);u&&(o[l.id]={sortUndefined:u.columnDef.sortUndefined,invertSorting:u.columnDef.invertSorting,sortingFn:u.getSortingFn()})});const a=l=>{const u=l.map(c=>({...c}));return u.sort((c,h)=>{for(let f=0;f<i.length;f+=1){var d;const p=i[f],g=o[p.id],m=g.sortUndefined,v=(d=p?.desc)!=null?d:!1;let S=0;if(m){const C=c.getValue(p.id),b=h.getValue(p.id),w=C===void 0,R=b===void 0;if(w||R){if(m==="first")return w?-1:1;if(m==="last")return w?1:-1;S=w&&R?0:w?m:-m}}if(S===0&&(S=g.sortingFn(c,h,p.id)),S!==0)return v&&(S*=-1),g.invertSorting&&(S*=-1),S}return c.index-h.index}),u.forEach(c=>{var h;r.push(c),(h=c.subRows)!=null&&h.length&&(c.subRows=a(c.subRows))}),u};return{rows:a(n.rows),flatRows:r,rowsById:n.rowsById}},F(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function zf(e,t){return e?Tc(e)?I.createElement(e,t):e:null}function Tc(e){return Ac(e)||typeof e=="function"||Mc(e)}function Ac(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function Mc(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Vf(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=I.useState(()=>({current:_c(t)})),[s,r]=I.useState(()=>n.current.initialState);return n.current.setOptions(i=>({...i,...e,state:{...s,...e.state},onStateChange:o=>{r(o),e.onStateChange==null||e.onStateChange(o)}})),n.current}var Oc=bi(ca(),1);function We(e,t,n){let s=n.initialDeps??[],r,i=!0;function o(){var a,l,u;let c;n.key&&((a=n.debug)!=null&&a.call(n))&&(c=Date.now());const h=e();if(!(h.length!==s.length||h.some((f,p)=>s[p]!==f)))return r;s=h;let d;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(d=Date.now()),r=t(...h),n.key&&((u=n.debug)!=null&&u.call(n))){const f=Math.round((Date.now()-c)*100)/100,p=Math.round((Date.now()-d)*100)/100,g=p/16,m=(v,S)=>{for(v=String(v);v.length<S;)v=" "+v;return v};console.info(`%c⏱ ${m(p,5)} /${m(f,5)} ms`,`
|
|
6
|
-
font-size: .6rem;
|
|
7
|
-
font-weight: bold;
|
|
8
|
-
color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(r),i=!1,r}return o.updateDeps=a=>{s=a},o}function Or(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var xc=(e,t)=>Math.abs(e-t)<1.01,Pc=(e,t,n)=>{let s;return function(...r){e.clearTimeout(s),s=e.setTimeout(()=>t.apply(this,r),n)}},xr=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},kc=e=>e,Fc=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),s=[];for(let r=t;r<=n;r++)s.push(r);return s},Lc=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;const r=o=>{const{width:a,height:l}=o;t({width:Math.round(a),height:Math.round(l)})};if(r(xr(n)),!s.ResizeObserver)return()=>{};const i=new s.ResizeObserver(o=>{const a=()=>{const l=o[0];if(l?.borderBoxSize){const u=l.borderBoxSize[0];if(u){r({width:u.inlineSize,height:u.blockSize});return}}r(xr(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},Pr={passive:!0},kr=typeof window>"u"?!0:"onscrollend"in window,Nc=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;let r=0;const i=e.options.useScrollendEvent&&kr?()=>{}:Pc(s,()=>{t(r,!1)},e.options.isScrollingResetDelay),o=c=>()=>{const{horizontal:h,isRtl:d}=e.options;r=h?n.scrollLeft*(d&&-1||1):n.scrollTop,i(),t(r,c)},a=o(!0),l=o(!1);n.addEventListener("scroll",a,Pr);const u=e.options.useScrollendEvent&&kr;return u&&n.addEventListener("scrollend",l,Pr),()=>{n.removeEventListener("scroll",a),u&&n.removeEventListener("scrollend",l)}},Dc=(e,t,n)=>{if(t?.borderBoxSize){const s=t.borderBoxSize[0];if(s)return Math.round(s[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},jc=(e,{adjustments:t=0,behavior:n},s)=>{var r,i;const o=e+t;(i=(r=s.scrollElement)==null?void 0:r.scrollTo)==null||i.call(r,{[s.options.horizontal?"left":"top"]:o,behavior:n})},Gc=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,n,s;return((s=(n=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:n.now)==null?void 0:s.call(n))??Date.now()},this.observer=(()=>{let t=null;const n=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(s=>{s.forEach(r=>{const i=()=>{const o=r.target,a=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(a)&&this.resizeItem(a,this.options.measureElement(o,r,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var s;(s=n())==null||s.disconnect(),t=null},observe:s=>{var r;return(r=n())==null?void 0:r.observe(s,{box:"border-box"})},unobserve:s=>{var r;return(r=n())==null?void 0:r.unobserve(s)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([n,s])=>{typeof s>"u"&&delete t[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:kc,rangeExtractor:Fc,onChange:()=>{},measureElement:Dc,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var n,s;(s=(n=this.options).onChange)==null||s.call(n,this,t)},this.maybeNotify=We(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,r)=>{this.scrollAdjustments=0,this.scrollDirection=r?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=r,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,n)=>{const s=new Map,r=new Map;for(let i=n-1;i>=0;i--){const o=t[i];if(s.has(o.lane))continue;const a=r.get(o.lane);if(a==null||o.end>a.end?r.set(o.lane,o):o.end<a.end&&s.set(o.lane,!0),s.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((i,o)=>i.end===o.end?i.index-o.index:i.end-o.end)[0]:void 0},this.getMeasurementOptions=We(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,n,s,r,i,o,a)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:n,scrollMargin:s,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a}),{key:!1}),this.getMeasurements=We(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:n,scrollMargin:s,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a},l)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const d of this.laneAssignments.keys())d>=t&&this.laneAssignments.delete(d);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(d=>{this.itemSizeCache.set(d.key,d.size)}));const u=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const c=this.measurementsCache.slice(0,u),h=new Array(o).fill(void 0);for(let d=0;d<u;d++){const f=c[d];f&&(h[f.lane]=d)}for(let d=u;d<t;d++){const f=r(d),p=this.laneAssignments.get(d);let g,m;const v=a==="estimate"||l.has(f);if(p!==void 0&&this.options.lanes>1){g=p;const w=h[g],R=w!==void 0?c[w]:void 0;m=R?R.end+this.options.gap:n+s}else{const w=this.options.lanes===1?c[d-1]:this.getFurthestMeasurement(c,d);m=w?w.end+this.options.gap:n+s,g=w?w.lane:d%this.options.lanes,this.options.lanes>1&&v&&this.laneAssignments.set(d,g)}const S=l.get(f),C=typeof S=="number"?S:this.options.estimateSize(d),b=m+C;c[d]={index:d,start:m,size:C,end:b,key:f,lane:g},h[g]=d}return this.measurementsCache=c,c},{key:!1,debug:()=>this.options.debug}),this.calculateRange=We(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,n,s,r)=>this.range=t.length>0&&n>0?$c({measurements:t,outerSize:n,scrollOffset:s,lanes:r}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=We(()=>{let t=null,n=null;const s=this.calculateRange();return s&&(t=s.startIndex,n=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,n]},(t,n,s,r,i)=>r===null||i===null?[]:t({startIndex:r,endIndex:i,overscan:n,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const n=this.options.indexAttribute,s=t.getAttribute(n);return s?parseInt(s,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(s!==void 0&&this.range){const r=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,s-r),o=Math.min(this.options.count-1,s+r);return t>=i&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((i,o)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(o))});return}const n=this.indexFromElement(t),s=this.options.getItemKey(n),r=this.elementsCache.get(s);r!==t&&(r&&this.observer.unobserve(r),this.observer.observe(t),this.elementsCache.set(s,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,n)=>{var s;const r=this.measurementsCache[t];if(!r)return;const i=n-(this.itemSizeCache.get(r.key)??r.size);i!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,i,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,n)),this.notify(!1))},this.getVirtualItems=We(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,n)=>{const s=[];for(let r=0,i=t.length;r<i;r++){const o=n[t[r]];s.push(o)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const n=this.getMeasurements();if(n.length!==0)return Or(n[Po(0,n.length-1,s=>Or(n[s]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,n,s=0)=>{if(!this.scrollElement)return 0;const r=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=t>=i+r?"end":"start"),n==="center"?t+=(s-r)/2:n==="end"&&(t-=r);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,n="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const s=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[t];if(!i)return;if(n==="auto")if(i.end>=r+s-this.options.scrollPaddingEnd)n="end";else if(i.start<=r+this.options.scrollPaddingStart)n="start";else return[r,n];if(n==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),n];const o=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,n,i.size),n]},this.scrollToOffset=(t,{align:n="start",behavior:s="auto"}={})=>{const r=this.getOffsetForAlignment(t,n),i=this.now();this.scrollState={index:null,align:n,behavior:s,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:n="auto",behavior:s="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const r=this.getOffsetForIndex(t,n);if(!r)return;const[i,o]=r,a=this.now();this.scrollState={index:t,align:o,behavior:s,startedAt:a,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:n="auto"}={})=>{const s=this.getScrollOffset()+t,r=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:r,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const n=this.getMeasurements();let s;if(n.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((t=n[n.length-1])==null?void 0:t.end)??0;else{const r=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&r.some(o=>o===null);){const o=n[i];r[o.lane]===null&&(r[o.lane]=o.end),i--}s=Math.max(...r.filter(o=>o!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:n,behavior:s})=>{this.options.scrollToFn(t,{behavior:s,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const e=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,t=e?e[0]:this.scrollState.lastTargetOffset,n=1,s=t!==this.scrollState.lastTargetOffset;if(!s&&xc(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=n){this.scrollState=null;return}}else this.scrollState.stableFrames=0,s&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior="auto",this._scrollToOffset(t,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}},Po=(e,t,n,s)=>{for(;e<=t;){const r=(e+t)/2|0,i=n(r);if(i<s)e=r+1;else if(i>s)t=r-1;else return r}return e>0?e-1:0};function $c({measurements:e,outerSize:t,scrollOffset:n,lanes:s}){const r=e.length-1,i=l=>e[l].start;if(e.length<=s)return{startIndex:0,endIndex:r};let o=Po(0,r,i,n),a=o;if(s===1)for(;a<r&&e[a].end<n+t;)a++;else if(s>1){const l=Array(s).fill(0);for(;a<r&&l.some(c=>c<n+t);){const c=e[a];l[c.lane]=c.end,a++}const u=Array(s).fill(n+t);for(;o>=0&&u.some(c=>c>=n);){const c=e[o];u[c.lane]=c.start,o--}o=Math.max(0,o-o%s),a=Math.min(r,a+(s-1-a%s))}return{startIndex:o,endIndex:a}}var Fr=typeof document<"u"?I.useLayoutEffect:I.useEffect;function Bc({useFlushSync:e=!0,...t}){const n=I.useReducer(()=>({}),{})[1],s={...t,onChange:(i,o)=>{var a;e&&o?(0,Oc.flushSync)(n):n(),(a=t.onChange)==null||a.call(t,i,o)}},[r]=I.useState(()=>new Gc(s));return r.setOptions(s),Fr(()=>r._didMount(),[]),Fr(()=>r._willUpdate()),r}function qf(e){return Bc({observeElementRect:Lc,observeElementOffset:Nc,scrollToFn:jc,...e})}function Uc(){return{id:"memory",label:"Session only (not saved)",persistent:!1,warning:"Keys stay in memory for this tab only. They are not saved across reloads.",load:()=>({}),save:()=>{},clear:()=>{}}}var Hc=/^[a-z][a-z0-9-]{0,63}$/,zc="x-byok-";function ie(e){return typeof e=="string"&&Hc.test(e)}function Lr(e){if(!ie(e))throw new Error(`Invalid BYOK provider id: ${e}`);return`${zc}${e}`}function Vc(e){if(typeof e!="object"||e===null||!("error"in e))return!1;const t=e.error;return!(typeof t!="object"||t===null||!("type"in t)||t.type!=="byok_missing"||!("provider"in t)||typeof t.provider!="string"||!ie(t.provider)||!("message"in t)||typeof t.message!="string")}var cs=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name="ByokMissingError",this.provider=e}},on=class extends Error{provider;reason;constructor(e,t){super(t==="locked"?`${e} key is locked`:`Missing ${e} API key`),this.name="ByokBlockedError",this.provider=e,this.reason=t}},ko=class extends Error{constructor(){super("BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider."),this.name="ByokUnresolvedProviderError"}};function $t(e){return e.length<=4?"••":e.slice(-4)}var qc={status:{},locked:!1,prompt:null,storageError:null};function Oe(e){if(!ie(e))throw new Error(`Invalid BYOK provider id: ${e}`);return e}function Bt(e,t){return e instanceof Error&&e.message.length>0?e.message:t}function Kc(e){if(typeof DOMException<"u"&&e instanceof DOMException&&e.name==="NotAllowedError")return!0;if(e instanceof Error){if(e.name==="NotAllowedError")return!0;const t=e.message.toLowerCase();return t.includes("cancelled")||t.includes("not allowed")}return!1}function Nr(e){if(typeof e!="object"||e===null)return{};const t={};for(const[n,s]of Object.entries(e))ie(n)&&typeof s=="string"&&s.length>0&&(t[n]=s);return t}var Qc=class{storage;#t={};#e={};#n;#s=null;#i=!1;#r={};#a={};#l=new Set;#h;#o=null;#u;constructor(e={}){this.storage=e.storage??Uc();for(const t of e.providers??[])t.with?.length&&(this.#a[Oe(t.id)]=t.with.map(n=>Oe(n.id)));this.#n=!!this.storage.unlockable,this.#h=this.#f(),this.#u=this.#m()}ready=()=>this.#u;subscribe=e=>(this.#l.add(e),()=>{this.#l.delete(e)});getSnapshot=()=>this.#h;#f(){return{status:{...this.#e},locked:this.#n,prompt:this.#s,storageError:this.#o}}keys(){return{...this.#t}}request(e,t){this.#s={provider:Oe(e),reason:t},this.#c()}setServerCoverage(e){if(typeof e=="boolean"){this.#i=e,this.#r={};return}this.#i=!1,this.#r={...this.#r,...e}}#d(e){return this.#i||this.#r[e]===!0}#p(e){return[e,...this.#a[e]??[]]}headers(e){const t={};if(e){Oe(e);for(const n of this.#p(e)){const s=this.#t[n];s&&(t[Lr(n)]=s)}return t}for(const[n,s]of Object.entries(this.#t))s&&(t[Lr(n)]=s);return t}async prepare(e){if(await this.#u,this.storage.unlockable&&this.#n&&await this.unlock(),!!e){Oe(e);for(const t of this.#p(e))if(!(this.#t[t]||this.#d(t)))throw this.request(t,"missing"),new on(t,"missing")}}async update(e,t){await this.#u;let n,s;if(t===void 0){if(!this.#s)throw new Error("byok.update(key) cannot run when prompt is null");n=this.#s.provider,s=e}else n=Oe(e),s=t;if(s=s.trim(),s.length===0)throw new Error("BYOK key must be non-empty");this.storage.unlockable&&this.#n&&await this.unlock();const r=this.#t,i={...this.#e},o=this.#n,a=this.#s,l=this.#o,u={...this.#t,[n]:s};try{await this.storage.save(u)}catch(c){throw this.#t=r,this.#e=i,this.#n=o,this.#s=a,this.#o=l,this.#e[n]={state:"error",masked:$t(s),message:Bt(c,`Failed to persist ${n} key`)},this.#c(),c}this.#t=u,this.#e[n]={state:"set",masked:$t(s)},this.#n=!1,this.#s=null,this.#o=null,this.#c()}async clear(e){if(await this.#u,e){Oe(e),this.storage.unlockable&&this.#n&&await this.unlock();const i=this.#t,o={...this.#e},a={...this.#t};delete a[e];try{await this.storage.save(a)}catch(l){throw this.#t=i,this.#e=o,this.#c(),l}this.#t=a,delete this.#e[e],this.#c();return}const t=this.#t,n=this.#e,s=this.#n,r=this.#s;try{await this.storage.clear()}catch(i){throw this.#t=t,this.#e=n,this.#n=s,this.#s=r,this.#c(),i}this.#t={},this.#e={},this.#n=!1,this.#s=null,this.#o=null,this.#c()}async unlock(){if(await this.#u,!!this.storage.unlockable)try{const e=Nr(await this.storage.load());this.#t={...e,...this.#t};for(const[t,n]of Object.entries(e)){if(!ie(t)||!n)continue;const s=this.#e[t];(!s||s.state==="locked")&&(this.#e[t]={state:"set",masked:$t(n)})}this.#n=!1,this.#o=null,this.#c()}catch(e){if(Kc(e)){const t=this.#g();if(t)throw this.request(t,"locked"),new on(t,"locked")}throw this.#o=Bt(e,"Failed to unlock keyring"),this.#c(),e instanceof Error?e:new Error(String(e))}}#g(){if(this.#s&&ie(this.#s.provider))return this.#s.provider;for(const[e,t]of Object.entries(this.#e))if(t?.state==="locked"&&ie(e))return e}async#m(){if(this.storage.unlockable){if(!this.storage.peek)return;try{const e=await this.storage.peek();for(const[t,n]of Object.entries(e))!ie(t)||this.#e[t]||(this.#e[t]={state:"locked",masked:n||"••"});this.#n=Object.keys(e).length>0,this.#o=null,this.#c()}catch(e){this.#o=Bt(e,"Failed to read keyring"),this.#c()}return}try{const e=Nr(await this.storage.load());this.#t={...e,...this.#t};for(const[t,n]of Object.entries(e))!ie(t)||!n||(this.#e[t]={state:"set",masked:$t(n)});this.#o=null,this.#c()}catch(e){this.#o=Bt(e,"Failed to read keyring"),this.#c()}}#c(){this.#h=this.#f();for(const e of this.#l)e()}};function Kf(e={}){return new Qc(e)}var ds=class extends Error{missingFeature;constructor(e){super(Wc(e)),this.name="UnsupportedResponseStreamError",this.missingFeature=e}};function Wc(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function Jc(e){if(!e.body)throw new ds("Response.body");if(typeof e.body.getReader!="function")throw new ds("Response.body.getReader");return e.body.getReader()}function Xc(){if(typeof globalThis.TextDecoder!="function")throw new ds("TextDecoder");return new globalThis.TextDecoder}function Yc(e){if(!e.startsWith("data:"))return e;const t=e.slice(5);return t.startsWith(" ")?t.slice(1):t}function Dr(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!="string")return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function Zc(e){const t=Dr(e.createdAt),n=e.parts.map(i=>{if(i.type!=="tool-result")return i;const o=Dr(i.createdAt),{createdAt:a,...l}=i;return o?{...l,createdAt:o}:l}),{createdAt:s,...r}=e;return t?{...r,parts:n,createdAt:t}:{...r,parts:n}}function Fo(e){return e.map(Zc)}function jr(e){return Object.keys(e).length>0?e:void 0}function Lo(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)&&"promptTokens"in e}function ed(e,t){return Lo(e)?e:Array.isArray(e)?Gr(e,t):Gr(void 0,t)}function Gr(e,t){const n=e?.[0];if(n==null&&t==null)return;const{promptTokensDetails:s,completionTokensDetails:r,...i}=t??{},o=jr({...n?.cachedInputTokens!==void 0?{cachedTokens:n.cachedInputTokens}:{},...s}),a=jr({...n?.reasoningTokens!==void 0?{reasoningTokens:n.reasoningTokens}:{},...r});return{promptTokens:n?.inputTokens??0,completionTokens:n?.outputTokens??0,totalTokens:n?.totalTokens??0,...i,...o!==void 0?{promptTokensDetails:o}:{},...a!==void 0?{completionTokensDetails:a}:{}}}function $r(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function No(e,t){if(t==null)return e;if(e==null)return{...t};const n={...e,...t};return $r(e.tanstack)&&$r(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function B(e){if(e==null)return;const t="metadata"in e?e.metadata:void 0,n=(t!=null&&typeof t=="object"&&!Array.isArray(t)?t:e).tanstack;if(!(n==null||typeof n!="object"||Array.isArray(n)))return n}function Do(e,t){const n=e.metadata,s=B(e)??{};return{...e,metadata:{...n??{},tanstack:{...s,...t}}}}var Ut=(function(e){return e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e})({}),td=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function le(e,t){return e>>>t|e<<32-t}function nd(e){const t=new TextEncoder().encode(e),n=t.length*8,s=t.length+1,r=s+(56-s%64+64)%64+8,i=new Uint8Array(r);i.set(t),i[t.length]=128;const o=new DataView(i.buffer);o.setUint32(r-8,Math.floor(n/4294967296)),o.setUint32(r-4,n>>>0);let a=1779033703,l=3144134277,u=1013904242,c=2773480762,h=1359893119,d=2600822924,f=528734635,p=1541459225;const g=new Uint32Array(64);for(let v=0;v<r;v+=64){for(let T=0;T<16;T++)g[T]=o.getUint32(v+T*4);for(let T=16;T<64;T++){const M=g[T-15]??0,A=g[T-2]??0,x=le(M,7)^le(M,18)^M>>>3,P=le(A,17)^le(A,19)^A>>>10;g[T]=(g[T-16]??0)+x+(g[T-7]??0)+P>>>0}let S=a,C=l,b=u,w=c,R=h,y=d,_=f,O=p;for(let T=0;T<64;T++){const M=le(R,6)^le(R,11)^le(R,25),A=R&y^~R&_,x=O+M+A+(td[T]??0)+(g[T]??0)>>>0,P=(le(S,2)^le(S,13)^le(S,22))+(S&C^S&b^C&b)>>>0;O=_,_=y,y=R,R=w+x>>>0,w=b,b=C,C=S,S=x+P>>>0}a=a+S>>>0,l=l+C>>>0,u=u+b>>>0,c=c+w>>>0,h=h+R>>>0,d=d+y>>>0,f=f+_>>>0,p=p+O>>>0}const m=v=>(v>>>0).toString(16).padStart(8,"0");return m(a)+m(l)+m(u)+m(c)+m(h)+m(d)+m(f)+m(p)}function sd(e){return`sha256:${nd(e)}`}function hs(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!="object")throw new TypeError("Interrupt values must be JSON-compatible.");if(t.has(e))throw new TypeError("Interrupt values must not cycle.");if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError("Interrupt values must use plain JSON objects.");t.add(e);let n;if(Array.isArray(e)){const s=[];for(let r=0;r<e.length;r++)s.push(hs(e[r],t));n=`[${s.join(",")}]`}else{const s=e;n=`{${Object.keys(s).sort().map(r=>`${JSON.stringify(r)}:${hs(s[r],t)}`).join(",")}}`}return t.delete(e),n}function je(e){return hs(e,new WeakSet)}function Ge(e,t=sd){if(typeof e!="string")throw new TypeError("Interrupt digests require canonical JSON text.");return t(e)}function jo(e){e===null||typeof e!="object"||Object.isFrozen(e)||(Object.values(e).forEach(jo),Object.freeze(e))}function U(e){const t=JSON.parse(je(e));return jo(t),t}function rd(e){const t=[...e].sort((r,i)=>r.interruptId.localeCompare(i.interruptId)),n=U(t),s=je(n);return Object.freeze({resolutions:n,canonicalResolutions:s,fingerprint:Ge(s)})}function Br(e){const t={};for(const[n,s]of Object.entries(e))n!=="$schema"&&(t[n]=s);return t}function Go(e){return(typeof e=="object"||typeof e=="function")&&e!==null}function Et(e){if(!Go(e)||!("~standard"in e))return!1;const t=e["~standard"];return typeof t!="object"||t===null||!("version"in t)||t.version!==1||!("jsonSchema"in t)||typeof t.jsonSchema!="object"||t.jsonSchema===null||!("input"in t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function Me(e){return Go(e)&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"version"in e["~standard"]&&e["~standard"].version===1&&"validate"in e["~standard"]&&typeof e["~standard"].validate=="function"}function id(e){return Object.keys(e).length>0?e:void 0}function Ur(e){if(Array.isArray(e)){const n=e.map(r=>an(r,r.required||[])),s=n.map(r=>r.nullWidening??{});return{schema:n.map(r=>r.schema),itemMap:s.some(r=>Object.keys(r).length>0)?s:void 0}}const t=an(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function an(e,t=[]){const n={...e},s={};if(n.type==="object"&&n.properties){const r={...n.properties},i=Object.keys(r),o={};for(const a of i){const l=r[a];if(!l)continue;const u=!t.includes(a);let c=!1,h;if(l.type==="object"&&l.properties){const d=an(l,l.required||[]);r[a]=u?{...d.schema,type:["object","null"]}:d.schema,c=u,h=d.nullWidening}else if(l.type==="array"&&l.items){const d=Ur(l.items);r[a]={...l,items:d.schema,...u?{type:["array","null"]}:{}},c=u,h=d.itemMap?{items:d.itemMap}:void 0}else u&&(l.type&&!Array.isArray(l.type)?(r[a]={...l,type:[l.type,"null"]},c=!0):Array.isArray(l.type)&&!l.type.includes("null")&&(r[a]={...l,type:[...l.type,"null"]},c=!0));(c||h)&&(o[a]={...h??{},...c?{widened:!0}:{}})}n.properties=r,n.required=i,n.additionalProperties=!1,Object.keys(o).length>0&&(s.properties=o)}if(n.type==="array"&&n.items){const r=Ur(n.items);n.items=r.schema,r.itemMap&&(s.items=r.itemMap)}return{schema:n,nullWidening:id(s)}}function od(e){if(Et(e)){const t=Br(e["~standard"].jsonSchema.input({target:"draft-07"}));return"properties"in t&&!t.type&&(t.type="object"),t.type==="object"&&!("properties"in t)&&(t.properties={}),t.type==="object"&&!("required"in t)&&(t.required=[]),t}if(Me(e))throw new Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e!="object"?e:Br(e)}function fs(e,t={}){if(!e)return;const{forStructuredOutput:n=!1}=t;if(!n&&!Et(e)&&!Me(e))return e;const s=od(e);return!s||typeof s!="object"||!n?s:an(s,s.required||[]).schema}var ad=class extends Error{name="StandardSchemaValidationError";issues;constructor(e){super(`Validation failed: ${e.map(t=>t.message||"Validation failed").join(", ")}`),this.issues=e}};function ld(e,t){if(!Me(e))return t;const n=e["~standard"].validate(t);if(n instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!n.issues)return n.value;throw new ad(n.issues)}var ud=new Set(["$schema","$id","$ref","$defs","type","properties","required","additionalProperties","items","oneOf","anyOf","allOf","enum","const","format","minimum","maximum","minLength","maxLength","pattern"]);function $o(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Us(e){return $o(e)&&Object.keys(e).some(t=>ud.has(t))}function cd(e){return Me(e)||Et(e)||Us(e)}function dd(e){if(!$o(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>n==="approve"||n==="reject")&&t.every(n=>cd(e[n]))}function hd(e){const t={};for(const[n,s]of Object.entries(e))t[n]=s;return t}function dt(e){if(Me(e)){const t=Et(e)?hd(e["~standard"].jsonSchema.input({target:"draft-2020-12"})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Us(e))return{source:e,jsonSchema:e};throw new TypeError("Expected a supported SchemaInput.")}function Hr(e){const t={approved:{const:e.approved}},n=["approved"];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push("payload")),{type:"object",properties:t,required:n,additionalProperties:!1}}function fd(e,t){const n=t===void 0?null:dt(t);let s=null,r=null;if(e!==void 0)if(Me(e)||Us(e))s=dt(e),r=s;else if(dd(e))s=e.approve===void 0?null:dt(e.approve),r=e.reject===void 0?null:dt(e.reject);else throw new TypeError("approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.");const i={oneOf:[Hr({approved:!0,payload:s,inputSchema:n}),Hr({approved:!1,payload:r,inputSchema:null})]},o=je(i),a=je({approve:s?.jsonSchema??null,reject:r?.jsonSchema??null});return{branches:{approve:s,reject:r},responseSchema:i,responseSchemaHash:Ge(o),approvalSchemaHash:Ge(a)}}function zr(e){if(e===void 0)return Ge("undefined");const t=dt(e).jsonSchema??{standardValidator:"unserialized"};return Ge(je(t))}var gn="tanstack:interruptBinding",Bo=gn;function ln(e){return e&&typeof e=="object"?e:null}function Q(e,t){return typeof e[t]=="string"?e[t]:void 0}function pd(e){const t=e.v;return t===void 0?!0:t===1}function Uo(e){const t=ln(e.metadata),n=t?ln(t[Bo]):null;if(!n||Q(n,"interruptId")!==e.id||!pd(n))return;const s=Q(n,"kind"),r=Q(n,"interruptId"),i=Q(n,"responseSchemaHash"),o=Q(n,"expiresAt");if(!r||i===""||o!==void 0&&!Number.isFinite(Date.parse(o)))return;const a=1;if(s==="generic"){const c=Q(n,"definitionId"),h=Q(n,"key"),d=n.batchIndex,f=Q(n,"payloadSchemaHash");return(c!==void 0||h!==void 0||d!==void 0||f!==void 0)&&(!c||!h||typeof d!="number"||!Number.isInteger(d)||d<0)?void 0:{v:a,kind:s,interruptId:r,...i?{responseSchemaHash:i}:{},...o?{expiresAt:o}:{},...c?{definitionId:c}:{},...h?{key:h}:{},...typeof d=="number"?{batchIndex:d}:{},...f?{payloadSchemaHash:f}:{}}}if(!i)return;const l=Q(n,"toolName"),u=Q(n,"toolCallId");if(!(!l||!u)){if(s==="client-tool-execution"){const c=Q(n,"outputSchemaHash");return c?{v:a,kind:s,interruptId:r,toolName:l,toolCallId:u,outputSchemaHash:c,responseSchemaHash:i,...o?{expiresAt:o}:{}}:void 0}if(s==="tool-approval"){const c=Q(n,"inputSchemaHash"),h=Q(n,"approvalSchemaHash");return!c||!h?void 0:{v:a,kind:s,interruptId:r,toolName:l,toolCallId:u,originalArgs:n.originalArgs,inputSchemaHash:c,approvalSchemaHash:h,responseSchemaHash:i,...o?{expiresAt:o}:{}}}}}function gd(e){const t=Uo(e);if(!t)return;const n=ln(e.metadata),s=n?ln(n[Bo]):null;if(!s)return;const r=Q(s,"interruptedRunId"),i=s.generation;if(!(!r||typeof i!="number"||!Number.isInteger(i)||i<0))return{...t,interruptedRunId:r,generation:i}}var md="tanstack:interruptPayload";function vd(e,t){if(!Et(e))throw new TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{const n=e["~standard"].jsonSchema.input({target:"draft-07"});if(n===void 0)throw new TypeError("The exported schema is undefined.");if(typeof n=="function")throw new TypeError("The exported schema must not be a function.");if(Array.isArray(n))throw new TypeError("The exported schema must be a plain JSON object.");if(!n||typeof n!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(n)))throw new TypeError("The exported schema must be a plain JSON object.");const s={};for(const[r,i]of Object.entries(n))r!=="$schema"&&(s[r]=i);return{json:s,canonicalJson:je(s)}}catch(n){throw new TypeError(`${t} could not export compatible JSON Schema: ${n instanceof Error?n.message:String(n)}`)}}function Sd(e){return Ge(vd(e,"Interrupt schema").canonicalJson)}var yd="tanstack:interruptContinuation";function Id(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Rd(e){return{[yd]:e}}function Cd(e){const t=Uo(e);if(t?.kind!=="generic"||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;const n=Id(e.metadata)?e.metadata:void 0,s=n!==void 0&&Object.prototype.hasOwnProperty.call(n,"tanstack:interruptPayload");return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??"",...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{},...t.responseSchemaHash!==void 0?{responseSchemaHash:t.responseSchemaHash}:{},...t.payloadSchemaHash!==void 0?{payloadSchemaHash:t.payloadSchemaHash}:{},...s?{payload:n[md]}:{}}}var bd=new Set(["text","image","audio","video","document"]);function wd(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.type!="string"||!bd.has(t.type))return!1;if(t.type==="text")return typeof t.content=="string";const n=t.source;if(typeof n!="object"||n===null)return!1;const s=n;return typeof s.value!="string"?!1:s.type==="data"?typeof s.mimeType=="string":s.type==="url"}function ps(e){return Array.isArray(e)&&e.length>0&&e.every(wd)}function Hs(e){return typeof e=="string"||ps(e)?e:JSON.stringify(e)}function Ed(e){const t=e?.metadata;return typeof t=="object"&&t!==null&&t.providerExecuted===!0?t:null}function Ho(e){return Ed(e)!==null}function Ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _d(e){return e.type==="text"||e.type==="image"||e.type==="audio"||e.type==="video"||e.type==="document"}function Td(e){try{return JSON.stringify(e)??""}catch{return""}}function Vr(e){return typeof e=="string"&&e!==""?e:void 0}function Ad(e){if("encryptedValue"in e){const t=Vr(e.encryptedValue);if(t!==void 0)return t}return Vr(B(e)?.signature)}function zo(e){return e.length===0?null:e.every(t=>t.type==="text")?e.map(t=>t.content).join("")||null:e}function Vo(e){return e==null?"":typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.content).join("")}function Md(e){return Array.isArray(e)?e:Vo(e)}function Od(e){if(!("role"in e)||e.role!=="tool")return e;const t=e,n=B(t)?.toolResult;if(!Ln(n)||"content"in n&&!ps(n.content))return e;const s={...e};if("id"in n||Reflect.deleteProperty(s,"id"),"createdAt"in n||Reflect.deleteProperty(s,"createdAt"),typeof n.id=="string"&&Reflect.set(s,"id",n.id),typeof n.createdAt=="string"){const i=re(n.createdAt);i&&Reflect.set(s,"createdAt",i)}ps(n.content)&&Reflect.set(s,"content",n.content);const r=Reflect.get(t,"metadata");if(Ln(r)){const i=r.tanstack;if(Ln(i)){const{toolResult:o,...a}=i,l={...r};Object.keys(a).length?l.tanstack=a:delete l.tanstack,Object.keys(l).length?Reflect.set(s,"metadata",l):Reflect.deleteProperty(s,"metadata")}}return s}function re(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!="string")return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function qo(e){if(e.type!=="tool-result")return e;const t=re(e.createdAt),{createdAt:n,...s}=e;return t===void 0?s:{...s,createdAt:t}}function Ko(e){return re(B(e)?.createdAt)}function gs(e){const t=re(e.createdAt);return t!==void 0?{createdAt:t}:{}}function mn(e){return e.name!==void 0?{name:e.name}:{}}function vn(e){if(e==null||typeof e!="object"||Array.isArray(e)||!("type"in e)||e.type!=="ui-resource"||!("toolCallId"in e)||typeof e.toolCallId!="string"||!("toolName"in e)||typeof e.toolName!="string"||!("resource"in e)||e.resource==null||typeof e.resource!="object"||Array.isArray(e.resource))return!1;const t=e.resource;return"uri"in t&&typeof t.uri=="string"&&"mimeType"in t&&typeof t.mimeType=="string"}function qr(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function Qo(e,t){if(t.length===0)return e;const n=new Set(e.parts.filter(vn).map(r=>qr(r))),s=t.filter(r=>!n.has(qr(r)));return s.length===0?e:{...e,parts:[...e.parts,...s]}}function xd(e){const t=e.parts.filter(vn),n=e.metadata??{},s=B(e),r={};s?.model!==void 0&&(r.model=s.model),s?.signature!==void 0&&(r.signature=s.signature),t.length>0&&(r.uiResources=t);const i={...n};return Object.keys(r).length>0?i.tanstack=r:delete i.tanstack,Object.keys(i).length>0?i:void 0}function Pd(e){return e.role==="system"?[]:e.role!=="assistant"?[kd(e)]:Ld(e)}function kd(e){const t=[];for(const n of e.parts)_d(n)&&t.push(n);return{id:e.id,role:e.role,content:zo(t),...mn(e),...gs(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function Kr(){return{contentParts:[],toolCalls:[]}}function Fd(e){return e.state==="input-complete"||e.state==="complete"||e.state==="approval-requested"||e.state==="approval-responded"||e.state==="error"||e.output!==void 0}function Ld(e){const t=[];let n=Kr(),s=[];const r=new Set,i={id:e.id,...mn(e),...gs(e)},o=xd(e),a={...i,...o!==void 0&&{metadata:o}};function l(u=!1){const c=zo(n.contentParts),h=c!==null,d=n.toolCalls.length>0,f=s.length>0;(u||h||d||f)&&(t.push({...a,role:"assistant",content:c,...d&&{toolCalls:n.toolCalls},...f&&{thinking:s},...n.structuredOutput&&{structuredOutput:n.structuredOutput}}),s=[]),n=Kr()}for(const u of e.parts)switch(u.type){case"text":case"image":case"audio":case"video":case"document":n.contentParts.push(u);break;case"tool-call":Fd(u)&&n.toolCalls.push({id:u.id,type:"function",function:{name:u.name,arguments:u.arguments},...u.metadata!==void 0&&{metadata:u.metadata}});break;case"tool-result":l(t.length===0),(u.state==="complete"||u.state==="error")&&!r.has(u.toolCallId)&&(t.push({...u.id!==void 0&&{id:u.id},...gs(u),role:"tool",content:u.content,toolCallId:u.toolCallId,...u.name!==void 0&&{name:u.name},...u.metadata!==void 0&&{metadata:u.metadata},...u.error!==void 0&&{error:u.error}}),r.add(u.toolCallId));break;case"thinking":(u.content||u.signature)&&(n.toolCalls.some(Ho)&&l(),s.push({content:u.content,...u.signature&&{signature:u.signature}}));break;case"structured-output":if(u.status==="complete"){const c=u.raw!==""?u.raw:u.data!==void 0?Td(u.data):"";c!==""&&(n.contentParts.push({type:"text",content:c}),n.structuredOutput=u)}}l();for(const u of e.parts)if(u.type==="tool-call"&&(u.output!==void 0&&!r.has(u.id)&&(t.push({role:"tool",content:Hs(u.output),toolCallId:u.id}),r.add(u.id)),u.output===void 0&&u.state==="approval-responded"&&u.approval?.approved!==void 0&&!r.has(u.id))){const c=u.approval.approved;t.push({role:"tool",content:JSON.stringify({approved:c,...c&&{pendingExecution:!0},message:c?"User approved this action":"User denied this action"}),toolCallId:u.id}),r.add(u.id)}return t.length===0&&t.push({...a,role:"assistant",content:null}),t}function un(e,t){const n=[],s=re(e.createdAt);if(e.role==="assistant"&&e.thinking?.length)for(const a of e.thinking)!a.content&&!a.signature||n.push({type:"thinking",content:a.content,...a.signature&&{signature:a.signature}});const r=e.structuredOutput??Wo(B(e)?.structuredOutput);if(e.role==="assistant"&&r){if(typeof e.content=="string"&&e.content&&e.content!==r.raw){const a=r.raw,l=a!==""&&e.content.endsWith(a)?e.content.slice(0,-a.length):e.content;l&&n.push({type:"text",content:l})}n.push(r)}else if(e.role==="tool"&&e.toolCallId)n.push({type:"tool-result",toolCallId:e.toolCallId,content:Md(e.content),state:e.error===void 0?"complete":"error",...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name},...e.metadata!==void 0&&{metadata:e.metadata},...s!==void 0&&{createdAt:s},...e.error!==void 0&&{error:e.error}});else if(Array.isArray(e.content))for(const a of e.content)n.push(a);else{const a=Vo(e.content);a&&n.push({type:"text",content:a})}if(e.toolCalls&&e.toolCalls.length>0)for(const a of e.toolCalls){let l;try{l=JSON.parse(a.function.arguments)}catch{l=void 0}n.push({type:"tool-call",id:a.id,name:a.function.name,arguments:a.function.arguments,state:"input-complete",...l!==void 0&&{input:l},...a.metadata!==void 0&&{metadata:a.metadata}})}const i={id:t||Ne(),role:e.role==="tool"?"assistant":e.role,parts:n,...mn(e),...s!==void 0&&{createdAt:s},...e.metadata!==void 0&&{metadata:e.metadata}},o=B(e)?.uiResources;return Qo(i,Array.isArray(o)?o.filter(vn):[])}function Nd(e){if("parts"in e)return xe(e,{...e,id:e.id||Ne()});const t=e.id||Ne();switch(e.role){case"user":return xe(e,{id:t,role:"user",parts:Dd(e.content)});case"assistant":{const n=B(e),s=n?.toolCallMetadata,r=Wo(n?.structuredOutput),i=e.toolCalls?.map(o=>{const a=s!=null&&typeof s=="object"?s[o.id]:void 0;return a!==void 0?{...o,metadata:a}:o});return xe(e,un({role:"assistant",content:e.content??null,...mn(e),...i&&{toolCalls:i},...r&&{structuredOutput:r}},t))}case"tool":{e=Od(e);const n=re("createdAt"in e?e.createdAt:void 0)??Ko(e);return xe(e,un({role:"tool",content:e.content,toolCallId:e.toolCallId,..."name"in e&&typeof e.name=="string"?{name:e.name}:{},..."id"in e&&typeof e.id=="string"?{id:e.id}:{},..."metadata"in e&&e.metadata!=null?{metadata:e.metadata}:{},...n!==void 0?{createdAt:n}:{},...e.error!==void 0&&{error:e.error}},t))}case"system":case"developer":return xe(e,{id:t,role:"system",parts:e.content?[{type:"text",content:e.content}]:[]});case"reasoning":{const n=Ad(e),s=typeof e.content=="string"?e.content:"";return xe(e,{id:t,role:"assistant",parts:s||n!==void 0?[{type:"thinking",content:s,...n!==void 0?{signature:n}:{}}]:[]})}default:return xe(e,{id:t,role:"assistant",parts:[]})}}function xe(e,t){const n=t.parts.map(u=>qo(u));n!==t.parts&&(t={...t,parts:n});const s="name"in e&&typeof e.name=="string"?e.name:void 0;let r=s!==void 0?{...t,name:s}:t,i;if("metadata"in e){const u=e.metadata;u!=null&&typeof u=="object"&&!Array.isArray(u)&&(i=u,r={...r,metadata:i})}const o=re(r.createdAt)??(i!==void 0?Ko(i):void 0);if(o!==void 0&&!Object.is(o,r.createdAt))r={...r,createdAt:o};else if(o===void 0&&r.createdAt!==void 0){const{createdAt:u,...c}=r;r=c}const a=B(i)?.uiResources,l=Array.isArray(a)?a.filter(vn):[];return Qo(r,l)}function Wo(e){if(!(e==null||e.status!=="streaming"&&e.status!=="complete"&&e.status!=="error"||typeof e.raw!="string"))return{type:"structured-output",status:e.status,raw:e.raw,...e.partial!==void 0?{partial:e.partial}:{},...e.data!==void 0?{data:e.data}:{},...e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0?{errorMessage:e.errorMessage}:{}}}function Dd(e){if(typeof e=="string")return e?[{type:"text",content:e}]:[];const t=[];for(const n of e)n.type==="text"?t.push({type:"text",content:n.text}):n.type!=="binary"&&t.push(n);return t}function jd(e,t){if("parts"in e){const n=e.parts.map(s=>qo(s));return{...e,parts:n,id:e.id||t(),createdAt:re(e.createdAt)??new Date}}else return{...un(e,t()),createdAt:re(e.createdAt)??new Date}}function Ne(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function Qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nn(e,t,n,s,r=!1){const i=Qr(e)?e:{},o=Qr(i.tanstack)?{...i.tanstack}:{};r&&delete o.uiResources;const a=re(t),l={...n!==void 0?{id:n}:{},...a&&{createdAt:a.toISOString()},...Array.isArray(s)&&{content:s}},u={...i,tanstack:{...o,toolResult:l}};return Object.keys(u).length?u:void 0}function Gd(e,t){const n=[],s=new Set(e.flatMap(o=>"id"in o&&o.id&&o.role!=="tool"?[o.id]:[])),r=t?.includeSnapshotStructuredOutput??!1,i=new Set;for(const o of e)o.role==="assistant"&&o.id!==void 0&&i.add(o.id);for(const o of e){if(!("parts"in o)&&o.role==="tool"&&o.toolCallId){const d=jn(Kd(o.id,o.toolCallId,i),s),f=Nn(o.metadata,o.createdAt,o.id,o.content);n.push({role:"tool",id:d,...o.name!==void 0&&{name:o.name},toolCallId:o.toolCallId,content:typeof o.content=="string"?o.content:JSON.stringify(o.content),...o.error!==void 0&&{error:o.error},...f!==void 0&&{metadata:f}});continue}const a="parts"in o?o:un(o,o.id),l=a.parts;if(s.add(a.id),o.role==="system"){n.push(Dn(a,"system",{content:l.length>0?ms(l):o.content??""},l,r));continue}if(o.role==="user"){n.push(Dn(a,"user",{content:l.length>0?Hd(l):o.content??""},l,r));continue}for(const d of l)if(d.type==="thinking"){const f={role:"reasoning",id:Jo(qd(a.id,d),s),content:d.content};d.signature&&(f.encryptedValue=d.signature),n.push(f)}const u=ms(l),c=Vd(l);n.push(Dn(a,"assistant",{...u!==""&&{content:u},...c&&{toolCalls:c}},l,r));const h=new Set(l.flatMap(d=>d.type==="tool-result"?[d.toolCallId]:[]));for(const d of l)if(d.type==="tool-result"){const f=jn(d.id??vs(d.toolCallId),s),p=Nn(d.metadata,d.createdAt,d.id,d.content,!0);n.push({role:"tool",id:f,toolCallId:d.toolCallId,...d.name!==void 0&&{name:d.name},content:typeof d.content=="string"?d.content:JSON.stringify(d.content),...d.error!==void 0&&{error:d.error},...p!==void 0&&{metadata:p}})}else if(d.type==="tool-call"){const f=d.approval?.approved;if(h.has(d.id)||d.output===void 0&&(d.state!=="approval-responded"||f===void 0))continue;const p=d.output!==void 0?Hs(d.output):JSON.stringify({approved:f,...f&&{pendingExecution:!0},message:f?"User approved this action":"User denied this action"}),g=typeof p=="string"?p:JSON.stringify(p);n.push({role:"tool",id:jn(vs(d.id),s),toolCallId:d.id,content:g,metadata:Nn(void 0,void 0,void 0,p)})}}return n}function Dn(e,t,n,s,r){const i=$d(e,s,r),o={id:e.id,...e.name!==void 0&&{name:e.name},...i!==void 0&&{metadata:i}};return t==="system"?{...o,role:t,content:String(n.content??"")}:t==="user"?{...o,role:t,content:n.content??""}:{...o,role:t,...typeof n.content=="string"&&{content:n.content},...n.toolCalls!==void 0&&{toolCalls:n.toolCalls}}}function $d(e,t,n){const s={...e.metadata??{}},r=B(e),i={};r?.model!==void 0&&(i.model=r.model),r?.signature!==void 0&&(i.signature=r.signature);const o=re(e.createdAt);o!==void 0&&(i.createdAt=o.toISOString());const a=Bd(t,n);a&&(i.structuredOutput=a);const l={};for(const c of t)c.type==="tool-call"&&c.metadata!==void 0&&(l[c.id]=c.metadata);Object.keys(l).length>0&&(i.toolCallMetadata=l);const u=t.filter(c=>c.type==="ui-resource");return u.length>0&&(i.uiResources=u),Object.keys(i).length>0?s.tanstack=i:delete s.tanstack,Object.keys(s).length>0?s:void 0}function Bd(e,t){for(const n of e)if(n.type==="structured-output"&&(t||n.status!=="complete"))return Ud(n,t)}function Ud(e,t){return{status:e.status,raw:e.raw,...t&&e.partial!==void 0?{partial:e.partial}:{},...t&&e.data!==void 0?{data:e.data}:{},...t&&e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0&&{errorMessage:e.errorMessage}}}function ms(e){const t=[];for(const n of e)n.type==="text"?t.push(n.content):n.type==="structured-output"&&n.status==="complete"&&n.raw!==""&&t.push(n.raw);return t.join("")}function Hd(e){if(!e.some(n=>n.type==="image"||n.type==="audio"||n.type==="video"||n.type==="document"))return ms(e);const t=[];for(const n of e)n.type==="text"?t.push({type:"text",text:n.content}):(n.type==="image"||n.type==="audio"||n.type==="video"||n.type==="document")&&t.push(n);return t}function zd(e){if(e==null||typeof e!="object"||Array.isArray(e)||!("thoughtSignature"in e))return;const t=e.thoughtSignature;return typeof t=="string"&&t!==""?t:void 0}function Vd(e){const t=[];for(const n of e)if(n.type==="tool-call"){const s=zd(n.metadata);t.push({id:n.id,type:"function",function:{name:n.name,arguments:n.arguments},...s!==void 0?{encryptedValue:s}:{}})}return t.length>0?t:void 0}function qd(e,t){return`${e}-reasoning-${t.id??Qd(t.content)}`}function vs(e){return`tool-${e}`}function jn(e,t){return Jo(e,t)}function Jo(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}-${n}`);)n++;const s=`${e}-${n}`;return t.add(s),s}function Kd(e,t,n){const s=vs(t);return e===void 0||n.has(e)?s:e}function Qd(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function Wd(e){if((e.type===Ut.RUN_FINISHED||e.type===Ut.RUN_ERROR)&&(Array.isArray(e.usage)||Lo(e.usage))){const t=ed(e.usage,B(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===Ut.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===Ut.TOOL_CALL_END&&e.input===void 0){const t=B(e)?.input;t!==void 0&&(e.input=t)}return e}function Xo(e){Wd(e);const t=B(e),n=e;if(t==null)return n;for(const[s,r]of Object.entries(t))s==="usage"||s==="interruptErrors"||n[s]===void 0&&r!==void 0&&(n[s]=r);return t.interruptErrors!==void 0&&(n["tanstack:interruptErrors"]=t.interruptErrors),n}function Wr(e){return typeof e=="string"&&e!==""?e:void 0}function Yo(e){if("runId"in e){const t=Wr(e.runId);if(t!==void 0)return t}return Wr(B(e)?.runId)}var Jr=tt((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),Jd=tt((e=>{var t=e&&e.__createBinding||(Object.create?(function(u,c,h,d){d===void 0&&(d=h);var f=Object.getOwnPropertyDescriptor(c,h);(!f||("get"in f?!c.__esModule:f.writable||f.configurable))&&(f={enumerable:!0,get:function(){return c[h]}}),Object.defineProperty(u,d,f)}):(function(u,c,h,d){d===void 0&&(d=h),u[d]=c[h]})),n=e&&e.__exportStar||function(u,c){for(var h in u)h!=="default"&&!Object.prototype.hasOwnProperty.call(c,h)&&t(c,u,h)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var s=Jr();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return s.Allow}}),n(Jr(),e);var r=class extends Error{};e.PartialJSON=r;var i=class extends Error{};e.MalformedJSON=i;function o(u,c=s.Allow.ALL){if(typeof u!="string")throw new TypeError(`expecting str, got ${typeof u}`);if(!u.trim())throw new Error(`${u} is empty`);return a(u.trim(),c)}e.parseJSON=o;var a=(u,c)=>{const h=u.length;let d=0;const f=w=>{throw new r(`${w} at position ${d}`)},p=w=>{throw new i(`${w} at position ${d}`)},g=()=>(b(),d>=h&&f("Unexpected end of input"),u[d]==='"'?m():u[d]==="{"?v():u[d]==="["?S():u.substring(d,d+4)==="null"||s.Allow.NULL&c&&h-d<4&&"null".startsWith(u.substring(d))?(d+=4,null):u.substring(d,d+4)==="true"||s.Allow.BOOL&c&&h-d<4&&"true".startsWith(u.substring(d))?(d+=4,!0):u.substring(d,d+5)==="false"||s.Allow.BOOL&c&&h-d<5&&"false".startsWith(u.substring(d))?(d+=5,!1):u.substring(d,d+8)==="Infinity"||s.Allow.INFINITY&c&&h-d<8&&"Infinity".startsWith(u.substring(d))?(d+=8,1/0):u.substring(d,d+9)==="-Infinity"||s.Allow._INFINITY&c&&1<h-d&&h-d<9&&"-Infinity".startsWith(u.substring(d))?(d+=9,-1/0):u.substring(d,d+3)==="NaN"||s.Allow.NAN&c&&h-d<3&&"NaN".startsWith(u.substring(d))?(d+=3,NaN):C()),m=()=>{const w=d;let R=!1;for(d++;d<h&&(u[d]!=='"'||R&&u[d-1]==="\\");)R=u[d]==="\\"?!R:!1,d++;if(u.charAt(d)=='"')try{return JSON.parse(u.substring(w,++d-Number(R)))}catch(y){p(String(y))}else if(s.Allow.STR&c)try{return JSON.parse(u.substring(w,d-Number(R))+'"')}catch{return JSON.parse(u.substring(w,u.lastIndexOf("\\"))+'"')}f("Unterminated string literal")},v=()=>{d++,b();const w={};try{for(;u[d]!=="}";){if(b(),d>=h&&s.Allow.OBJ&c)return w;const R=m();b(),d++;try{w[R]=g()}catch(y){if(s.Allow.OBJ&c)return w;throw y}b(),u[d]===","&&d++}}catch{if(s.Allow.OBJ&c)return w;f("Expected '}' at end of object")}return d++,w},S=()=>{d++;const w=[];try{for(;u[d]!=="]";)w.push(g()),b(),u[d]===","&&d++}catch{if(s.Allow.ARR&c)return w;f("Expected ']' at end of array")}return d++,w},C=()=>{if(d===0){u==="-"&&p("Not sure what '-' is");try{return JSON.parse(u)}catch(R){if(s.Allow.NUM&c)try{return JSON.parse(u.substring(0,u.lastIndexOf("e")))}catch{}p(String(R))}}const w=d;for(u[d]==="-"&&d++;u[d]&&",]}".indexOf(u[d])===-1;)d++;d==h&&!(s.Allow.NUM&c)&&f("Unterminated number literal");try{return JSON.parse(u.substring(w,d))}catch{u.substring(w,d)==="-"&&f("Not sure what '-' is");try{return JSON.parse(u.substring(w,u.lastIndexOf("e")))}catch(y){p(String(y))}}},b=()=>{for(;d<h&&`
|
|
9
|
-
\r `.includes(u[d]);)d++};return g()},l=o;e.parse=l})),Xd=Jd(),Yd=class{parse(e){if(!(!e||e.trim()===""))try{return(0,Xd.parse)(e)}catch{return}}},Zo=new Yd;function Zd(e){return Zo.parse(e)}var eh=class{shouldEmit(e,t){return!0}};function th(e){const t=new Error(e.message||e.error?.message||"An error occurred"),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}function nh(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type==="text"?r[r.length-1]={type:"text",content:n}:r.push({type:"text",content:n}),{...s,parts:r}})}function Ht(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.find(u=>u.type==="tool-call"&&u.id===n.id),o=n.metadata??i?.metadata,a=n.input??i?.input,l={type:"tool-call",id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...a!==void 0&&{input:a},...o!==void 0&&{metadata:o}};return i?r[r.indexOf(i)]=l:r.push(l),{...s,parts:r}})}function Xr(e,t,n,s,r,i){return e.map(o=>{if(o.id!==t)return o;const a=[...o.parts],l=a.findIndex(c=>c.type==="tool-result"&&c.toolCallId===n),u={type:"tool-result",toolCallId:n,content:s,state:r,...i&&{error:i}};return l>=0?a[l]=u:a.push(u),{...o,parts:a}})}function Yr(e,t,n,s){return e.map(r=>{if(r.id!==t)return r;const i=[...r.parts],o=i.find(a=>a.type==="tool-call"&&a.id===n);if(o){const a=i.indexOf(o);i[a]={...o,state:"approval-requested",approval:{id:s,needsApproval:!0}}}return{...r,parts:i}})}function Zr(e,t,n,s,r){return e.map(i=>{const o=[...i.parts],a=o.find(l=>l.type==="tool-call"&&l.id===t);if(a){const l=o.indexOf(a);o[l]={...a,output:r?{error:r}:n,state:s??(r?"error":"complete")}}return{...i,parts:o}})}function sh(e,t,n){return e.map(s=>{const r=[...s.parts],i=r.find(o=>o.type==="tool-call"&&o.approval?.id===t);if(i&&i.approval){const o=r.indexOf(i);r[o]={...i,approval:{...i.approval,approved:n},state:"approval-responded"}}return{...s,parts:r}})}function rh(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.findIndex(h=>h.type==="structured-output"),o=i>=0?r[i]:null,a=(o?.raw??"")+n,l=Zd(a),u=l??o?.partial,c={type:"structured-output",status:"streaming",raw:a,...u!==void 0?{partial:u}:{},...o?.reasoning!==void 0?{reasoning:o.reasoning}:{}};return i>=0?r[i]=c:r.push(c),{...s,parts:r}})}function ih(e,t,n,s,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(h=>h.type==="structured-output"),l=a>=0?o[a].raw:"";let u=s||l;if(u===""&&n!==void 0)try{u=JSON.stringify(n)}catch{}const c={type:"structured-output",status:"complete",data:n,partial:n,raw:u,...r!==void 0?{reasoning:r}:{}};return a>=0?o[a]=c:o.push(c),{...i,parts:o}})}function ei(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.findIndex(a=>a.type==="structured-output");if(i<0)return r.push({type:"structured-output",status:"error",raw:"",errorMessage:n}),{...s,parts:r};const o=r[i];return o.status==="complete"?s:(r[i]={...o,status:"error",errorMessage:n},{...s,parts:r})})}function Gn(e,t,n,s,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(u=>u.type==="thinking"&&u.stepId===n),l={type:"thinking",content:s,stepId:n,...r&&{signature:r}};return a>=0?o[a]=l:o.push(l),{...i,parts:o}})}var oh=12;function ah(e){return e.some(t=>{const n=t.metadata;if(!n||typeof n!="object"||Array.isArray(n))return!1;const s=n[gn];return s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.kind==="generic"})}var lh=class ea{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;streamEndEmitted=!1;recording=null;recordingStartTime=0;constructor(t={}){this.chunkStrategy=t.chunkStrategy||new eh,this.events=t.events||{},this.jsonParser=t.jsonParser||Zo,this.recordingEnabled=t.recording??!1,t.initialMessages&&(this.messages=[...t.initialMessages])}setMessages(t){this.messages=[...t],this.emitMessagesChange()}addUserMessage(t,n,s){const r=typeof t=="string"?[{type:"text",content:t}]:t.map(o=>o),i={id:n??Ne(),role:"user",parts:r,createdAt:new Date,...s!=null?{metadata:s}:{}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(t){this.prepareAssistantMessage();const{messageId:n}=this.ensureAssistantMessage(t);return this.pendingManualMessageId=n,n}getCurrentAssistantMessageId(){let t=null;for(const[n,s]of this.messageStates)s.role==="assistant"&&(t=n);return t}addToolResult(t,n,s){const r=this.messages.find(l=>l.parts.some(u=>u.type==="tool-call"&&u.id===t));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${t}`);return}let i=Zr(this.messages,t,n,s?"error":void 0,s);const o=Hs(n),a=s?"error":"complete";i=Xr(i,r.id,t,o,a,s),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(t,n){this.messages=sh(this.messages,t,n),this.emitMessagesChange()}toModelMessages(){const t=[];for(const n of this.messages)t.push(...Pd(n));return t}getMessages(){return this.messages}areAllToolsComplete(){const t=this.messages.findLast(r=>r.role==="assistant");if(!t)return!0;const n=t.parts.filter(r=>r.type==="tool-call");if(n.length===0)return!0;const s=new Set(t.parts.filter(r=>r.type==="tool-result").map(r=>r.toolCallId));return n.every(r=>r.state==="complete"||r.state==="approval-responded"||r.output!==void 0&&!r.approval||s.has(r.id)||Ho(r))}removeMessagesAfter(t){const n=new Set(this.messages.slice(0,t+1).map(s=>s.id));for(const s of this.structuredMessageIds)n.has(s)||this.structuredMessageIds.delete(s);for(const s of this.structuredOutputUpdateBatches.keys())n.has(s)||this.structuredOutputUpdateBatches.delete(s);for(const s of this.messageStates.keys())n.has(s)||this.messageStates.delete(s);for(const[s,r]of this.toolCallToMessage)n.has(r)||this.toolCallToMessage.delete(s);for(const s of this.activeMessageIds)n.has(s)||this.activeMessageIds.delete(s);this.messages=this.messages.slice(0,t+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(t){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(const n of t)this.processChunk(n);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(t){switch(this.recording&&this.recording.chunks.push({chunk:t,timestamp:Date.now(),index:this.recording.chunks.length}),t.type){case"TEXT_MESSAGE_START":this.handleTextMessageStartEvent(t);break;case"TEXT_MESSAGE_CONTENT":this.handleTextMessageContentEvent(t);break;case"TEXT_MESSAGE_END":this.handleTextMessageEndEvent(t);break;case"TOOL_CALL_START":this.handleToolCallStartEvent(t);break;case"TOOL_CALL_ARGS":this.handleToolCallArgsEvent(t);break;case"TOOL_CALL_END":this.handleToolCallEndEvent(t);break;case"RUN_FINISHED":this.handleRunFinishedEvent(t);break;case"RUN_ERROR":this.handleRunErrorEvent(t);break;case"STEP_FINISHED":this.handleStepFinishedEvent(t);break;case"MESSAGES_SNAPSHOT":this.handleMessagesSnapshotEvent(t);break;case"CUSTOM":this.handleCustomEvent(t);break;case"RUN_STARTED":this.handleRunStartedEvent(t);break;case"REASONING_START":case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"REASONING_MESSAGE_CONTENT":this.handleReasoningMessageContentEvent(t);break;case"REASONING_ENCRYPTED_VALUE":this.handleReasoningEncryptedValueEvent(t);break;case"TOOL_CALL_RESULT":this.handleToolCallResultEvent(t);break;case"STEP_STARTED":this.handleStepStartedEvent(t)}}createMessageState(t,n){const s={id:t,role:n,totalTextContent:"",currentSegmentText:"",lastEmittedText:"",hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(t,s),s}getMessageState(t){return this.messageStates.get(t)}consumePendingThinkingStep(t){if(!this.pendingThinkingStepId)return;const n=this.pendingThinkingStepId;t.currentThinkingStepId=n,t.thinkingSteps.has(n)||(t.thinkingSteps.set(n,""),t.thinkingStepOrder.push(n)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){const t=Array.from(this.activeMessageIds).reverse();for(const n of t){const s=this.messageStates.get(n);if(s&&s.role==="assistant")return n}for(const[n,s]of[...this.messageStates].reverse())if(s.role==="assistant")return n;return null}resumeAssistantState(t,n){this.activeMessageIds.add(t),(n.isComplete||this.isDone)&&(n.isComplete=!1,this.isDone=!1)}ensureAssistantMessage(t){if(t){const o=this.getMessageState(t);if(o)return this.resumeAssistantState(t,o),{messageId:t,state:o}}const n=this.getActiveAssistantMessageId();if(n){const o=this.getMessageState(n);if(o)return this.resumeAssistantState(n,o),{messageId:n,state:o}}if(t){const o=this.messages.find(a=>a.id===t);if(o){const a=this.createMessageState(t,o.role);this.activeMessageIds.add(t);const l=o.parts.length>0?o.parts[o.parts.length-1]:null;return l&&l.type==="text"&&(a.currentSegmentText=l.content,a.lastEmittedText=l.content,a.totalTextContent=l.content),{messageId:t,state:a}}}const s=t||Ne(),r={id:s,role:"assistant",parts:[],createdAt:new Date};this.messages=[...this.messages,r];const i=this.createMessageState(s,"assistant");return this.activeMessageIds.add(s),this.pendingManualMessageId=s,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:s,state:i}}mergeMessageMetadata(t,n){if(n==null||typeof n!="object"||Array.isArray(n))return;const s=this.messages.find(c=>c.id===t);if(!s)return;const r=n,i=B(r),o=i!=null&&("content"in i||"args"in i)?{...r,tanstack:Object.fromEntries(Object.entries(i).filter(([c])=>c!=="content"&&c!=="args"))}:r,a=No(s.metadata,o),l=re(B(r)?.createdAt),u=l!==void 0;this.messages=this.messages.map(c=>c.id===t?{...c,...a!==void 0?{metadata:a}:{},...u?{createdAt:l}:{}}:c),this.emitMessagesChange()}handleTextMessageStartEvent(t){const{messageId:n,role:s}=t,r=s==="user"||s==="system"?s:"assistant";if(this.pendingManualMessageId){const o=this.pendingManualMessageId;if(this.pendingManualMessageId=null,o!==n){this.messages=this.messages.map(u=>u.id===o?{...u,id:n}:u);const l=this.messageStates.get(o);l&&(l.id=n,this.messageStates.delete(o),this.messageStates.set(n,l)),this.activeMessageIds.delete(o),this.activeMessageIds.add(n);for(const[u,c]of this.toolCallToMessage)c===o&&this.toolCallToMessage.set(u,n)}let a=this.messageStates.get(n);a?a.hasToolCallsSinceTextStart&&(a.currentSegmentText!==a.lastEmittedText&&this.emitTextUpdateForMessage(n),a.currentSegmentText="",a.lastEmittedText="",a.hasToolCallsSinceTextStart=!1):(a=this.createMessageState(n,r),this.activeMessageIds.add(n)),this.mergeMessageMetadata(n,t.metadata),this.emitMessagesChange();return}if(this.messages.find(o=>o.id===n)){this.activeMessageIds.add(n);const o=this.messageStates.get(n);o?o.hasToolCallsSinceTextStart&&(o.currentSegmentText!==o.lastEmittedText&&this.emitTextUpdateForMessage(n),o.currentSegmentText="",o.lastEmittedText="",o.hasToolCallsSinceTextStart=!1):this.createMessageState(n,r),this.mergeMessageMetadata(n,t.metadata);return}const i={id:n,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(n,r),this.activeMessageIds.add(n),this.mergeMessageMetadata(n,t.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(t){const{messageId:n}=t;this.mergeMessageMetadata(n,t.metadata);const s=this.getMessageState(n);s&&(s.isComplete||s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(n))}handleMessagesSnapshotEvent(t){this.resetStreamState();const n=this.messages,s=new Map(n.map(i=>[i.id,i])),r=this.mergeReasoningFanOut(t.messages.map(Nd));this.messages=this.reconcileSnapshotToolCalls(r,n).map(i=>{if(i.metadata!=null)return i;const o=s.get(i.id);return o?.metadata==null?i:{...i,metadata:o.metadata}}),this.emitMessagesChange()}mergeReasoningFanOut(t){const n=[];let s=[];const r=l=>l.parts.filter(u=>u.type==="thinking"),i=l=>l.role==="assistant"&&l.parts.length>0&&l.parts.every(u=>u.type==="thinking"),o=l=>l.role==="assistant"&&l.parts.some(u=>u.type==="tool-result")&&l.parts.every(u=>u.type==="tool-result"||u.type==="ui-resource"),a=()=>{n.push(...s),s=[]};for(const l of t){if(i(l)){s.push(l);continue}if(l.role==="assistant"&&s.length>0&&!o(l)){n.push({...l,parts:[...s.flatMap(r),...l.parts]}),s=[];continue}a(),n.push(l)}return a(),n}reconcileSnapshotToolCalls(t,n){const s=new Map;for(const o of n)for(const a of o.parts)a.type==="tool-call"&&s.set(a.id,a);const r=new Set;for(const o of t)for(const a of o.parts)a.type==="tool-call"&&r.add(a.id);const i=[];for(const o of t){const a=o.parts.filter(h=>h.type==="tool-result"),l=o.role==="assistant"&&a.length===1&&o.parts.every(h=>h.type==="tool-result"||h.type==="ui-resource")?a[0]:void 0;if(!l){i.push(o);continue}const u=i.findLast(h=>h.parts.some(d=>d.type==="tool-call"&&d.id===l.toolCallId))??i.findLast(h=>h.role==="assistant"&&!(h.parts.length===1&&h.parts[0]?.type==="tool-result"));if(!u){r.has(l.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${l.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${l.toolCallId}") will not be able to locate this call`),i.push(o);continue}const c=[...u.parts];if(!r.has(l.toolCallId)&&!c.some(h=>h.type==="tool-call"&&h.id===l.toolCallId)){const h=s.get(l.toolCallId);h?(c.push({...h}),r.add(h.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${l.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${l.toolCallId}") will not be able to locate this call`)}c.push(...o.parts),u.parts=c}return this.enrichSnapshotToolCallsFromResults(i,s)}enrichSnapshotToolCallsFromResults(t,n){const s=new Map;for(const r of t)for(const i of r.parts)i.type==="tool-result"&&s.set(i.toolCallId,i);return t.map(r=>{const i=r.parts.map(o=>{if(o.type!=="tool-call")return o;const a=n.get(o.id),l=s.get(o.id);let u=o;if(a&&(a.output!==void 0||a.state==="complete"||a.state==="error")&&(o.output===void 0||o.state==="input-complete"||o.state==="input-streaming"||o.state==="awaiting-input")&&(u={...o,...a.output!==void 0?{output:a.output}:{},state:a.state,...a.approval!==void 0?{approval:a.approval}:{},...a.metadata!==void 0?{metadata:a.metadata}:{}}),l&&u.output===void 0){let c;if(Array.isArray(l.content))c=l.content;else try{c=JSON.parse(l.content)}catch{c=l.content}const h=l.state==="error"?this.extractToolResultError(c):void 0;u={...u,output:h?{error:h}:c,state:l.state==="error"?"error":"complete"}}return u});return i.some((o,a)=>o!==r.parts[a])?{...r,parts:i}:r})}handleTextMessageContentEvent(t){const{messageId:n,state:s}=this.ensureAssistantMessage(t.messageId);if(this.mergeMessageMetadata(n,t.metadata),this.structuredMessageIds.has(n)){const c=t.delta||"";c!==""&&(this.messages=rh(this.messages,n,c),s.totalTextContent+=c,this.queueStructuredOutputUpdate(n,c),this.emitMessagesChange());return}const r=s.currentSegmentText;s.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(t,r)&&(r!==s.lastEmittedText&&this.emitTextUpdateForMessage(n),s.currentSegmentText="",s.lastEmittedText="",s.hasToolCallsSinceTextStart=!1),s.hasToolCallsSinceTextStart=!1;const i=s.currentSegmentText,o=t.delta||"",a=o!==""?i+o:i,l=a.slice(i.length);s.currentSegmentText=a,s.totalTextContent+=l;const u=t.delta||"";this.chunkStrategy.shouldEmit(u,s.currentSegmentText)&&s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(n)}handleToolCallStartEvent(t){const n=t.parentMessageId??this.getActiveAssistantMessageId(),{messageId:s,state:r}=this.ensureAssistantMessage(n??void 0);r.hasToolCallsSinceTextStart=!0;const i=t.toolCallId;if(!r.toolCalls.get(i)){const o="awaiting-input",a=t.toolCallName,l=t.metadata,u={id:t.toolCallId,name:a,arguments:"",state:o,parsedArguments:void 0,index:r.toolCalls.size,...l!==void 0&&{metadata:l}};r.toolCalls.set(i,u),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,s),this.messages=Ht(this.messages,s,{id:t.toolCallId,name:a,arguments:"",state:o,...l!==void 0&&{metadata:l}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(s,t.toolCallId,o,"")}}handleToolCallArgsEvent(t){const n=t.toolCallId,s=this.toolCallToMessage.get(n);if(!s)return;const r=this.getMessageState(s);if(!r)return;const i=r.toolCalls.get(n);if(!i)return;const o=i.state==="awaiting-input";i.arguments+=t.delta||"",o&&t.delta&&(i.state="input-streaming"),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=Ht(this.messages,s,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(s,i.id,i.state,i.arguments)}handleToolCallEndEvent(t){const n=this.toolCallToMessage.get(t.toolCallId);if(!n)return;const s=this.getMessageState(n);if(!s)return;const r=t.input!==void 0?t.input:B(t)?.input,i=s.toolCalls.get(t.toolCallId);if(i&&i.state!=="input-complete"){if(r!==void 0&&!i.arguments)try{i.arguments=JSON.stringify(r)}catch{}const o=s.toolCallOrder.indexOf(t.toolCallId);this.completeToolCall(n,o,i),r!==void 0&&(i.parsedArguments=r,this.messages=Ht(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:"input-complete",input:r,...i.metadata!==void 0&&{metadata:i.metadata}}),this.emitMessagesChange())}}extractToolResultError(t){return t&&typeof t=="object"&&"error"in t&&typeof t.error=="string"?t.error:typeof t=="string"?t:"Tool execution failed"}handleToolCallResultEvent(t){const n=this.toolCallToMessage.get(t.toolCallId)??this.messages.find(o=>o.parts.some(a=>a.type==="tool-call"&&a.id===t.toolCallId))?.id;if(!n)return;const s=t.state==="output-error"||B(t)?.state==="output-error";let r;try{r=JSON.parse(t.content)}catch{r=t.content}this.messages=Zr(this.messages,t.toolCallId,r,s?"error":void 0);const i=s?"error":"complete";this.messages=Xr(this.messages,n,t.toolCallId,t.content,i,i==="error"?this.extractToolResultError(r):void 0),this.emitMessagesChange()}handleRunStartedEvent(t){this.activeRuns.add(t.runId)}handleRunFinishedEvent(t){const n=t;if(this.finishReason=n.finishReason!==void 0?n.finishReason:B(t)?.finishReason??null,this.activeRuns.delete(t.runId),t.outcome?.type==="interrupt"&&this.handleInterrupts(t.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason==="tool_calls"&&t.outcome?.type!=="interrupt")return;this.isDone=!0,this.finalizeStream()}}handleInterrupts(t){const n=ah(t);for(const s of t){const r=s.metadata&&typeof s.metadata=="object"?s.metadata:{},i=typeof r.kind=="string"?r.kind:void 0,o=s.toolCallId;if(!o)continue;const a=typeof r.toolName=="string"?r.toolName:this.findToolCallName(o),l=Object.hasOwn(r,"input")?r.input:{};if(i==="approval"||s.reason==="approval_required"){const u=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(o)??this.messages.find(c=>c.role==="assistant"&&c.parts.some(h=>h.type==="tool-call"&&h.id===o))?.id;u&&(this.messages=Yr(this.messages,u,o,s.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:o,toolName:a,input:l,approvalId:s.id});continue}if(i==="client_tool"||s.reason==="client_tool_input"){if(n)continue;this.events.onToolCall?.({toolCallId:o,toolName:a,input:l})}}}findToolCallName(t){for(const n of this.messageStates.values()){const s=n.toolCalls.get(t);if(s)return s.name}return""}handleRunErrorEvent(t){this.hasError=!0;const n=Yo(t);n?this.activeRuns.delete(n):this.activeRuns.clear();const{messageId:s}=this.ensureAssistantMessage(),r=t.message||"An error occurred";t.message||console.error("[StreamProcessor] RUN_ERROR with no message; original chunk:",t),this.structuredMessageIds.has(s)&&(this.flushStructuredOutputUpdate(s),this.messages=ei(this.messages,s,r),this.structuredMessageIds.delete(s),this.emitStructuredOutputChange(s,"error"),this.emitMessagesChange()),this.events.onError?.(th(t))}handleStepStartedEvent(t){const n=t.stepName||Ne(),s=this.getActiveAssistantMessageId();if(s){const r=this.getMessageState(s);if(r){r.currentThinkingStepId=n,r.thinkingSteps.has(n)||(r.thinkingSteps.set(n,""),r.thinkingStepOrder.push(n)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=n}handleStepFinishedEvent(t){const n=t,s=n.signature;if(!s)return;const{messageId:r,state:i}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),o=i.currentThinkingStepId??n.stepId;if(!o)return;const a=i.thinkingSteps.get(o);a!==void 0&&(i.thinkingStepSignatures.set(o,s),this.messages=Gn(this.messages,r,o,a,s),this.emitMessagesChange())}handleReasoningMessageContentEvent(t){const{messageId:n,state:s}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);s.hasSeenReasoningEvents=!0;const r=t.delta||"";this.consumePendingThinkingStep(s);const i=s.currentThinkingStepId??t.messageId;s.thinkingSteps.has(i)||(s.thinkingSteps.set(i,""),s.thinkingStepOrder.push(i),s.currentThinkingStepId=i);const o=(s.thinkingSteps.get(i)??"")+r;s.thinkingSteps.set(i,o),this.messages=Gn(this.messages,n,i,o,s.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(n,i,o)}handleReasoningEncryptedValueEvent(t){const n=t.encryptedValue;if(typeof n!="string"||n==="")return;if(t.subtype==="tool-call"){this.attachToolCallSignature(t.entityId,n);return}const{messageId:s,state:r}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),i=r.currentThinkingStepId??t.entityId;r.thinkingStepSignatures.set(i,n);const o=r.thinkingSteps.get(i)??"";r.thinkingSteps.has(i)||(r.thinkingSteps.set(i,o),r.thinkingStepOrder.push(i)),this.messages=Gn(this.messages,s,i,o,n),this.emitMessagesChange()}attachToolCallSignature(t,n){this.messages=this.messages.map(s=>{let r=!1;const i=s.parts.map(o=>o.type!=="tool-call"||o.id!==t?o:(r=!0,{...o,metadata:{...o.metadata!=null&&typeof o.metadata=="object"?o.metadata:{},thoughtSignature:n}}));return r?{...s,parts:i}:s});for(const s of this.messageStates.values()){const r=s.toolCalls.get(t);r&&(r.metadata={...r.metadata??{},thoughtSignature:n})}this.emitMessagesChange()}handleCustomEvent(t){const n=this.getActiveAssistantMessageId();if(t.name==="structured-output.start"&&t.value){const s=t.value,{messageId:r}=this.ensureAssistantMessage(s.messageId??n??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:"start",messageId:r,status:"streaming",raw:""}));return}if(t.name==="structured-output.complete"&&t.value){const s=t.value,{messageId:r}=this.ensureAssistantMessage(s.messageId??n??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=ih(this.messages,r,s.object,s.raw??"",s.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,"complete"),this.emitMessagesChange())}if(t.name==="tool-input-available"&&t.value){const{toolCallId:s,toolName:r,input:i}=t.value;this.events.onToolCall?.({toolCallId:s,toolName:r,input:i});return}if(t.name==="approval-requested"&&t.value){const{toolCallId:s,toolName:r,input:i,approval:o}=t.value,a=n??this.toolCallToMessage.get(s);a&&(this.messages=Yr(this.messages,a,s,o.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:s,toolName:r,input:i,approvalId:o.id});return}if(t.name==="ui-resource"&&t.value){const s=t.value,r=this.toolCallToMessage.get(s.toolCallId)??n;if(r){const i={type:"ui-resource",resource:s.resource,toolCallId:s.toolCallId,toolName:s.toolName,...s.serverId!==void 0&&{serverId:s.serverId},...s.meta!==void 0&&{meta:s.meta}};this.messages=this.messages.map(o=>o.id===r?{...o,parts:[...o.parts,i]}:o),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${s.toolCallId}" (toolName "${s.toolName}")`);return}if(this.events.onCustomEvent){const s=t.value&&typeof t.value=="object"?t.value.toolCallId:void 0;this.events.onCustomEvent(t.name,t.value,{toolCallId:s})}}isNewTextSegment(t,n){return!0}completeAllToolCalls(){for(const t of this.activeMessageIds)this.completeAllToolCallsForMessage(t)}completeAllToolCallsForMessage(t){const n=this.getMessageState(t);n&&n.toolCalls.forEach((s,r)=>{if(s.state!=="input-complete"){const i=n.toolCallOrder.indexOf(r);this.completeToolCall(t,i,s)}})}completeToolCall(t,n,s){s.state="input-complete";let r=!1;try{s.parsedArguments=JSON.parse(s.arguments),r=!0}catch{s.parsedArguments=void 0}this.isToolCallPartErrored(s.id)||this.isToolCallPartAwaitingUserAction(s.id)||(this.messages=Ht(this.messages,t,{id:s.id,name:s.name,arguments:s.arguments,state:"input-complete",...r&&{input:s.parsedArguments},...s.metadata!==void 0&&{metadata:s.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(t,s.id,"input-complete",s.arguments))}isToolCallPartAwaitingUserAction(t){return this.messages.some(n=>n.parts?.some(s=>s.type==="tool-call"&&s.id===t&&(s.state==="approval-requested"||s.state==="approval-responded")))}isToolCallPartErrored(t){return this.messages.some(n=>n.parts?.some(s=>s.type==="tool-call"&&s.id===t&&s.state==="error"))}emitTextUpdateForMessage(t){const n=this.getMessageState(t);n&&(n.lastEmittedText=n.currentSegmentText,this.messages=nh(this.messages,t,n.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(t,n.currentSegmentText))}queueStructuredOutputUpdate(t,n){const s=this.structuredOutputUpdateBatches.get(t),r={delta:`${s?.delta??""}${n}`,chunkCount:(s?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(t,r),r.chunkCount>=oh&&this.flushStructuredOutputUpdate(t)}flushStructuredOutputUpdate(t){const n=this.structuredOutputUpdateBatches.get(t);!n||n.chunkCount===0||(this.structuredOutputUpdateBatches.delete(t),this.emitStructuredOutputChange(t,"update",n.delta))}emitStructuredOutputChange(t,n,s){const r=this.messages.find(i=>i.id===t)?.parts.find(i=>i.type==="structured-output");r&&this.events.onStructuredOutputChange?.({phase:n,messageId:t,status:r.status,raw:r.raw,...r.partial!==void 0?{partial:r.partial}:{},...r.data!==void 0?{data:r.data}:{},...r.reasoning!==void 0?{reasoning:r.reasoning}:{},...r.errorMessage!==void 0?{errorMessage:r.errorMessage}:{},...s!==void 0?{delta:s}:{}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;let t;for(const n of this.activeMessageIds){const s=this.getMessageState(n);if(!s)continue;this.completeAllToolCallsForMessage(n),s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(n),s.isComplete=!0;const r=this.messages.find(i=>i.id===n);r&&r.role==="assistant"&&(t=r)}for(const n of this.structuredMessageIds)this.flushStructuredOutputUpdate(n),this.messages=ei(this.messages,n,"Stream ended without structured-output.complete"),this.emitStructuredOutputChange(n,"error");if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),t&&!this.hasError&&this.isWhitespaceOnlyMessage(t)){this.messages=this.messages.filter(n=>n.id!==t.id),this.emitMessagesChange();return}t&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(t))}getCompletedToolCalls(){const t=[];for(const n of this.messageStates.values())for(const s of n.toolCalls.values())s.state==="input-complete"&&t.push({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments},...s.metadata!==void 0&&{metadata:s.metadata}});return t}getResult(){const t=this.getCompletedToolCalls();let n="",s="";for(const r of this.messageStates.values()){n+=r.totalTextContent;for(const i of r.thinkingStepOrder)s+=r.thinkingSteps.get(i)??""}return{content:n,thinking:s||void 0,toolCalls:t.length>0?t:void 0,finishReason:this.finishReason}}getState(){let t="",n="";const s=new Map,r=[];for(const i of this.messageStates.values()){t+=i.totalTextContent;for(const o of i.thinkingStepOrder)n+=i.thinkingSteps.get(o)??"";for(const[o,a]of i.toolCalls)s.set(o,a);r.push(...i.toolCallOrder)}return{content:t,thinking:n,toolCalls:s,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:"1.0",timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.streamEndEmitted=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(t){return t.parts.length===0?!1:t.parts.every(n=>n.type==="text"&&n.content.trim()==="")}static async replay(t,n){return new ea(n).process(uh(t))}};function uh(e){return{async*[Symbol.asyncIterator](){for(const{chunk:t}of e.chunks)yield t}}}var Ss=(function(e){return e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e})({}),ta=new WeakMap;function se(e){return ta.get(e)??Yo(e)}var na=class extends Error{constructor(){super("Stream ended with unterminated trailing data — connection was likely cut short."),this.name="StreamTruncatedError"}},zs=class extends Error{constructor(e){super("Stream response body read failed",{cause:e}),this.name="StreamReadError"}},ch=class extends Error{constructor(){super("Durable run ended without a terminal event and could not resume — the run did not complete."),this.name="DurableStreamIncompleteError"}},dh=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name="StreamReconnectLimitError"}};function hh(e){const t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw new Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function fh(e){const t=hh(e),n=new Set;let s,r=0;return{get lastEventId(){return s},note(i){return i===void 0?"new":i===""?(s=void 0,n.clear(),"reset"):n.has(i)?"duplicate":(n.add(i),s=i,"new")},async waitBeforeReconnect(i,o){if(i)r=0;else if(r+=1,r>t.maxAttempts)throw new dh(t.maxAttempts);await ph(t.delayMs,o)}}}function ph(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{const s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}function ti(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function zt(e,t){if(!e)throw new Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function ct(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((n,s)=>{t[s]=n}),t}return e}var gh="X-Run-Id";function mh(e){return e===void 0?{}:{[gh]:e}}function Vs(e,t){const n=e.indexOf("#"),s=n===-1?"":e.slice(n),r=n===-1?e:e.slice(0,n),i=r.indexOf("?"),o=i===-1?r:r.slice(0,i),a=new URLSearchParams(i===-1?"":r.slice(i+1));for(const[u,c]of Object.entries(t))a.set(u,c);const l=a.toString();return`${o}${l.length===0?"":`?${l}`}${s}`}async function*vh(e,t){try{const n=Xc();let s="";for(;!t?.aborted;){let r;try{r=await e.read()}catch(l){if(t?.aborted)return;throw new zs(l)}const{done:i,value:o}=r;if(i)break;s+=n.decode(o,{stream:!0});const a=s.split(`
|
|
10
|
-
`);s=a.pop()||"";for(const l of a){const u=l.endsWith("\r")?l.slice(0,-1):l;u.trim()&&(yield u)}}if(s+=n.decode(),s.trim()&&!t?.aborted)throw new na}finally{e.releaseLock()}}function Sh(e){return Xo(e)}function yh(e){const t=B(e)?.model;if(typeof t=="string")return t;const n="usage"in e?e.usage:void 0;if(Array.isArray(n)){const s=n[0]?.model;if(typeof s=="string")return s}}async function*Ih(e,t){let n,s,r,i;for await(const o of e){if(o==="id"||o.startsWith("id:")){const h=o==="id"?"":o.slice(3);i=h.startsWith(" ")?h.slice(1):h;continue}if(o.startsWith(":")||o.startsWith("event:")||o.startsWith("retry:"))continue;const a=Yc(o);if(a==="[DONE]"){yield{chunk:Do({type:Ss.RUN_FINISHED,threadId:n??t?.threadId??"",runId:s??t?.runId??"",timestamp:Date.now()},{finishReason:"stop",...r!==void 0?{model:r}:{}})};return}const l=Sh(JSON.parse(a));"threadId"in l&&typeof l.threadId=="string"&&(n=l.threadId),"runId"in l&&typeof l.runId=="string"&&(s=l.runId);const u=yh(l);u!==void 0&&(r=u);const c=i;i=void 0,yield{chunk:l,...c!==void 0?{id:c}:{}}}}async function qs(e){if(!e.ok){if(e.status===401){const t=await e.clone().json().catch(()=>null);if(Vc(t))throw new cs(t.error.provider)}throw new Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}async function Rh(e,t,n,s,r){const i=await e(Vs(t,{threadId:r}),{method:"GET",headers:{Accept:"application/json",...n},credentials:s});await qs(i);const o=await i.json(),a=o.activeRun&&typeof o.activeRun.runId=="string"?{runId:o.activeRun.runId}:null,l=o.interrupts&&typeof o.interrupts.runId=="string"&&Array.isArray(o.interrupts.pending)&&o.interrupts.pending.length>0?{runId:o.interrupts.runId,pending:o.interrupts.pending}:null;return{messages:Array.isArray(o.messages)?Fo(o.messages):[],activeRun:a,interrupts:l}}async function Ch(e,t,n,s,r){const i=await e(Vs(t,{threadId:r}),{method:"GET",headers:{Accept:"application/json",...n},credentials:s});await qs(i);const o=await i.json();if(o===null)return{resumeSnapshot:null,activeRun:null};if(typeof o!="object"||Array.isArray(o))throw new Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(o)?"an array":typeof o}.`);const a=o,l=a.activeRun&&typeof a.activeRun.runId=="string"?{runId:a.activeRun.runId}:null;return{resumeSnapshot:a.resumeSnapshot??null,activeRun:l}}async function*ys(e,t,n){await qs(e),yield*Ih(vh(Jc(e),t),n)}async function*bh(e,t){for await(const{chunk:n}of ys(e,t))yield n}function ni(e,t,n,s){return async function*(r,i){let o;try{o=await e(t,{...n,headers:{...n.headers,...r},...i?{signal:i}:{}})}catch(a){throw new zs(a)}yield*s(o,i)}}async function*si(e,t,n){const s=fh(n);for(;;){if(t?.aborted)return;const r=s.lastEventId!==void 0?{"Last-Event-ID":s.lastEventId}:{};let i=!1,o=!1;try{for await(const{chunk:a,id:l}of e(r,t))s.note(l)!=="duplicate"&&(o=!0,(a.type==="RUN_FINISHED"||a.type==="RUN_ERROR")&&(i=!0),yield a)}catch(a){if(t?.aborted)return;if((a instanceof na||a instanceof zs)&&s.lastEventId!==void 0){await s.waitBeforeReconnect(o,t);continue}throw a}if(t?.aborted||i)return;if(s.lastEventId!==void 0){if(o){await s.waitBeforeReconnect(!0,t);continue}throw new ch}return}}function ri(e){if(!e)throw new Error("Connection adapter is required");const t="connect"in e,n="subscribe"in e,s="send"in e;if(t&&(n||s))throw new Error("Connection adapter must provide either connect or both subscribe and send, not both modes");if(n&&s){const l=e.joinRun?.bind(e),u=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...l?{joinRun:l}:{},...u?{hydrate:u}:{}}}if(!t)throw new Error("Connection adapter must provide either connect or both subscribe and send");let r=[],i=[];function o(l,u){u&&ta.set(l,u);const c=i.shift();c?c(l):r.push(l)}async function a(l){const u=()=>r.length===0&&(i.length>0||l?.aborted);for(let h=0;h<16&&!l?.aborted;h++){if(u())return;await Promise.resolve()}let c=0;for(;!l?.aborted;)if(u()||(await new Promise(h=>setTimeout(h,0)),c++,i.length===0&&c>=32))return}return{subscribe(l){const u=r.splice(0),c=[];return r=u,i=c,(async function*(){for(;!l?.aborted;){let h;const d=u.shift();d!==void 0?h=d:h=await new Promise(f=>{const p=()=>f(null);c.push(g=>{l?.removeEventListener("abort",p),f(g)}),l?.addEventListener("abort",p,{once:!0})}),h!==null&&(yield h)}})()},async send(l,u,c,h){let d=!1,f,p;try{const g=e.connect(l,u,c,h);for await(const m of g)"threadId"in m&&typeof m.threadId=="string"&&(f=m.threadId),"runId"in m&&typeof m.runId=="string"&&(p=m.runId),(m.type==="RUN_FINISHED"||m.type==="RUN_ERROR")&&(d=!0),o(m,h?.runId);!c?.aborted&&!d&&o(Do({type:Ss.RUN_FINISHED,threadId:zt(f??h?.threadId,"threadId"),runId:zt(p??h?.runId,"runId"),timestamp:Date.now()},{finishReason:"stop",model:"connect-wrapper"}),h?.runId)}catch(g){if(!c?.aborted&&!d)try{const m=g instanceof Error?g.message:"Unknown error in connect()";o({type:Ss.RUN_ERROR,threadId:zt(f??h?.threadId,"threadId"),runId:zt(p??h?.runId,"runId"),timestamp:Date.now(),message:m},h?.runId)}catch{}throw g}await a(c)},...typeof e.joinRun=="function"?{joinRun:(l,u)=>e.joinRun(l,u)}:{},...(()=>{const l=e.hydrate;return typeof l=="function"?{hydrate:u=>l(u)}:{}})()}}function wh(e,t,n,s){const r=Gd(e),i={...s.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??ti("thread"),runId:n?.runId??ti("run"),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:r,tools:n?.clientTools??[],context:[],forwardedProps:i,data:{...i}}}function Qf(e,t={}){return{async*connect(n,s,r,i){const o=typeof e=="function"?e():e,a=typeof t=="function"?await t():t,l={"Content-Type":"application/json",...ct(a.headers),...ct(i?.headers),...mh(i?.runId)},u=wh(n,s,i,a),c=a.fetchClient??fetch,h=r||a.signal;yield*si(ni(c,o,{method:"POST",headers:l,body:JSON.stringify(u),credentials:a.credentials||"same-origin"},(d,f)=>ys(d,f,{...i?.threadId!==void 0?{threadId:i.threadId}:{},...i?.runId!==void 0?{runId:i.runId}:{}})),h,a.reconnect)},async*joinRun(n,s){const r=typeof e=="function"?e():e,i=typeof t=="function"?await t():t,o=Vs(r,{offset:"-1",runId:n}),a={...ct(i.headers)},l=i.fetchClient??fetch,u=s||i.signal;yield*si(ni(l,o,{method:"GET",headers:a,credentials:i.credentials||"same-origin"},(c,h)=>ys(c,h,{runId:n})),u,i.reconnect)},async hydrate(n){const s=typeof e=="function"?e():e,r=typeof t=="function"?await t():t;return Rh(r.fetchClient??fetch,s,ct(r.headers),r.credentials||"same-origin",n)},async hydrateGeneration(n){const s=typeof e=="function"?e():e,r=typeof t=="function"?await t():t;return Ch(r.fetchClient??fetch,s,ct(r.headers),r.credentials||"same-origin",n)}}}function Eh(e){return{async*connect(t,n,s,r){if(!s)throw new Error("fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.");if(!r)throw new Error("fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.");const i=await e({messages:t,data:n,threadId:r.threadId,runId:r.runId,...r.parentRunId!==void 0?{parentRunId:r.parentRunId}:{},...r.resume!==void 0?{resume:r.resume}:{}},{signal:s,headers:r.headers});i instanceof Response?yield*bh(i,s):yield*_h(i,s)}}}async function*_h(e,t){if(t.aborted)return;const n=e[Symbol.asyncIterator](),s=new Promise(r=>{t.addEventListener("abort",()=>r({done:!0,value:void 0}),{once:!0})});try{for(;;){const r=await Promise.race([n.next(),s]);if(r.done)return;yield r.value}}finally{await n.return?.()}}function pe(e){return e.resumable}function $n(e,t){const n=Cd(e.descriptor);return n?{...t,metadata:Rd(n)}:t}function Th(e){return"cancel"in e&&"clearResolution"in e}var Ah=new Set(["invalid-payload","invalid-edited-args","invalid-tool-output","invalid-response-schema","unknown-interrupt","expired","stale","conflict","legacy-unsupported"]),Mh=new Set(["incomplete-batch","item-validation-failed","unsupported-bulk-operation","async-resolver","inactive-transaction","mixed-provenance","transport","server","protocol","invalid-response-schema","expired","stale","conflict","legacy-submit-failed"]);function ae(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sa(e){return ae(e)&&e.kind==="approval"&&typeof e.toolName=="string"&&"input"in e}function ra(e){return ae(e)&&e.kind==="client_tool"&&typeof e.toolName=="string"&&"input"in e}function Oh(e){return sa(e.metadata)||ra(e.metadata)}function ii(e){return gd(e)}function xh(e){if(!ae(e.metadata))return!1;const t=e.metadata[gn];return!ae(t)||t.v!==void 0&&t.v!==1?!1:t.kind==="generic"||t.kind==="tool-approval"||t.kind==="client-tool-execution"||"definitionId"in t||"key"in t||"batchIndex"in t||"payloadSchemaHash"in t}function Ph(e){if(!ae(e.metadata))return!1;const t=e.metadata[gn];return!ae(t)||t.kind!=="generic"?!1:"definitionId"in t||"key"in t||"batchIndex"in t||"payloadSchemaHash"in t}function kh(e){return e.metadata?.["tanstack:interruptPayload"]}function Fh(e){return e==="tanstack:client_tool_execution"||e==="client_tool_input"}function ht(e){if(e.responseSchema!==void 0)try{return Ge(je(e.responseSchema))}catch{return}}function oi(e){if(e!==void 0)try{return Sd(e)}catch{return}}function Pe(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"then"in e&&typeof e.then=="function"}function Vt(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(Me(e)){const s=e["~standard"].validate(t),r=i=>i.issues?{code:n,message:i.issues[0]?.message??"Schema validation failed."}:{valid:!0,payload:i.value};return Pe(s)?Promise.resolve(s).then(r):r(s)}return{valid:!0,payload:t}}function Lh(e){for(const t of Ah)if(t===e)return!0;return!1}function Nh(e){for(const t of Mh)if(t===e)return!0;return!1}function ai(e){if(!ae(e))return!1;const t=e.scope,n=e.code;return typeof n=="string"&&typeof e.message=="string"&&typeof e.retryable=="boolean"&&typeof e.threadId=="string"&&typeof e.interruptedRunId=="string"&&typeof e.generation=="number"?t==="item"?Lh(n)&&typeof e.interruptId=="string"&&(e.source==="client"||e.source==="server"):t==="batch"&&Nh(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(s=>typeof s=="string")&&(e.source==="client"||e.source==="server"||e.source==="transport"):!1}function Dh(e){return ai(e)?[e]:!ae(e)||!Array.isArray(e.errors)?[]:e.errors.every(ai)?e.errors:[]}function ia(e,t){if(e.length!==t.length)return!1;const n=[...e].sort(),s=[...t].sort();return n.every((r,i)=>r===s[i])}function li(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&ia(e.interruptIds,t.interruptIds)}function jh(e,t,n){const s=n.filter(a=>a.source!=="transport"),r=a=>t.includes(a)&&s.some(l=>li(a,l)),i=e.filter(a=>!r(a)),o=t.filter(a=>!s.some(l=>li(a,l)));return Object.freeze({rootErrors:Object.freeze([...i,...n]),submissionRootErrors:Object.freeze([...o,...s])})}function Gh(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;const n=t.resolutions.map(s=>s.interruptId);return e.scope==="item"?n.includes(e.interruptId):ia(e.interruptIds,n)}function Bn(e,t,n){const s=ht(e)??n?.responseSchemaHash;return U({v:1,kind:"generic",interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...s!==void 0?{responseSchemaHash:s}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}})}function $h(e,t){const n=U(e.descriptor),s=e.error===void 0?Object.freeze([]):Object.freeze([U(e.error)]),r=s[0];return{id:n.id,interruptId:n.id,reason:n.reason,...n.message!==void 0?{message:n.message}:{},...n.responseSchema!==void 0?{responseSchema:n.responseSchema}:{},...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{},...n.metadata!==void 0?{metadata:n.metadata}:{},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:s,...r!==void 0?{error:r}:{},canResolve:e.canResolve}}var Bh=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;const t=new Map;for(const n of e.interrupts??[]){if(t.has(n.id))throw new Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t="live"){this.activeSubmissionOperation=void 0,this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:U(e.interrupts)};const n=new Map;for(const s of e.interrupts){const r=ii(s);r?.kind==="generic"&&r.definitionId!==void 0&&r.key!==void 0&&r.batchIndex!==void 0&&n.set(r.batchIndex,(n.get(r.batchIndex)??0)+1)}this.items=e.interrupts.map(s=>this.hydrateInterrupt(s,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind==="generic"&&e.definition!==void 0)}reset(e){this.activeSubmissionOperation=void 0,this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??"live")}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e=="boolean"){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(const e of this.items)pe(e)&&(e.validationGeneration++,e.resolution=Object.freeze($n(e,{interruptId:e.descriptor.id,status:"cancelled"})),e.status="staged",e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw new Error("Interrupt submission is already active.");const e=this.retrySubmission;if(!e){this.addRootError("transport","There is no retryable interrupt submission.",!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){const n=this.items.find(s=>s.kind==="client-tool-execution"&&s.binding?.kind==="client-tool-execution"&&s.binding.toolCallId===e||s.kind==="generic"&&Fh(s.descriptor.reason)&&s.descriptor.toolCallId===e&&ra(s.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){const n=this.items.find(s=>s.descriptor.id===e&&(s.kind==="tool-approval"||s.kind==="generic"&&s.descriptor.reason==="approval_required"&&sa(s.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){const s=U(e),r=ii(s),i=r===void 0&&Oh(s);if(r===void 0&&!i)return xh(s)?{descriptor:s,binding:Bn(s,t,void 0),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","The interrupt binding is invalid or incomplete."),validationGeneration:0}:{descriptor:s,binding:void 0,kind:"unbound",status:"pending",canResolve:!1,resumable:!1,validationGeneration:0};const o=r!==void 0&&r.interruptId===s.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&ht(s)===r.responseSchemaHash,a=r!==void 0&&r.interruptId===s.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&r.responseSchemaHash===(ht(s)??r.responseSchemaHash);if(r!==void 0&&Ph(s)&&(!a||r.kind!=="generic"||r.definitionId===void 0||r.key===void 0||r.batchIndex===void 0))return{descriptor:s,binding:Bn(s,t,r),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","The interrupt binding does not match this interrupted run."),validationGeneration:0};if(a&&r.kind==="tool-approval"){const u=this.tools?.find(c=>c.name===r.toolName);if(u?.needsApproval===!0&&s.toolCallId===r.toolCallId)try{const c=fd(u.approvalSchema,u.inputSchema);if(zr(u.inputSchema)===r.inputSchemaHash&&c.approvalSchemaHash===r.approvalSchemaHash&&c.responseSchemaHash===r.responseSchemaHash)return{descriptor:s,binding:U(r),kind:"tool-approval",status:"pending",canResolve:!0,resumable:!0,tool:u,validationGeneration:0}}catch{}}if(a&&r.kind==="client-tool-execution"){const u=this.tools?.find(c=>c.name===r.toolName);if(u!==void 0&&s.toolCallId===r.toolCallId&&zr(u.outputSchema)===r.outputSchemaHash)return{descriptor:s,binding:U(r),kind:"client-tool-execution",status:"pending",canResolve:!0,resumable:!0,tool:u,validationGeneration:0}}if(r!==void 0&&r.kind==="generic"&&r.definitionId!==void 0&&r.key!==void 0&&r.batchIndex!==void 0&&r.key.length>0&&n.get(r.batchIndex)!==1)return{descriptor:s,binding:U(r),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","Generic interrupt batch contains a duplicate batchIndex."),validationGeneration:0};if(o&&r.kind==="generic"&&r.definitionId!==void 0&&r.key!==void 0&&r.batchIndex!==void 0&&r.key.length>0&&n.get(r.batchIndex)===1){const u=this.interruptDefinitions.get(r.definitionId);if(u!==void 0&&oi(u.responseSchema)===r.responseSchemaHash&&(u.payloadSchema===void 0?r.payloadSchemaHash===void 0:r.payloadSchemaHash===oi(u.payloadSchema))){const c=kh(s);return{descriptor:s,binding:U(r),definition:u,kind:"generic",status:"pending",canResolve:!0,resumable:!0,...c===void 0?{}:{payload:U(c)},validationGeneration:0}}}const l=i||r!==void 0&&r.interruptId===s.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&(r.kind!=="generic"||ht(s)===void 0||r.responseSchemaHash===ht(s));return{descriptor:s,binding:Bn(s,t,r),kind:"generic",status:"pending",canResolve:l,resumable:l,validationGeneration:0}}buildSnapshot(e){const t=this.requireHydration(),n=this.items.filter(s=>s.kind!=="client-tool-execution"&&s.status!=="submitting").map(s=>{const r=$h(s,t);if(s.kind==="unbound"||s.binding===void 0){const a={...r,kind:"unbound",canResolve:!1};return Object.freeze(a)}if(s.kind==="tool-approval"&&s.binding.kind==="tool-approval"){const a=U(s.binding),l={...r,kind:"tool-approval",binding:a,toolName:s.binding.toolName,toolCallId:s.binding.toolCallId,originalArgs:U(s.binding.originalArgs),cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:(u,c)=>{const h=ae(c)?c:void 0;this.resolveItem(s.descriptor.id,{approved:u,...u&&h?.editedArgs!==void 0?{editedArgs:h.editedArgs}:{},...h?.payload!==void 0?{payload:h.payload}:{}},e)}};return Object.freeze(l)}const i=s.binding.kind==="generic"?U(s.binding):U({v:1,kind:"generic",interruptId:s.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof s.binding.responseSchemaHash=="string"?{responseSchemaHash:s.binding.responseSchemaHash}:{}});if(s.definition!==void 0&&s.binding.kind==="generic"){const a={...r,kind:"generic",definitionId:s.definition.id,key:s.binding.key??"",payload:s.payload,binding:i,cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:l=>this.resolveItem(s.descriptor.id,l,e)};return Object.freeze(a)}const o={...r,kind:"generic",binding:i,cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:a=>this.resolveItem(s.descriptor.id,a,e)};return Object.freeze(o)});return Object.freeze(n)}publish(e="live"){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,n){this.assertItemMutable(n);const s=this.findItem(e);if(this.invalidateRetry(),!s.canResolve){s.status="error",s.error=this.itemError(e,"invalid-response-schema","The interrupt response schema is invalid and cannot be resolved."),n||this.publish();return}const r=++s.validationGeneration,i=this.validateCandidate(s,t);if(Pe(i)){s.status="validating",s.error=void 0,n||this.publish(),Promise.resolve(i).then(o=>{r===s.validationGeneration&&this.applyValidation(s,o,n)}).catch(o=>{r===s.validationGeneration&&this.applyValidation(s,{code:this.validationCode(s),message:o instanceof Error?o.message:String(o)},n)});return}this.applyValidation(s,i,n)}cancelItem(e,t){this.assertItemMutable(t);const n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze($n(n,{interruptId:e,status:"cancelled"})),n.status="staged",n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);const n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status="pending",t||this.publish()}maybeSubmit(){const e=this.items.some(i=>i.kind==="generic"),t=this.items.filter(i=>pe(i)&&!(e&&i.kind==="client-tool-execution"));if(t.length===0||t.some(i=>i.resolution===void 0||i.status!=="staged"))return;const n=this.requireHydration(),s=rd(t.map(i=>i.resolution).filter(i=>i!==void 0)),r=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:s.resolutions,canonicalResolutions:s.canonicalResolutions,fingerprint:s.fingerprint});this.submitBatch(r)}applyValidation(e,t,n){if(!("valid"in t)){e.status="error";const s=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=s,e.kind==="client-tool-execution"&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(r=>!(r.code==="item-validation-failed"&&r.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:"batch",code:"item-validation-failed",message:s.message,source:"client",retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:s.threadId,interruptedRunId:s.interruptedRunId,generation:s.generation})])),n||this.publish();return}e.resolution=U($n(e,{interruptId:e.descriptor.id,status:"resolved",payload:t.payload})),e.status="staged",e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind==="generic"){const n=Vt(e.definition?.responseSchema??e.descriptor.responseSchema,t,"invalid-payload");if(e.definition===void 0)return n;const s=r=>"valid"in r?{valid:!0,payload:t}:r;return Pe(n)?Promise.resolve(n).then(s):s(n)}return e.kind==="client-tool-execution"?Vt(e.tool?.outputSchema,t,"invalid-tool-output"):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!ae(t)||typeof t.approved!="boolean")return{code:"invalid-payload",message:"Tool approval resolutions require an approved boolean."};const n=t.approved,s=t.editedArgs;if(!n&&s!==void 0)return{code:"invalid-edited-args",message:"Rejected tool approvals cannot edit tool arguments."};if(n&&s!==void 0){const r=Vt(e.tool?.inputSchema,s,"invalid-edited-args");return Pe(r)?Promise.resolve(r).then(i=>"valid"in i?this.validateApprovalPayload(e,t,i.payload):i):"valid"in r?this.validateApprovalPayload(e,t,r.payload):r}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){const s=t.approved===!0,r=this.approvalBranchSchema(e.tool,s),i=t.payload;if(r===void 0&&i!==void 0)return{code:"invalid-payload",message:"This approval branch does not accept a payload."};if(r!==void 0&&i===void 0)return{code:"invalid-payload",message:"This approval branch requires a payload."};const o=Vt(r,i,"invalid-payload"),a=l=>"valid"in l?{valid:!0,payload:{approved:s,...n!==void 0?{editedArgs:n}:{},...r!==void 0?{payload:l.payload}:{}}}:l;return Pe(o)?Promise.resolve(o).then(a):a(o)}approvalBranchSchema(e,t){const n=e?.approvalSchema;return!ae(n)||!("approve"in n||"reject"in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind==="client-tool-execution"?"invalid-tool-output":"invalid-payload"}resolveBooleanBulk(e){const t=this.items.filter(n=>pe(n)&&n.kind!=="client-tool-execution");if(!t.every(n=>n.kind==="tool-approval"&&this.approvalBranchSchema(n.tool,e)===void 0)||t.length===0){this.addRootError("unsupported-bulk-operation","Boolean bulk resolution requires payloadless tool approvals.",!1);return}this.invalidateRetry();for(const n of t)n.validationGeneration++,n.resolution=U({interruptId:n.descriptor.id,status:"resolved",payload:{approved:e}}),n.status="staged",n.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){const t=this.items.map(i=>({status:i.status,...i.resolution!==void 0?{resolution:i.resolution}:{},...i.error!==void 0?{error:i.error}:{},validationGeneration:i.validationGeneration})),n={active:!0};this.activeTransaction=n;const s=this.buildSnapshot(n).filter(Th);let r;try{for(const i of s){const o=e(i);if(o!==void 0){r={code:Pe(o)?"async-resolver":"inactive-transaction",message:Pe(o)?"Interrupt transaction resolvers must be synchronous.":"Interrupt transaction resolvers must return literal undefined."};break}}r===void 0&&this.items.some(i=>pe(i)&&i.kind!=="client-tool-execution"&&(i.resolution===void 0||i.status!=="staged"))&&(r={code:"incomplete-batch",message:"Interrupt transaction did not resolve every item."})}catch(i){r={code:"item-validation-failed",message:i instanceof Error?i.message:String(i)}}finally{n.active=!1,this.activeTransaction=void 0}if(r){this.restoreCheckpoints(t),this.addRootError(r.code,r.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,n)=>{const s=e[n];s&&(t.status=s.status,t.resolution=s.resolution,t.error=s.error,t.validationGeneration=s.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active)throw new Error("Interrupt transaction is inactive.");if(this.activeTransaction&&e!==this.activeTransaction)throw new Error("Interrupt transaction is inactive.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}assertRootMutable(){if(this.activeTransaction)throw new Error("Interrupt transaction is already active.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){const t={submission:e};this.activeSubmissionOperation=t,this.resuming=!0,this.retrySubmission=void 0;for(const n of this.items)pe(n)&&(n.status="submitting");this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){const n=Dh(e);if(n.length===0){const l=e instanceof Error?e.message:String(e);this.addRootError("transport",l,!0,"transport"),this.retrySubmission=t;for(const u of this.items)pe(u)&&(u.status="error");return}const s=n.filter(l=>Gh(l,t));s.length!==n.length&&this.addRootError("protocol","Interrupt submission errors did not match the active batch.",!1);let r=!1,i=!1;const o=[];for(const l of s)if((l.code==="stale"||l.code==="expired"||l.code==="conflict")&&(r=!0),i||=l.retryable,l.scope==="item"){const u=this.items.find(c=>pe(c)&&c.descriptor.id===l.interruptId);u&&(u.status="error",u.error=U(l))}else o.push(U(l));const a=jh(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=a.rootErrors,this.submissionRootErrors=a.submissionRootErrors;for(const l of this.items)pe(l)&&l.status==="submitting"&&(l.status="error");this.retrySubmission=i&&!r?t:void 0}addRootError(e,t,n,s="client"){const r=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:"batch",code:e,message:t,source:s,retryable:n,interruptIds:Object.freeze(this.items.filter(pe).map(i=>i.descriptor.id)),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})]),this.publish()}findItem(e){const t=this.items.find(n=>n.descriptor.id===e);if(!t)throw new Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw new Error("InterruptManager is not hydrated.");return this.hydration}itemError(e,t,n,s){const r=this.requireHydration();return Object.freeze({scope:"item",interruptId:e,code:t,message:n,...s!==void 0?{path:Object.freeze([...s])}:{},source:"client",retryable:!1,threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})}};function Uh(e,...t){const n=e?.();if(ie(n))return n;for(const s of t)if(ie(s))return s}async function Hh(e,t){if(!t)throw new ko;return await e.prepare(t),e.headers(t)}function zh(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():Math.random().toString(36).slice(2)}var qt;function ui(){return qt!==void 0||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__=zh()),qt=globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__),qt}var Vh=0;function ue(e){return e==null||e===""?"missing":`value-${encodeURIComponent(String(e))}`}function Is(e){const t=e.runtimeId??ui(),n=e.eventId&&e.eventId.length>0?e.eventId:[e.source,e.eventType,ue(t),ue(e.clientId),ue(e.requestId),ue(e.streamId),ue(e.hookId),ue(e.threadId),ue(e.runId),ue(e.messageId),ue(e.toolCallId),ue(e.sequence),e.timestamp,ui(),Vh++].join(":");return{...e,runtimeId:t,eventId:n}}var qh=class{#t=!0;#e;#n;#s;#i;#r;#a;#l;#h=0;#o=5;#u=!1;#f=!1;#d=null;#p=()=>{this.debugLog("Connected to event bus"),this.#r=!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)};#g=()=>{if(this.#h<this.#o){this.#h++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#n().removeEventListener("tanstack-connect",this.#g),this.#f=!0,this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};#m=()=>{this.#u||(this.#u=!0,this.#n().addEventListener("tanstack-connect-success",this.#p),this.#g())};constructor({pluginId:e,debug:t=!1,enabled:n=!0,reconnectEveryMs:s=300}){this.#e=e,this.#t=n,this.#n=this.getGlobalTarget,this.#s=t,this.debugLog(" Initializing event subscription for plugin",this.#e),this.#i=[],this.#r=!1,this.#f=!1,this.#a=null,this.#l=s}startConnectLoop(){this.#a!==null||this.#r||(this.debugLog(`Starting connect loop (every ${this.#l}ms)`),this.#a=setInterval(this.#g,this.#l))}stopConnectLoop(){this.#u=!1,this.#a!==null&&(clearInterval(this.#a),this.#a=null,this.#i=[],this.debugLog("Stopped connect loop"))}debugLog(...e){this.#s&&console.log(`🌴 [tanstack-devtools:${this.#e}-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"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;const e=typeof EventTarget<"u"?new EventTarget:void 0;return typeof e>"u"||typeof e.addEventListener>"u"?(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.#e}dispatchCustomEventShim(e,t){try{const 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.#e}:${e}`,payload:t,pluginId:this.#e}}emit(e,t){if(!this.#t){this.debugLog("Event bus client is disabled, not emitting event",e,t);return}if(this.#d&&(this.debugLog("Emitting event to internal event target",e,t),this.#d.dispatchEvent(new CustomEvent(`${this.#e}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#f){this.debugLog("Previously failed to connect, not emitting to bus");return}if(!this.#r){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.#m(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,n){const s=n?.withEventTarget??!1,r=`${this.#e}:${e}`;if(s&&(this.#d||(this.#d=new EventTarget),this.#d.addEventListener(r,o=>{t(o.detail)})),!this.#t)return this.debugLog("Event bus client is disabled, not registering event",r),()=>{};const i=o=>{this.debugLog("Received event from bus",o.detail),t(o.detail)};return this.#n().addEventListener(r,i),this.debugLog("Registered event to bus",r),()=>{s&&this.#d?.removeEventListener(r,i),this.#n().removeEventListener(r,i)}}onAll(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=n=>{const s=n.detail;e(s)};return this.#n().addEventListener("tanstack-devtools-global",t),()=>this.#n().removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=n=>{const s=n.detail;this.#e&&s.pluginId!==this.#e||e(s)};return this.#n().addEventListener("tanstack-devtools-global",t),()=>this.#n().removeEventListener("tanstack-devtools-global",t)}},Kh=class extends qh{constructor(){super({pluginId:"tanstack-ai-devtools"})}},ci=Symbol.for("tanstack.ai.devtools.eventClient");function Qh(){const e=globalThis,t=e[ci];if(t)return t;const n=new Kh;return e[ci]=n,n}var wt=Qh();function X(e,t){wt.emit(e,t)}var oa=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent("client:created",{initialMessageCount:e})}loadingChanged(e){this.emitEvent("client:loading:changed",{isLoading:e})}errorChanged(e){this.emitEvent("client:error:changed",{error:e})}textUpdated(e,t,n,s){this.emitEvent("text:chunk:content",{streamId:e,messageId:t,content:n,...s})}toolCallStateChanged(e,t,n,s,r,i,o){this.emitEvent("tools:call:updated",{streamId:e,messageId:t,toolCallId:n,toolName:s,state:r,arguments:i,...o})}thinkingUpdated(e,t,n,s,r){this.emitEvent("text:chunk:thinking",{streamId:e,messageId:t,content:n,delta:s,...r})}structuredOutputChanged(e,t,n,s,r){this.emitEvent(e,{streamId:t,messageId:n,...s,...r})}approvalRequested(e,t,n,s,r,i,o){this.emitEvent("tools:approval:requested",{streamId:e,messageId:t,toolCallId:n,toolName:s,input:r,approvalId:i,...o})}messageAppended(e,t,n){const s=e.parts.filter(r=>r.type==="text").map(r=>r.content).join(" ");this.emitEvent("text:message:created",{streamId:t,messageId:e.id,role:e.role,content:s,parts:e.parts,...n})}messageSent(e,t){const n=typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.content).join("");this.emitEvent("text:message:created",{messageId:e,role:"user",content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent("text:message:user",{messageId:e,role:"user",content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent("client:reloaded",{fromMessageIndex:e})}stopped(){this.emitEvent("client:stopped")}messagesCleared(){this.emitEvent("client:messages:cleared")}toolResultAdded(e,t,n,s,r){this.emitEvent("tools:result:added",{toolCallId:e,toolName:t,output:n,state:s,...r})}toolApprovalResponded(e,t,n,s){this.emitEvent("tools:approval:responded",{approvalId:e,toolCallId:t,approved:n,...s})}toolFixtureApplied(e){this.emitEvent("devtools:tool-fixture:applied",{...e})}},Wh=class extends oa{emitEvent(e,t){const n=Date.now(),s=e.startsWith("text:")||e.startsWith("tools:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",r=e.startsWith("client:")||e.startsWith("tools:")||e.startsWith("text:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",i=s?"user-visible":"client-state",o={hookId:this.clientId,...typeof t?.threadId=="string"?{threadId:t.threadId}:{},...typeof t?.runId=="string"?{runId:t.runId}:{},...typeof t?.streamId=="string"?{streamId:t.streamId}:{},...typeof t?.messageId=="string"?{messageId:t.messageId}:{},...typeof t?.toolCallId=="string"?{toolCallId:t.toolCallId}:{}};if(r){const a=Is({eventType:e,clientId:this.clientId,...o,source:"client",visibility:i,timestamp:n});wt.emit(e,{...t,...a})}else{const a=Is({eventType:e,source:"client",visibility:"client-state",timestamp:n});wt.emit(e,{...t,...a})}}},Jh=class extends oa{emitEvent(){}},Xh=class{events;constructor(e){this.events=new Jh(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,s){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return""}observeChunk(e){}recordMemoryState(e){}recordCompactionEvent(e,t){}recordCompactionState(e){}recordSkillsState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Yh=e=>new Xh(e);function di(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function hi(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function fi(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function Zh(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var ef=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,s){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=s}writeState(){const e=[...this.lastMessages];if(e.length===0&&!this.lastResume){const s=this.generation;this.runOperation(()=>{if(s===this.generation)return this.adapter.removeItem(this.id)});return}const t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}readInitial(){try{const e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(di).catch(()=>{});const t=di(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;const t=this.messagesGeneration;e.then(n=>{!n||this.messagesGeneration!==t||(this.lastResume=n.resume??null,this.lastMessages=n.messages,this.applyMessages(n.messages),n.resume&&this.applyResume&&this.applyResume(n.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;const e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){const t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{const t=e();if(t instanceof Promise){this.queuePending=!0;const n=t.catch(()=>{});this.queue=n,n.finally(()=>{this.queue===n&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){const t=se(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const n=hi(e);if(n&&this.clearedToolCallIds.has(n))return!0;const s=Zh(e);if(s&&this.clearedMessageIds.has(s))return n&&this.clearedToolCallIds.add(n),!0;const r=fi(e);return r?!!this.clearedMessageIds.has(r):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){const e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){const t=fi(e);t&&this.clearedMessageIds.add(t);const n=hi(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return se(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type==="TEXT_MESSAGE_START"||e.type==="TEXT_MESSAGE_CONTENT"||e.type==="TOOL_CALL_START"||e.type==="TOOL_CALL_ARGS"||e.type==="TOOL_CALL_END"||e.type==="TOOL_CALL_RESULT"||e.type==="MESSAGES_SNAPSHOT"||e.type==="RUN_ERROR"}};function pi(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function gi(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function tf(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var nf=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){const t=se(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const n=pi(e);if(n&&this.clearedToolCallIds.has(n))return!0;const s=tf(e);if(s&&this.clearedMessageIds.has(s))return n&&this.clearedToolCallIds.add(n),!0;const r=gi(e);return!!(r&&this.clearedMessageIds.has(r))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){const e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){const t=gi(e);t&&this.clearedMessageIds.add(t);const n=pi(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return se(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type==="TEXT_MESSAGE_START"||e.type==="TEXT_MESSAGE_CONTENT"||e.type==="TOOL_CALL_START"||e.type==="TOOL_CALL_ARGS"||e.type==="TOOL_CALL_END"||e.type==="TOOL_CALL_RESULT"||e.type==="MESSAGES_SNAPSHOT"||e.type==="RUN_ERROR"}};function sf(e){const t=new Set;for(const n of e??[]){if(t.has(n.id))throw new Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function mi(e){const{connection:t,fetcher:n}=e;if(t&&n)throw new Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return Eh(n);throw new Error("ChatClient: either `connection` or `fetcher` is required.")}function vi(e){return"connect"in e}function rf(e){if(e.type!=="RUN_FINISHED"||e.outcome?.type==="interrupt")return!1;const t=e;return t.finishReason!==void 0?t.finishReason==="tool_calls":B(e)?.finishReason==="tool_calls"}function Si(e){const t={whenBusy:"queue",drain:"fifo",onOverflow:"reject"};if(!e)return t;if(typeof e=="string")return{...t,whenBusy:e};if(typeof e=="function")return{...t,strategy:e};const n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new Error("ChatClient: queue.maxSize must be a non-negative integer");return{whenBusy:e.whenBusy??"queue",drain:e.drain??"fifo",onOverflow:e.onOverflow??"reject",...n!==void 0?{maxSize:n}:{}}}function of(e){const t=e.at(-1)?.body,n=[];for(const i of e){if(typeof i.content!="string")break;n.push(i.content)}if(n.length===e.length)return{content:n.join(`
|
|
11
|
-
`),...t!==void 0?{body:t}:{}};const s=[];let r;for(const i of e){if(typeof i.content=="string"){s.push({type:"text",content:i.content});continue}typeof i.content.content=="string"?s.push({type:"text",content:i.content.content}):s.push(...i.content.content),r=No(r,i.content.metadata)}return{content:{content:s,...r!==void 0?{metadata:r}:{}},...t!==void 0?{body:t}:{}}}function af(e){if(!(e===null||typeof e!="object"||Array.isArray(e))&&!(!("approved"in e)||typeof e.approved!="boolean"))return e.approved}function lf(e){const t=e;if(t===null||typeof t!="object"||!("resumeState"in t))return;const n=t.resumeState;if(!(n===null||typeof n!="object"||!("threadId"in n)||typeof n.threadId!="string"||n.threadId.length===0||!("runId"in n)||typeof n.runId!="string"||n.runId.length===0))return{threadId:n.threadId,runId:n.runId}}var uf=2e3,cf=new Set(["TEXT_MESSAGE_START","TEXT_MESSAGE_CONTENT","TOOL_CALL_START","MESSAGES_SNAPSHOT"]),df=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new nf;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status="ready";connectionStatus="disconnected";abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;connectionDrainsOnSend=!1;errorReportedGeneration=null;streamGeneration=0;continuationGeneration=0;streamContinuationGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){sf(e.interrupts),this.threadId=e.threadId||"",this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1}else if(e.persistence){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new ef(e.persistence,e.threadId,a=>this.processor.setMessages(a),a=>this.applyPersistedResume(a))}this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=Si(e.queue);const n=mi(e);if(this.connectionDrainsOnSend=vi(n),this.connection=ri(n),this.clientToolsRef={current:new Map},e.tools)for(const a of e.tools)this.clientToolsRef.current.set(a.name,a);this.devtoolsBridge=(e.devtoolsBridgeFactory??Yh)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new Bh({...e.tools!==void 0?{tools:e.tools}:{},...e.interrupts!==void 0?{interrupts:e.interrupts}:{},submit:a=>this.submitInterruptBatch(a),onChange:a=>this.notifyResumeStateChange(a)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);const s=this.persistor?.readInitial(),r=s instanceof Promise?void 0:s,i=r?r.messages:e.initialMessages;let o=null;if(r?.resume){const a=r.resume;Array.isArray(a.pendingInterrupts)&&a.pendingInterrupts.length>0?this.applyResumeSnapshot(a):a.resumeState.runId&&(o=a.resumeState.runId)}if(!o&&e.initialResumeSnapshot){const a=e.initialResumeSnapshot;!(Array.isArray(a.pendingInterrupts)&&a.pendingInterrupts.length>0)&&a.resumeState.runId&&(o=a.resumeState.runId)}this.processor=new lh({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...i?{initialMessages:i}:{},events:{onMessagesChange:a=>{this.persistor?.notifyMessagesChanged(a),this.callbacksRef.current.onMessagesChange(a)},onStreamStart:()=>{this.setStatus("streaming");const a=this.processor.getCurrentAssistantMessageId();if(!a)return;const l=this.processor.getMessages().find(u=>u.id===a);l&&(this.currentMessageId=l.id,this.events.messageAppended(l,this.currentStreamId||void 0))},onStreamEnd:a=>{this.callbacksRef.current.onFinish(a),this.setStatus("ready"),this.resolveProcessing()},onError:a=>{this.reportStreamError(a)},onTextUpdate:(a,l)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,a,l)},onThinkingUpdate:(a,l)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,a,l,void 0)},onStructuredOutputChange:a=>{const l=this.devtoolsBridge.resolveStreamId(),u=a.phase==="start"?"structured-output:started":a.phase==="complete"?"structured-output:completed":a.phase==="error"?"structured-output:errored":"structured-output:updated";this.currentMessageId=a.messageId,this.events.structuredOutputChanged(u,l,a.messageId,{status:a.status,raw:a.raw,...a.partial!==void 0?{partial:a.partial}:{},...a.data!==void 0?{data:a.data}:{},...a.reasoning!==void 0?{reasoning:a.reasoning}:{},...a.errorMessage!==void 0?{errorMessage:a.errorMessage}:{},...a.delta!==void 0?{delta:a.delta}:{}})},onToolCallStateChange:(a,l,u,c)=>{const h=this.processor.getMessages().find(d=>d.id===a)?.parts.find(d=>d.type==="tool-call"&&d.id===l)?.name||"unknown";this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,a,l,h,u,c)},onToolCall:a=>{const l=(this.activeClientTools??this.clientToolsRef.current).get(a.toolName),u=l?.execute;if(u){const c=this.continuationGeneration,h=this.devtoolsBridge.getCurrentRunEventContext(),d=(async()=>{try{const f=this.activeClientTools===null?this.context:this.activeContext,p=await u(a.input,{toolCallId:a.toolCallId,context:f,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:a.toolCallId,tool:a.toolName,output:p,state:"output-available"},l,c,h)}catch(f){await this.addToolResultForClientTool({toolCallId:a.toolCallId,tool:a.toolName,output:null,state:"output-error",errorText:f.message},l,c,h)}finally{this.pendingToolExecutions.delete(a.toolCallId)}})();this.pendingToolExecutions.set(a.toolCallId,d)}},onApprovalRequest:a=>{const l=this.devtoolsBridge.resolveStreamId(),u=this.findMessageIdForToolCall(a.toolCallId)??this.currentMessageId??"";this.events.approvalRequested(l,u,a.toolCallId,a.toolName,a.input,a.approvalId)},onCustomEvent:(a,l,u)=>{a==="memory:state"&&this.devtoolsBridge.recordMemoryState(l),(a==="compaction:started"||a==="compaction:state"||a==="compaction:ended")&&this.devtoolsBridge.recordCompactionEvent(a,l),a==="skills:state"&&this.devtoolsBridge.recordSkillsState(l),this.callbacksRef.current.onCustomEvent(a,l,u)}}}),this.persistor?.hydrateAsync(s),this.rejoinRunId=o,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){const t=lf(e);if(t===void 0){this.interruptManager.reset({source:"hydrate"});return}this.lastResume=t;const n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:"hydrate"});return}const s=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:s,interrupts:n},"hydrate")}applyPersistedResume(e){this.applyResumeSnapshot(e);const t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){const e=this.connection.hydrate;e&&(this.isLoading||this.abortController||this.disposed||(async()=>{let t;try{t=await e(this.threadId)}catch{return}this.disposed||!this.tailing||this.isLoading||this.abortController||(t.messages.length>0&&this.processor.setMessages(Fo(t.messages)),t.interrupts&&t.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId))})())}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||(this.threadId=this.generateUniqueId("thread")),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!=="RUN_ERROR")return;const t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=se(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),se(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type==="RUN_STARTED"){const r=se(e)??e.runId;this.activeResumeThreadId="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=r,this.activeRunIds.add(r),this.clearedStreamTracker.onRunStarted(r),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:r});return}if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const n=se(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type==="RUN_ERROR"&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);const s=e.type==="RUN_FINISHED"&&rf(e);t?.resolveProcessing!==!1&&!s&&this.resolveProcessing()}observeInterruptState(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR"||this.activeInterruptSubmission&&e.type==="RUN_ERROR")return;const t=se(e),n="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId;if(e.type==="RUN_FINISHED"&&e.outcome?.type==="interrupt"){const u=this.currentRunId??t??this.activeResumeRunId??"";this.lastResume={threadId:n??this.threadId,runId:u},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:u,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},"live");return}const s=e.type==="RUN_ERROR"&&!t,r=!!(t&&this.lastResume?.runId===t),i=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),a=this.isLoading&&e.type==="RUN_FINISHED"&&!t,l=!!(this.activeInterruptSubmission&&this.isLoading&&e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt");if(s||r||i||o||a||l){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange("live")}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e=="boolean"){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){const n=t??this.lastResume;return n?this.resumeInterruptsUnsafeForGeneration(e,n,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,n){return n!==this.continuationGeneration?Promise.resolve(!1):this.isLoading?new Promise((s,r)=>{this.queuePostStreamAction(async()=>{try{s(await this.resumeInterruptsUnsafeForGeneration(e,t,n))}catch(i){r(i)}})}):(this.pendingResumeThreadId=t.threadId,this.pendingResumeParentRunId=t.runId,this.pendingResumeItems=[...e],this.streamResponse())}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){const t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(const r of e.resolutions){const i=af(r.payload);if(i===void 0)continue;const o=r.interruptId;this.processor.addToolApprovalResponse(o,i)}const n=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},t).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(t!==this.continuationGeneration)return;const s=this.takeInterruptSubmissionFailure();if(s!==void 0)throw{errors:s.errors};if(!n)throw new Error("Interrupt continuation could not be started.");this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){const e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(const n of e){const s=n.metadata?.["tanstack:interruptBinding"];if(s===null||typeof s!="object"||!("generation"in s)||typeof s.generation!="number"||!Number.isInteger(s.generation)||s.generation<0||t!==void 0&&t!==s.generation)return 0;t=s.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){const t=this.getResumeState(),n=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}const t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){const t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??"useChat",outputKind:e?.outputKind??"chat",...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:n=>{this.processor.setMessages(n)},addToolResult:(n,s,r)=>{this.processor.addToolResult(n,s,r)},generateId:n=>this.generateUniqueId(n)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){const t=this.processor.getMessages();for(const n of t)if(n.parts.find(s=>s.type==="tool-call"&&s.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus("ready")}reportStreamError(e){const t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status==="submitted"||this.status==="streaming")&&this.setStatus("error"),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;const e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(t=>{t instanceof Error&&t.name!=="AbortError"&&(this.setConnectionStatus("error"),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(t)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!=="error"&&this.setConnectionStatus("disconnected")))})}async consumeSubscription(e){const t=this.connection.subscribe(e);for await(const n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}resumeInFlightRun(e){const t=this.connection.joinRun;if(!t)return;const n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus("streaming"),(async()=>{let s=!1,r=!1,i=!1;const o=setTimeout(()=>{r||n.abort()},uf);try{for await(const a of t(e,n.signal)){if(n.signal.aborted)break;r||(r=!0,clearTimeout(o)),!s&&cf.has(a.type)&&(s=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(a){const l=a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError");!r&&!l&&(i=!0),r&&!l&&this.reportStreamError(a instanceof Error?a:new Error(String(a)))}finally{clearTimeout(o),!r&&i&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===n&&(this.abortController=null,this.setIsLoading(!1),this.status==="streaming"&&this.setStatus("ready"),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){const e=this.processor.getMessages(),t=e[e.length-1];t&&t.role==="assistant"&&this.processor.setMessages(e.slice(0,-1))}async processIncomingChunk(e,t){if(e=Xo(e),e.type==="RUN_ERROR"&&this.isActiveInterruptSubmissionFailure(e)){const n=B(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(n)?n:[]}}if(this.connectionStatus==="connecting"&&this.setConnectionStatus("connected"),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR")&&(se(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>"u"||!document.hidden)&&await new Promise(n=>setTimeout(n,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){const t=this.activeInterruptSubmission,n=B(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;const s=se(e);return s!==void 0&&s!==this.currentRunId||typeof e.threadId=="string"&&e.threadId!==t.threadId?!1:n.every(r=>r==null||typeof r!="object"||typeof r.threadId!="string"||typeof r.interruptedRunId!="string"||typeof r.generation!="number"?!1:r.threadId===t.threadId&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation)}resolveJoinedRun(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=se(e);if(t===void 0)return;const n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),typeof e=="string"&&!e.trim())return;if(this.hasPendingInterrupts())throw new Error("ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.");const s={...t,...n?.body};if(this.isSendBusy()){const{action:r,id:i}=this.decideWhenBusy(e,n);if(r==="drop")return;if(r==="queue"){this.enqueueMessage(e,s,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,s)}finally{this.sendInFlight=!1}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?"streaming":this.messageQueueDraining?"draining":"sendInFlight"}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{const n=this.normalizeMessageInput(e);this.pendingMessageBody=t;const s=this.processor.addUserMessage(n.content,n.id,n.metadata);return this.events.messageSent(s.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){const n=this.generateUniqueId("queued");if(t?.whenBusy)return{action:t.whenBusy,id:n};const{strategy:s,whenBusy:r}=this.queueConfig;if(s){const{action:i}=s({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:i,id:n}}return{action:r,id:n}}enqueueMessage(e,t,n){const{maxSize:s,onOverflow:r}=this.queueConfig;if(s!==void 0&&this.messageQueue.length>=s){if(r==="reject"||s===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId("queued"),content:e,createdAt:Date.now(),...t!==void 0?{body:t}:{}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e=="string"?{content:e.trim()}:{content:e.content,id:e.id,...e.metadata!==void 0?{metadata:e.metadata}:{}}}async append(e){if(this.mountDevtools(),this.hasPendingInterrupts())throw new Error("ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.");const t=jd(e,Ne);if(t.role==="system")return;const n=t;this.events.messageAppended(n);const s=this.processor.getMessages();if(this.processor.setMessages([...s,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;const e=++this.streamGeneration;this.streamContinuationGeneration=this.continuationGeneration;const t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,s=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;const r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(r),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=r,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus("submitted"),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;const i=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,a=null,l=!1;try{const u=this.processor.getMessages(),c=new Map(this.clientToolsRef.current),h=this.context;if(await this.callbacksRef.current.onResponse(),i.aborted)return!1;const d={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId("stream"),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=c,this.activeContext=h,this.processor.prepareAssistantMessage(),this.ensureSubscription();const f=this.waitForProcessing();let p;if(this.byok){const m=Uh(this.byokProvider,d.provider);p=await Hh(this.byok,m)}const g={threadId:t??this.threadId,runId:r,...n!==null?{parentRunId:n}:{},clientTools:Array.from(c.values()).map(m=>({name:m.name,description:m.description,parameters:m.inputSchema?fs(m.inputSchema):{type:"object"}})),forwardedProps:{...d},...s?{resume:s}:{},...p?{headers:p}:{}};if(this.devtoolsBridge.beginRun(g.runId,g.threadId),a=g.runId,this.devtoolsBridge.emitRunLifecycle("run:created",g.runId,"created"),this.devtoolsBridge.emitRunLifecycle("run:started",g.runId,"started"),this.devtoolsBridge.emitSnapshot(),await this.connection.send(u,d,i,g),e!==this.streamGeneration||i.aborted||(this.connectionDrainsOnSend&&this.resolveProcessing(),await f,e!==this.streamGeneration))return!1;if(this.status==="error")return a&&(this.devtoolsBridge.emitRunLifecycle("run:errored",a,"errored",this.error?{error:this.error.message}:{}),l=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),o=!0}catch(u){const c=u instanceof Error?u:new Error(String(u));if(c.name==="AbortError")return a&&(this.devtoolsBridge.emitRunLifecycle("run:cancelled",a,"cancelled"),l=!0),!1;if(c instanceof cs&&this.byok?.request(c.provider,"missing"),c instanceof on&&c.reason==="locked"&&this.byok?.request(c.provider,"locked"),e===this.streamGeneration&&(this.reportStreamError(c),a&&(this.devtoolsBridge.emitRunLifecycle("run:errored",a,"errored",{error:c.message}),l=!0)),e===this.streamGeneration&&(c instanceof cs||c instanceof on||c instanceof ko))throw c}finally{e===this.streamGeneration&&(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,a&&!l&&(o?this.devtoolsBridge.emitRunLifecycle("run:completed",a,"completed"):i.aborted&&this.devtoolsBridge.emitRunLifecycle("run:cancelled",a,"cancelled")),await this.drainPostStreamActions(),o?(this.status!=="ready"&&this.setStatus("ready"),this.messageQueueDraining||await this.drainQueue()):this.flushQueue())}return o}subscribe(e){const t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus("connecting"),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected")}async reload(){const e=this.processor.getMessages();if(e.length===0)return;const t=e.findLastIndex(n=>n.role==="user");t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){this.continuationGeneration++;const e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),this.lastResume=null,this.activeInterruptSubmission=void 0,this.interruptManager.reset(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){const e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.discardPendingSends(),this.persistor?.remove(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){const t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t,this.streamContinuationGeneration)}async addToolResultForClientTool(e,t,n,s){if(t&&e.state!=="output-error")try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(r){e={...e,output:null,state:"output-error",errorText:r.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||"output-available",s),n===this.continuationGeneration&&(this.processor.addToolResult(e.toolCallId,e.output,e.state==="output-error"?e.errorText||"Tool execution failed":void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state==="output-error"?{error:e.errorText||"Tool execution failed"}:e.output))){if(this.isLoading){this.queuePostStreamAction(()=>n===this.continuationGeneration?this.checkForContinuation():Promise.resolve());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&Me(e.outputSchema)?ld(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;const t=this.processor.getMessages();let n;for(const s of t){const r=s.parts.find(i=>i.type==="tool-call"&&i.approval?.id===e.id);if(r){n=r.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){const t=this.continuationGeneration;this.postStreamActions.push(async()=>{t===this.continuationGeneration&&await e()})}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.streamContinuationGeneration===this.continuationGeneration&&!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;const e=this.processor.getMessages().findLast(t=>t.role==="assistant");return!e||!e.parts.some(t=>t.type==="tool-call")?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain==="batch"){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.splice(0);this.emitQueueChange();const t=of(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){const t=this.messageQueue.findIndex(n=>n.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){const t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected");const n=mi({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=vi(n),this.connection=ri(n),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),e.byok!==void 0&&(this.byok=e.byok),e.byokProvider!==void 0&&(this.byokProvider=e.byokProvider),"context"in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(const t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=Si(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};function yi(e){return!e||typeof e!="object"?{}:{..."before"in e&&typeof e.before=="number"?{before:e.before}:{},..."after"in e&&typeof e.after=="number"?{after:e.after}:{},..."messagesBefore"in e&&typeof e.messagesBefore=="number"?{messagesBefore:e.messagesBefore}:{},..."messagesAfter"in e&&typeof e.messagesAfter=="number"?{messagesAfter:e.messagesAfter}:{},..."reusedCheckpoint"in e&&typeof e.reusedCheckpoint=="boolean"?{reusedCheckpoint:e.reusedCheckpoint}:{},..."maxTokens"in e&&typeof e.maxTokens=="number"?{maxTokens:e.maxTokens}:{},..."strategyKey"in e&&typeof e.strategyKey=="string"?{strategyKey:e.strategyKey}:{},..."durationMs"in e&&typeof e.durationMs=="number"?{durationMs:e.durationMs}:{}}}function Ii(e){if(!Array.isArray(e))return;const t=[];for(const n of e)!n||typeof n!="object"||!("role"in n)||!("tokens"in n)||!("text"in n)||typeof n.role!="string"||typeof n.tokens!="number"||typeof n.text!="string"||t.push({role:n.role,tokens:n.tokens,text:n.text});return t}function hf(e){if(!e||typeof e!="object"||!("before"in e)||!("after"in e)||!("messagesBefore"in e)||!("messagesAfter"in e)||typeof e.before!="number"||typeof e.after!="number"||typeof e.messagesBefore!="number"||typeof e.messagesAfter!="number")return null;const t="reusedCheckpoint"in e&&e.reusedCheckpoint===!0,n="maxTokens"in e&&typeof e.maxTokens=="number"?e.maxTokens:void 0,s="strategyKey"in e&&typeof e.strategyKey=="string"?e.strategyKey:void 0,r="dropped"in e?Ii(e.dropped):void 0,i="result"in e?Ii(e.result):void 0;return{before:e.before,after:e.after,messagesBefore:e.messagesBefore,messagesAfter:e.messagesAfter,reusedCheckpoint:t,...n!==void 0?{maxTokens:n}:{},...s?{strategyKey:s}:{},...r?{dropped:r}:{},...i?{result:i}:{}}}var Ri=Symbol.for("tanstack.ai.devtools.activeBridgeByHookId");function Un(){const e=globalThis,t=e[Ri];if(t)return t;const n=new Map;return e[Ri]=n,n}function ff(e,t){return{get hookId(){return e.hookId},get clientId(){return e.clientId},get threadId(){return e.threadId},metadata:e.metadata,getSnapshot:t.getSnapshot,...t.getTools||e.getTools?{getTools:t.getTools??e.getTools}:{},...t.applyToolFixture||e.applyToolFixture?{applyToolFixture:t.applyToolFixture??e.applyToolFixture}:{}}}var pf=class{options;unsubscribers=[];disposed=!1;superseded=!1;registered=!1;constructor(e){this.options=e}emitRegistered(){this.prepareForMountEmit()&&(this.registered=!0,X("hook:registered",{...this.createEnvelope("hook:registered"),...this.createMetadataPayload(),lifecycle:"mounted"}))}emitUpdated(){this.prepareForEmit()&&X("hook:updated",{...this.createEnvelope("hook:updated"),...this.createMetadataPayload(),lifecycle:"active"})}emitSnapshot(){this.prepareForEmit()&&X("hook:state-snapshot",{...this.createEnvelope("hook:state-snapshot"),...this.createMetadataPayload(),state:this.options.getSnapshot()})}emitToolsRegistered(){if(!this.prepareForEmit())return;const e=this.options.getTools?Array.from(this.options.getTools()).map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema?fs(t.inputSchema):{type:"object"},outputSchema:t.outputSchema?fs(t.outputSchema):void 0,needsApproval:t.needsApproval,metadata:t.metadata})):[];X("tools:registered",{...this.createEnvelope("tools:registered"),...this.createMetadataPayload(),tools:e})}emitRunLifecycle(e,t,n,s={}){this.prepareForEmit()&&X(e,{...this.createEnvelope(e,"client-state",{runId:t}),runId:t,status:n,...s.error?{error:s.error}:{}})}deactivate(){const e=Un();e.get(this.options.hookId)===this&&e.delete(this.options.hookId);for(const t of this.unsubscribers.splice(0))t()}supersede(){this.disposed||(this.superseded=!0,this.disposed=!0,this.deactivate())}dispose(){if(this.disposed)return;if(this.disposed=!0,!this.registered){this.deactivate();return}if(Un().get(this.options.hookId)!==this){this.deactivate();return}const e={...this.createEnvelope("hook:unregistered"),...this.createMetadataPayload(),reason:"disposed"};X("hook:unregistered",e),this.deactivate()}prepareForEmit(){return this.disposed||this.superseded?!1:(this.activate(),!0)}prepareForMountEmit(){return this.superseded?!1:(this.disposed&&(this.disposed=!1,this.registered=!1),this.activate(),!0)}activate(){if(this.disposed)return;const e=Un(),t=e.get(this.options.hookId);t&&t!==this&&(typeof t.supersede=="function"?t.supersede():t.deactivate()),e.set(this.options.hookId,this),!(this.unsubscribers.length>0)&&(this.unsubscribers.push(wt.on("devtools:request-state",n=>{this.handleRequestState(n)})),this.options.applyToolFixture&&this.unsubscribers.push(wt.on("devtools:tool-fixture:apply",n=>{this.handleToolFixtureApply(n)})))}handleRequestState(e){if(this.disposed||this.superseded)return;const t=e.payload.targetHookId;t&&t!==this.options.hookId||(this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot(),this.onReplayState())}onReplayState(){}async handleToolFixtureApply(e){const t=e.payload;this.matchesFixtureTarget(t)&&await this.options.applyToolFixture?.(t)}matchesFixtureTarget(e){return!e.hookId&&!e.threadId?!1:e.hookId?e.hookId===this.options.hookId:!(e.threadId&&(!this.options.threadId||e.threadId!==this.options.threadId))}createEnvelope(e,t="client-state",n={}){return Is({eventType:e,source:"client",visibility:t,clientId:this.options.clientId,hookId:this.options.hookId,...this.options.threadId?{threadId:this.options.threadId}:{},...n.runId?{runId:n.runId}:{},timestamp:Date.now()})}createMetadataPayload(){return{hookId:this.options.hookId,hookName:this.options.metadata.hookName,...this.options.metadata.name?{displayName:this.options.metadata.name}:{},...this.options.metadata.outputKind?{outputKind:this.options.metadata.outputKind}:{},...this.options.metadata.framework?{framework:this.options.metadata.framework}:{}}}},gf=class extends pf{events;chatOptions;currentRunId=null;currentRunThreadId=null;currentStreamId=null;lastStreamId=null;lastRunEventContext;lastMemoryStateValue=null;lastCompactionEvents=[];lastSkillsStateValue=null;constructor(e){super(ff(e,{getSnapshot:e.getSnapshot,applyToolFixture:t=>this.applyFixture(t)})),this.chatOptions=e,this.events=new Rf(()=>e.clientId,this)}setCurrentStreamId(e){this.currentStreamId=e,e&&(this.lastStreamId=e)}recordStreamId(e){e&&(this.lastStreamId=e)}mountWithTools(e){this.events.clientCreated(e),this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot()}notifyToolsChanged(){this.emitToolsRegistered(),this.emitSnapshot()}getCurrentStreamId(){return this.currentStreamId}getLastStreamId(){return this.lastStreamId}resolveStreamId(){return this.currentStreamId??this.lastStreamId??this.chatOptions.generateId("stream")}beginRun(e,t){this.currentRunId=e,this.currentRunThreadId=t,this.lastRunEventContext={runId:e,threadId:t}}observeChunk(e){if(e.type==="RUN_STARTED"){this.beginRun(e.runId,e.threadId);return}if(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR"){const t=(e.type==="RUN_FINISHED",e.runId);if(!t||t===this.currentRunId){const n=this.getCurrentRunEventContext();n&&(this.lastRunEventContext=n),this.currentRunId=null,this.currentRunThreadId=null}}}recordMemoryState(e){this.lastMemoryStateValue=e,this.emitMemoryState(e)}recordSkillsState(e){this.lastSkillsStateValue=e,this.emitSkillsState(e)}emitMemoryState(e){if(!e||typeof e!="object")return;const t=e,n=t.scope,s=t.adapter;if(!n||typeof s!="string")return;const r=this.currentRunId?{runId:this.currentRunId}:{};X("memory:retrieve:started",{...this.createEnvelope("memory:retrieve:started","client-state",r),scope:n,adapter:s,query:t.query??""}),t.recall&&X("memory:retrieve:completed",{...this.createEnvelope("memory:retrieve:completed","client-state",r),scope:n,adapter:s,fragmentCount:t.recall.fragmentCount??0,hasTools:!!t.recall.hasTools,systemPromptChars:t.recall.systemPromptChars??0,durationMs:t.recall.durationMs??0}),t.snapshot&&X("memory:snapshot",{...this.createEnvelope("memory:snapshot","client-state",r),scope:n,adapter:s,takenAt:t.snapshot.takenAt,data:t.snapshot.data,facts:t.snapshot.facts??[]})}recordCompactionEvent(e,t){this.lastCompactionEvents.push({eventType:e,value:t}),this.lastCompactionEvents.length>60&&this.lastCompactionEvents.splice(0,this.lastCompactionEvents.length-60),this.emitCompactionEvent(e,t)}recordCompactionState(e){this.recordCompactionEvent("compaction:state",e)}emitCompactionEvent(e,t){const n=this.currentRunId?{runId:this.currentRunId}:{};if(e==="compaction:started"){const s=yi(t);X("compaction:started",{...this.createEnvelope("compaction:started","client-state",n),...s});return}if(e==="compaction:ended"){const s=yi(t);X("compaction:ended",{...this.createEnvelope("compaction:ended","client-state",n),...s});return}if(e==="compaction:state"){const s=hf(t);if(!s)return;X("compaction:state",{...this.createEnvelope("compaction:state","client-state",n),...s})}}emitSkillsState(e){if(!e||typeof e!="object")return;const t=e,n=Array.isArray(t.catalog)?t.catalog:[],s=Array.isArray(t.activated)?t.activated:[],r=this.currentRunId?{runId:this.currentRunId}:{};X("skills:snapshot",{...this.createEnvelope("skills:snapshot","client-state",r),catalog:n,activated:s})}onReplayState(){this.lastMemoryStateValue!=null&&this.emitMemoryState(this.lastMemoryStateValue);for(const e of this.lastCompactionEvents)this.emitCompactionEvent(e.eventType,e.value);this.lastSkillsStateValue!=null&&this.emitSkillsState(this.lastSkillsStateValue)}getCurrentRunEventContext(){if(this.currentRunId)return{threadId:this.currentRunThreadId??this.chatOptions.threadId??"",runId:this.currentRunId}}getCurrentOrLastRunEventContext(){return this.getCurrentRunEventContext()??this.lastRunEventContext}findToolCallContext(e){const t={toolCallId:e},n=this.getCurrentRunEventContext();return n?{threadId:n.threadId,runId:n.runId,toolCallId:e}:this.chatOptions.threadId?{threadId:this.chatOptions.threadId,toolCallId:e}:t}async applyFixture(e){const t=this.chatOptions.getMessages(),n=e.threadId??this.chatOptions.threadId??"";if(e.execute){await this.executeFixture(e,t,n);return}const{message:s,toolCallId:r}=this.createReplayMessageFromFixture(e,t),i=s.id;this.events.messageAppended(s,void 0,{threadId:n,toolCallId:r,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,s]),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:n,...e.runId?{runId:e.runId}:{},toolName:e.toolName,input:e.input,output:e.output,messageId:i,toolCallId:r,...e.execute!==void 0?{execute:e.execute}:{},...e.message?{message:e.message}:{},...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}async executeFixture(e,t,n){const s=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i={id:r,role:"assistant",parts:[{type:"tool-call",id:s,name:e.toolName,arguments:Hn(e.input),input:e.input,state:"input-complete"}],createdAt:new Date};this.events.messageAppended(i,void 0,{threadId:n,toolCallId:s,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,i]),this.emitSnapshot();const o=this.findClientTool(e.toolName)?.execute;if(!o){console.warn(`[ai-devtools] tool fixture "${e.toolName}" requested execute=true but no client tool implementation is registered; replaying saved output instead.`),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:s,threadId:n,output:e.output,errorText:e.errorText});return}let a;try{a=await o(e.input)}catch(l){console.error(`[ai-devtools] tool fixture "${e.toolName}" execute threw`,l),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:s,threadId:n,output:null,errorText:l instanceof Error?`${l.name}: ${l.message}`:`Tool execution failed: ${String(l)}`});return}this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:s,threadId:n,output:a})}addToolResultForFixture(e){const t=e.errorText?"output-error":"output-available";this.events.toolResultAdded(e.toolCallId,e.fixture.toolName,e.output,t,{threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolCallId:e.toolCallId}),this.chatOptions.addToolResult(e.toolCallId,e.output,e.errorText),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolName:e.fixture.toolName,input:e.fixture.input,output:e.output,execute:!0,messageId:e.messageId,toolCallId:e.toolCallId,...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}createReplayMessageFromFixture(e,t){const n=this.cloneFixtureSourceMessage(e,t);if(n)return n;const s=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i=e.errorText?"error":"complete";return{toolCallId:s,message:{id:r,role:"assistant",parts:[{type:"tool-call",id:s,name:e.toolName,arguments:Hn(e.input),input:e.input,state:"input-complete",output:e.output},{type:"tool-result",toolCallId:s,content:Hn(e.output),state:i,...e.errorText?{error:e.errorText}:{}}],createdAt:new Date}}}cloneFixtureSourceMessage(e,t){const n=e.message;if(!n||!Array.isArray(n.parts))return;const s=this.createFixtureToolCallIdMap(n.parts,t),r=n.parts.map(a=>vf(a,s)).filter(a=>!!a),i=e.toolCallId?s.get(e.toolCallId):void 0;if(yf(r,{...i?{mappedToolCallId:i}:{},output:e.output}),r.length===0)return;const o=(e.toolCallId?s.get(e.toolCallId):void 0)??Sf(r);if(o)return{toolCallId:o,message:{id:this.resolveFixtureMessageId(n.id,t),role:n.role,parts:r,createdAt:new Date}}}createFixtureToolCallIdMap(e,t){const n=new Map;for(const s of e)!aa(s)||s.type!=="tool-call"||typeof s.id=="string"&&n.set(s.id,this.resolveFixtureToolCallId(s.id,t));return n}resolveFixtureMessageId(e,t){return e&&!t.some(n=>n.id===e)?e:this.chatOptions.generateId("fixture-msg")}resolveFixtureToolCallId(e,t){return e&&!If(t,e)?e:this.chatOptions.generateId("fixture-tool-call")}findClientTool(e){const t=this.chatOptions.getTools?.();if(t){for(const n of t)if(n.name===e)return n}}};function aa(e){return typeof e=="object"&&e!==null}function Hn(e){if(typeof e=="string")return e;if(e===void 0||typeof e=="function"||typeof e=="symbol")return String(e);try{return JSON.stringify(e)}catch(t){return console.error("[ai-devtools] failed to JSON.stringify fixture value; falling back to String(). Tool call arguments may be malformed.",{error:t,value:e}),String(e)}}function mf(e){try{return JSON.parse(e)}catch(t){return console.error("[ai-devtools] failed to JSON.parse fixture result content; replaying as raw string. Fixture payload may be corrupted.",{error:t,content:e}),e}}function vf(e,t){if(!aa(e)||typeof e.type!="string")return;const n={...e};return e.type==="tool-call"&&typeof e.id=="string"&&(n.id=t.get(e.id)??e.id),e.type==="tool-result"&&typeof e.toolCallId=="string"&&(n.toolCallId=t.get(e.toolCallId)??e.toolCallId),n}function Sf(e){const t=e.find(n=>n.type==="tool-call");return t?.type==="tool-call"?t.id:void 0}function yf(e,t){for(const n of e){if(n.type!=="tool-result")continue;const s=e.find(r=>r.type==="tool-call"&&r.id===n.toolCallId&&r.output===void 0);s&&(s.output=Array.isArray(n.content)?n.content:mf(n.content))}if(t.mappedToolCallId&&t.output!==void 0){const n=e.find(s=>s.type==="tool-call"&&s.id===t.mappedToolCallId&&s.output===void 0);n&&(n.output=t.output)}}function If(e,t){return e.some(n=>n.parts.some(s=>s.type==="tool-call"?s.id===t:s.type==="tool-result"?s.toolCallId===t:!1))}var Rf=class extends Wh{getClientId;helper;constructor(e,t){super(e()),this.getClientId=e,this.helper=t}emitEvent(e,t){this.clientId=this.getClientId(),super.emitEvent(e,t)}afterEmit(e){e&&this.helper.recordStreamId(e),this.helper.emitSnapshot()}textUpdated(e,t,n,s){super.textUpdated(e,t,n,s??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}thinkingUpdated(e,t,n,s,r){super.thinkingUpdated(e,t,n,s,r??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}messageAppended(e,t,n){super.messageAppended(e,t,n??this.helper.getCurrentRunEventContext()),this.afterEmit(t)}toolCallStateChanged(e,t,n,s,r,i,o){super.toolCallStateChanged(e,t,n,s,r,i,o??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}structuredOutputChanged(e,t,n,s,r){super.structuredOutputChanged(e,t,n,s,r??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(t)}approvalRequested(e,t,n,s,r,i,o){super.approvalRequested(e,t,n,s,r,i,o??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(e)}toolResultAdded(e,t,n,s,r){super.toolResultAdded(e,t,n,s,r??this.helper.getCurrentRunEventContext()),this.afterEmit()}toolApprovalResponded(e,t,n,s){super.toolApprovalResponded(e,t,n,s??this.helper.getCurrentRunEventContext()),this.afterEmit()}clientCreated(e){super.clientCreated(e),this.afterEmit()}loadingChanged(e){super.loadingChanged(e),this.afterEmit()}errorChanged(e){super.errorChanged(e),this.afterEmit()}reloaded(e){super.reloaded(e),this.afterEmit()}stopped(){super.stopped(),this.afterEmit()}messagesCleared(){super.messagesCleared(),this.afterEmit()}messageSent(e,t){super.messageSent(e,t),this.afterEmit()}toolFixtureApplied(e){super.toolFixtureApplied(e),this.afterEmit()}};function Cf(e){return new gf(e)}var Ci=Object.freeze([]),bf=Object.freeze([]);function Wf(e){const t=(0,I.useId)(),n=e.threadId??t,[s,r]=(0,I.useState)(e.initialMessages||[]),[i,o]=(0,I.useState)(!1),[a,l]=(0,I.useState)(void 0),[u,c]=(0,I.useState)("ready"),[h,d]=(0,I.useState)(!1),[f,p]=(0,I.useState)("disconnected"),[g,m]=(0,I.useState)(!1),[v,S]=(0,I.useState)([]),[C,b]=(0,I.useState)(null),[w,R]=(0,I.useState)(()=>({interrupts:Ci,pendingInterrupts:Ci,interruptErrors:bf,resuming:!1})),y=(0,I.useRef)(e.initialMessages||[]),_=(0,I.useRef)(!0),O=(0,I.useRef)(!1),T=(0,I.useRef)(null),M=(0,I.useRef)(null),A=(0,I.useRef)(null);y.current=s;const x=(0,I.useRef)(e);x.current=e;const P=(0,I.useCallback)(j=>{j&&(b(j.getCurrentRunId()),R(j.getInterruptState()))},[]),{client:E,initialization:G}=(0,I.useMemo)(()=>{const j=e.initialMessages||[];_.current=!1;const N=x.current,Ve=N.connection?{connection:N.connection}:{fetcher:N.fetcher},qe={current:void 0},Mt=()=>{const D=qe.current;if(!(!D||T.current!==D))return D},In={ready:!1,callbacks:[]},V=D=>{if(!In.ready){In.callbacks.push(D);return}const ne=qe.current;!ne||T.current!==ne||D()},Ks=new df({devtoolsBridgeFactory:Cf,...Ve,initialMessages:j,...typeof N.threadId=="string"&&N.persistence?{persistence:N.persistence,threadId:N.threadId}:{...N.threadId!==void 0&&{threadId:N.threadId}},...N.body!==void 0&&{body:N.body},...N.forwardedProps!==void 0&&{forwardedProps:N.forwardedProps},...N.byok!==void 0&&{byok:N.byok},byokProvider:()=>x.current.byokProvider?.(),...N.initialResumeSnapshot!==void 0&&{initialResumeSnapshot:N.initialResumeSnapshot},...N.context!==void 0&&{context:N.context},devtools:{...N.devtools,framework:"react",hookName:"useChat",outputKind:N.outputSchema?"structured":"chat"},onResponse:D=>{if(Mt())return x.current.onResponse?.(D)},onChunk:D=>{V(()=>{x.current.onChunk?.(D)})},onFinish:D=>{V(()=>{x.current.onFinish?.(D)})},onError:D=>{V(()=>{x.current.onError?.(D)})},...N.tools!==void 0&&{tools:N.tools},...N.interrupts!==void 0&&{interrupts:N.interrupts},onCustomEvent:(D,ne,Rn)=>{V(()=>{x.current.onCustomEvent?.(D,ne,Rn)})},...e.streamProcessor!==void 0&&{streamProcessor:e.streamProcessor},onMessagesChange:D=>{V(()=>{r(D)})},onLoadingChange:D=>{V(()=>{const ne=Mt();ne&&(o(D),P(ne))})},onErrorChange:D=>{V(()=>{l(D)})},onStatusChange:D=>{V(()=>{c(D)})},onSubscriptionChange:D=>{V(()=>{d(D)})},onConnectionStatusChange:D=>{V(()=>{p(D)})},onSessionGeneratingChange:D=>{V(()=>{m(D)})},...x.current.queue!==void 0&&{queue:x.current.queue},onQueueChange:D=>{V(()=>{S(D)})},onRunIdChange:D=>{V(()=>{b(D)})},onResumeStateChange:(D,ne)=>{V(()=>{R(Rn=>({...Rn,interrupts:ne,pendingInterrupts:ne}))})},onInterruptStateChange:(D,ne)=>{V(()=>{R(D),x.current.onInterruptStateChange?.(D,ne)})}});return qe.current=Ks,{client:Ks,initialization:In}},[n,P]);(0,I.useEffect)(()=>{T.current=E;try{for(;G.callbacks.length>0;){if(T.current!==E){G.callbacks.length=0;break}G.callbacks.shift()?.()}}finally{G.ready=!0}},[E,G]),(0,I.useEffect)(()=>{const j=E.getMessages();j!==y.current&&r(j)},[E]),(0,I.useEffect)(()=>{E.updateOptions({body:e.body})},[E,e.body]),(0,I.useEffect)(()=>{e.forwardedProps!==void 0&&E.updateOptions({forwardedProps:e.forwardedProps})},[E,e.forwardedProps]),(0,I.useEffect)(()=>{e.tools!==void 0&&E.updateOptions({tools:e.tools})},[E,e.tools]),(0,I.useEffect)(()=>{E.updateOptions({context:e.context})},[E,e.context]),(0,I.useEffect)(()=>{e.queue!==void 0&&E.updateOptions({queue:e.queue})},[E,e.queue]),(0,I.useEffect)(()=>{e.live?(E.subscribe(),O.current=!0):O.current&&(E.unsubscribe(),O.current=!1)},[E,e.live]),(0,I.useEffect)(()=>(E.attach(),()=>{E.detach()}),[E]),(0,I.useEffect)(()=>(A.current?.client===E&&(clearTimeout(A.current.timeout),A.current=null),M.current&&(clearTimeout(M.current),M.current=null),E.mountDevtools(),P(E),()=>{M.current=setTimeout(()=>{T.current===E&&(T.current=null),M.current=null},0);const j={client:E,timeout:setTimeout(()=>{x.current.live?E.unsubscribe():E.stop(),E.dispose(),A.current===j&&(A.current=null)},0)};A.current=j}),[E,P]);const st=(0,I.useCallback)(async(j,N)=>{try{await E.sendMessage(j,void 0,N)}finally{P(E)}},[E,P]),rt=(0,I.useCallback)(j=>{E.cancelQueued(j)},[E,P]),_t=(0,I.useCallback)(async j=>{try{await E.append(j)}finally{P(E)}},[E,P]),fe=(0,I.useCallback)(async()=>{try{await E.reload()}finally{P(E)}},[E,P]),it=(0,I.useCallback)(()=>{E.stop()},[E]),He=(0,I.useCallback)(()=>{E.clear(),P(E)},[E,P]),ee=(0,I.useCallback)(j=>{E.setMessagesManually(j)},[E]),Sn=(0,I.useCallback)(async j=>{await E.addToolResult(j)},[E]),yn=(0,I.useCallback)(async j=>{await E.addToolApprovalResponse(j),P(E)},[E,P]),Tt=(0,I.useCallback)(async(j,N)=>{const Ve=await E.resumeInterrupts(j,N??void 0);return P(E),Ve},[E,P]),$=(0,I.useCallback)(j=>{E.resolveInterrupts(j)},[E]),te=(0,I.useCallback)(()=>{E.cancelInterrupts()},[E]),At=(0,I.useCallback)(()=>{E.retryInterrupts()},[E]),ot=(0,I.useCallback)((j,N)=>E.resumeInterruptsUnsafe(j,N),[E]),ze=E.getMessages(),Ie=(0,I.useMemo)(()=>{let j=-1;for(let N=ze.length-1;N>=0;N--)if(ze[N]?.role==="user"){j=N;break}if(j===-1)return null;for(let N=ze.length-1;N>j;N--){const Ve=ze[N];if(Ve?.role!=="assistant")continue;const qe=Ve.parts.find(Mt=>Mt.type==="structured-output");if(qe)return qe}return null},[ze]),la=(0,I.useMemo)(()=>Ie?Ie.partial??Ie.data??{}:{},[Ie]),ua=(0,I.useMemo)(()=>!Ie||Ie.status!=="complete"?null:Ie.data,[Ie]);return{messages:ze,sendMessage:st,append:_t,reload:fe,stop:it,isLoading:i,error:a,status:u,isSubscribed:h,connectionStatus:f,sessionGenerating:g,setMessages:ee,clear:He,addToolResult:Sn,addToolApprovalResponse:yn,queue:v,cancelQueued:rt,runId:C,interrupts:w.interrupts,pendingInterrupts:w.pendingInterrupts,interruptErrors:w.interruptErrors,resuming:w.resuming,resolveInterrupts:$,cancelInterrupts:te,retryInterrupts:At,resumeInterruptsUnsafe:ot,resumeInterrupts:Tt,partial:la,final:ua}}function Jf(e){return(0,I.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>qc)}var Xf=new Uint8Array(128).fill(128);export{kf as C,Li as D,Mf as E,Af as O,po as S,xf as T,Nf as _,Uc as a,Ff as b,Vf as c,Bf as d,$f as f,Df as g,ku as h,Kf as i,Tf as k,Uf as l,jf as m,Wf as n,qf as o,Gf as p,Qf as r,zf as s,Jf as t,Hf as u,Lf as v,Pf as w,js as x,So as y};
|