db-studio 1.14.0 → 1.14.2

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.
Files changed (53) hide show
  1. package/dist/index.js +2 -2
  2. package/dist/index.js.map +1 -1
  3. package/dist/web-dist/assets/_pathlessLayout-BHGufnSc.js +1 -0
  4. package/dist/web-dist/assets/{_pathlessLayout-wBh7gK9q.js → _pathlessLayout-yNuiTElQ.js} +6 -6
  5. package/dist/web-dist/assets/{_queryId-CZGDd4fs.js → _queryId-LnHerkD-.js} +1 -1
  6. package/dist/web-dist/assets/{_table-j-6h6Om5.js → _table-BIRl7wsf.js} +1 -1
  7. package/dist/web-dist/assets/{_table-DZOIq7aF.js → _table-DKdWkgl_.js} +1 -1
  8. package/dist/web-dist/assets/{badge-DiSuKlwP.js → badge-D_Kx6BmG.js} +1 -1
  9. package/dist/web-dist/assets/{browser-DdWTHJJW.js → browser-LLDBA7Jr.js} +1 -1
  10. package/dist/web-dist/assets/{bundle-mjs-5mNXw8Uh.js → bundle-mjs-DVXBR05F.js} +1 -1
  11. package/dist/web-dist/assets/code-editor-BpkXdVns.js +9 -0
  12. package/dist/web-dist/assets/{database.store-DzuxpP71.js → database.store-Djdh7lNO.js} +1 -1
  13. package/dist/web-dist/assets/{dist-Bcrd0PtF.js → dist-C-SdF-L-.js} +1 -1
  14. package/dist/web-dist/assets/{format-cell-value-lejp1lDf.js → format-cell-value-BtrAFpQa.js} +1 -1
  15. package/dist/web-dist/assets/{highlighted-body-OFNGDK62-Cb34z6at.js → highlighted-body-OFNGDK62-D860IMcy.js} +1 -1
  16. package/dist/web-dist/assets/{icons-D6bNpzOL.js → icons-De4HOb_l.js} +1 -1
  17. package/dist/web-dist/assets/index-DGaShyKg.css +2 -0
  18. package/dist/web-dist/assets/index-DUbs819O.js +36 -0
  19. package/dist/web-dist/assets/indexes-Cp3DqRz7.js +1 -0
  20. package/dist/web-dist/assets/logs-BiM3MAXO.js +1 -0
  21. package/dist/web-dist/assets/{mermaid-GHXKKRXX-B5pqoNgJ.js → mermaid-GHXKKRXX-DQBwS7h_.js} +1 -1
  22. package/dist/web-dist/assets/{middleware-CYbbS--7.js → middleware-BbNmPIW8.js} +1 -1
  23. package/dist/web-dist/assets/{monaco-editor-C-DV5CL8.js → monaco-editor-CNMPKLoW.js} +280 -280
  24. package/dist/web-dist/assets/monaco-editor-IL9D_L0g.css +1 -0
  25. package/dist/web-dist/assets/{monitoring-DWzrlTkx.js → monitoring-Bv8YDvqU.js} +1 -1
  26. package/dist/web-dist/assets/{overlay.store-TOgdd28d.js → overlay.store-Cni3_SHg.js} +1 -1
  27. package/dist/web-dist/assets/{queries.store-Cul86O-l.js → queries.store-Z6EhVY9R.js} +1 -1
  28. package/dist/web-dist/assets/{query-runner-BhGrHn5P.js → query-runner-CRfNq31h.js} +5 -5
  29. package/dist/web-dist/assets/{radix-ui-CtzftI1z.js → radix-ui-Bk380HgZ.js} +1 -1
  30. package/dist/web-dist/assets/{react-B3nJmLdO.js → react-CfXK6joe.js} +1 -1
  31. package/dist/web-dist/assets/{react-dom-DOIt489g.js → react-dom-Y-FhvvJI.js} +1 -1
  32. package/dist/web-dist/assets/{redis-value-B1T4ApeG.js → redis-value-dNWQPX9M.js} +1 -1
  33. package/dist/web-dist/assets/{rolldown-runtime-D2WZefnn.js → rolldown-runtime-BGAbM2vM.js} +1 -1
  34. package/dist/web-dist/assets/{runner-BI316iCf.js → runner-CT8TXCWe.js} +1 -1
  35. package/dist/web-dist/assets/schema--myTsN4I.js +1 -0
  36. package/dist/web-dist/assets/schema-Cd61GWLb.js +57 -0
  37. package/dist/web-dist/assets/table-DznwPkbx.js +1 -0
  38. package/dist/web-dist/assets/tanstack-CJCyKnhp.js +11 -0
  39. package/dist/web-dist/assets/visualizer-CsHwq2yx.js +1 -0
  40. package/dist/web-dist/index.html +19 -19
  41. package/package.json +2 -2
  42. package/dist/web-dist/assets/_pathlessLayout-BXxEoaJK.js +0 -1
  43. package/dist/web-dist/assets/code-editor-BXm3myTR.js +0 -9
  44. package/dist/web-dist/assets/index-B_H1M603.js +0 -36
  45. package/dist/web-dist/assets/index-DHb8byer.css +0 -2
  46. package/dist/web-dist/assets/indexes-DecPH1pX.js +0 -1
  47. package/dist/web-dist/assets/logs-CXbJheYV.js +0 -1
  48. package/dist/web-dist/assets/monaco-editor-DcHpHuJd.css +0 -1
  49. package/dist/web-dist/assets/schema-CwD_s_ox.js +0 -64
  50. package/dist/web-dist/assets/schema-D9V1P9K2.js +0 -1
  51. package/dist/web-dist/assets/table-DbvYpea0.js +0 -1
  52. package/dist/web-dist/assets/tanstack-DQKs7SF9.js +0 -11
  53. package/dist/web-dist/assets/visualizer-7aPZoUCc.js +0 -1
@@ -0,0 +1,11 @@
1
+ import{r as Ei,t as tt}from"./rolldown-runtime-BGAbM2vM.js";import{xt as Cn}from"./icons-De4HOb_l.js";import{Ot as ha,kt as fa}from"./radix-ui-Bk380HgZ.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.2"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a55f6f96-3768-43bc-90cd-676bed02f1f1",e._sentryDebugIdIdentifier="sentry-dbid-a55f6f96-3768-43bc-90cd-676bed02f1f1")}catch{}})();var st=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(){}},pa=class extends st{#t;#e;#s;constructor(){super(),this.#s=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.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#s=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"}},bn=new pa,ga={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ma=class{#t=ga;#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 ma;function va(e){setTimeout(e,0)}var Sa=typeof window>"u"||"Deno"in globalThis;function q(){}function ya(e,t){return typeof e=="function"?e(t):e}function Hs(e){return typeof e=="number"&&e>=0&&e!==1/0}function _i(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 Wn(e,t){const{type:s="all",exact:n,fetchStatus:r,predicate:i,queryKey:o,stale:a}=e;if(o){if(n){if(t.queryHash!==wn(o,t.options))return!1}else if(!vt(t.queryKey,o))return!1}if(s!=="all"){const u=t.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||r&&r!==t.state.fetchStatus||i&&!i(t))}function Jn(e,t){const{exact:s,status:n,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(s){if(De(t.options.mutationKey)!==De(i))return!1}else if(!vt(t.options.mutationKey,i))return!1}return!(n&&t.state.status!==n||r&&!r(t))}function wn(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,s)=>zs(s)?Object.keys(s).sort().reduce((n,r)=>(n[r]=s[r],n),{}):s)}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(s=>vt(e[s],t[s])):!1}var Ia=Object.prototype.hasOwnProperty;function Ti(e,t,s=0){if(e===t)return e;if(s>500)return t;const n=Xn(e)&&Xn(t);if(!n&&!(zs(e)&&zs(t)))return t;const r=(n?e:Object.keys(e)).length,i=n?t:Object.keys(t),o=i.length,a=n?new Array(o):{};let u=0;for(let l=0;l<o;l++){const c=n?l:i[l],h=e[c],d=t[c];if(h===d){a[c]=h,(n?l<r:Ia.call(e,c))&&u++;continue}if(h===null||d===null||typeof h!="object"||typeof d!="object"){a[c]=d;continue}const f=Ti(h,d,s+1);a[c]=f,f===h&&u++}return r===o&&u===r?e:a}function Yt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function Xn(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function zs(e){if(!Yn(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!Yn(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Yn(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ra(e){return new Promise(t=>{ke.setTimeout(t,e)})}function Vs(e,t,s){return typeof s.structuralSharing=="function"?s.structuralSharing(e,t):s.structuralSharing!==!1?Ti(e,t):t}function Ca(e,t,s=0){const n=[...e,t];return s&&n.length>s?n.slice(1):n}function ba(e,t,s=0){const n=[t,...e];return s&&n.length>s?n.slice(0,-1):n}var En=Symbol();function Mi(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===En?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function _n(e,t){return typeof e=="function"?e(...t):!!e}function wa(e,t,s){let n=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),n||(n=!0,r.aborted?s():r.addEventListener("abort",s,{once:!0})),r)}),e}var St=(()=>{let e=()=>Sa;return{isServer(){return e()},setIsServer(t){e=t}}})();function qs(){let e,t;const s=new Promise((r,i)=>{e=r,t=i});s.status="pending",s.catch(()=>{});function n(r){Object.assign(s,r),delete s.resolve,delete s.reject}return s.resolve=r=>{n({status:"fulfilled",value:r}),e(r)},s.reject=r=>{n({status:"rejected",reason:r}),t(r)},s}function Pf(e){return e.state.status==="success"}var Ea=va;function _a(){let e=[],t=0,s=a=>{a()},n=a=>{a()},r=Ea;const i=a=>{t?e.push(a):r(()=>{s(a)})},o=()=>{const a=e;e=[],a.length&&r(()=>{n(()=>{a.forEach(u=>{s(u)})})})};return{batch:a=>{let u;t++;try{u=a()}finally{t--,t||o()}return u},batchCalls:a=>(...u)=>{i(()=>{a(...u)})},schedule:i,setNotifyFunction:a=>{s=a},setBatchNotifyFunction:a=>{n=a},setScheduler:a=>{r=a}}}var H=_a(),Ta=class extends st{#t=!0;#e;#s;constructor(){super(),this.#s=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#s=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 Ta;function Ma(e){return Math.min(1e3*2**e,3e4)}function Ai(e){return(e??"online")==="online"?Zt.isOnline():!0}var Ks=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Oi(e){let t=!1,s=0,n;const r=qs(),i=()=>r.status!=="pending",o=g=>{if(!i()){const v=new Ks(g);d(v),e.onCancel?.(v)}},a=()=>{t=!0},u=()=>{t=!1},l=()=>bn.isFocused()&&(e.networkMode==="always"||Zt.isOnline())&&e.canRun(),c=()=>Ai(e.networkMode)&&e.canRun(),h=g=>{i()||(n?.(),r.resolve(g))},d=g=>{i()||(n?.(),r.reject(g))},f=()=>new Promise(g=>{n=v=>{(i()||l())&&g(v)},e.onPause?.()}).then(()=>{n=void 0,i()||e.onContinue?.()}),p=()=>{if(i())return;let g;const v=s===0?e.initialPromise:void 0;try{g=v??e.fn()}catch(m){g=Promise.reject(m)}Promise.resolve(g).then(h).catch(m=>{if(i())return;const S=e.retry??(St.isServer()?0:3),C=e.retryDelay??Ma,b=typeof C=="function"?C(s,m):C,w=S===!0||typeof S=="number"&&s<S||typeof S=="function"&&S(s,m);if(t||!w){d(m);return}s++,e.onFail?.(s,m),Ra(b).then(()=>l()?void 0:f()).then(()=>{t?d(m):p()})})};return{promise:r,status:()=>r.status,cancel:o,continue:()=>(n?.(),r),cancelRetry:a,continueRetry:u,canStart:c,start:()=>(c()?p():f().then(p),r)}}var xi=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Hs(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 Aa(e){return{onFetch:(t,s)=>{const n=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},u=0;const l=async()=>{let c=!1;const h=p=>{wa(p,()=>t.signal,()=>c=!0)},d=Mi(t.options,t.fetchOptions),f=async(p,g,v)=>{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:v?"backward":"forward",meta:t.options.meta};return h(R),R})(),C=await d(S),{maxPages:b}=t.options,w=v?ba:Ca;return{pages:w(p.pages,C,b),pageParams:w(p.pageParams,g,b)}};if(r&&i.length){const p=r==="backward",g=p?Pi:Qs,v={pages:i,pageParams:o};a=await f(v,g(n,v),p)}else{const p=e??i.length;do{const g=u===0?o[0]??n.initialPageParam:Qs(n,a);if(u>0&&g==null)break;a=await f(a,g),u++}while(u<p)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=l}}}function Qs(e,{pages:t,pageParams:s}){const n=t.length-1;return t.length>0?e.getNextPageParam(t[n],t,s[n],s):void 0}function Pi(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}function Oa(e,t){return t?Qs(e,t)!=null:!1}function xa(e,t){return!t||!e.getPreviousPageParam?!1:Pi(e,t)!=null}var Pa=class extends xi{#t;#e;#s;#n;#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.#n=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=er(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=er(this.options);t.data!==void 0&&(this.setState(Zn(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const s=Vs(this.state.data,e,this.options);return this.#o({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}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===En||!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:!_i(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.#n.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.#n.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(u=>u.options.queryFn);a&&this.setOptions(a.options)}const s=new AbortController,n=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(this.#l=!0,s.signal)})},r=()=>{const a=Mi(this.options,t),l=(()=>{const c={client:this.#i,queryKey:this.queryKey,meta:this.meta};return n(c),c})();return this.#l=!1,this.options.persister?this.options.persister(a,l,this):a(l)},o=(()=>{const a={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:r};return n(a),a})();(this.#t==="infinite"?Aa(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#o({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=Oi({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:a=>{a instanceof Ks&&a.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},onFail:(a,u)=>{this.#o({type:"failed",failureCount:a,error:u})},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.#n.config.onSuccess?.(a,this),this.#n.config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof Ks){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.#n.config.onError?.(a,this),this.#n.config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}#o(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...ki(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...Zn(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=e.manual?n:void 0,n;case"error":const r=e.error;return{...s,error:r,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),H.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function ki(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ai(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Zn(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function er(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,n=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var Fi=class extends st{constructor(e,t){super(),this.options=t,this.#t=e,this.#l=null,this.#a=qs(),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#s=void 0;#n=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),tr(this.#e,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ws(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ws(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,s=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 n=this.hasListeners();n&&sr(this.#e,s,this.options,t)&&this.#m(),this.updateResult(),n&&(this.#e!==s||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();n&&(this.#e!==s||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),s=this.createResult(t,e);return Fa(this,s)&&(this.#n=s,this.#r=this.options,this.#i=this.#e.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,n)=>(this.trackProp(n),t?.(n),n==="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(s,n))})}trackProp(e){this.#g.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),s=this.#t.getQueryCache().build(this.#t,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#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.#n.isStale||!Hs(e))return;const t=_i(this.#n.dataUpdatedAt,e)+1;this.#f=ke.setTimeout(()=>{this.#n.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||!Hs(this.#p)||this.#p===0)&&(this.#d=ke.setInterval(()=>{(this.options.refetchIntervalInBackground||bn.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 s=this.#e,n=this.options,r=this.#n,i=this.#i,o=this.#r,a=e!==s?e.state:this.#s,{state:u}=e;let l={...u},c=!1,h;if(t._optimisticResults){const R=this.hasListeners(),y=!R&&tr(e,t),_=R&&sr(e,s,t,n);(y||_)&&(l={...l,...ki(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(l.fetchStatus="idle")}let{error:d,errorUpdatedAt:f,status:p}=l;h=l.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=Vs(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=Vs(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 v=l.fetchStatus==="fetching",m=p==="pending",S=p==="error",C=m&&v,b=h!==void 0,w={status:p,fetchStatus:l.fetchStatus,isPending:m,isSuccess:p==="success",isError:S,isInitialLoading:C,isLoading:C,data:h,dataUpdatedAt:l.dataUpdatedAt,error:d,errorUpdatedAt:f,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>a.dataUpdateCount||l.errorUpdateCount>a.errorUpdateCount,isFetching:v,isRefetching:v&&!m,isLoadingError:S&&!b,isPaused:l.fetchStatus==="paused",isPlaceholderData:c,isRefetchError:S&&b,isStale:Tn(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,_=A=>{y?A.reject(w.error):R&&A.resolve(w.data)},O=()=>{const A=this.#a=w.promise=qs();_(A)},T=this.#a;switch(T.status){case"pending":e.queryHash===s.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.#n,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.#n=t;const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,r=typeof n=="function"?n():n;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.#n).some(o=>{const a=o;return this.#n[a]!==e[a]&&i.has(a)})};this.#b({listeners:s()})}#C(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#s=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.#n)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function ka(e,t){return J(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&J(t.retryOnMount,e)===!1)}function tr(e,t){return ka(e,t)||e.state.data!==void 0&&Ws(e,t,t.refetchOnMount)}function Ws(e,t,s){if(J(t.enabled,e)!==!1&&be(t.staleTime,e)!=="static"){const n=typeof s=="function"?s(e):s;return n==="always"||n!==!1&&Tn(e,t)}return!1}function sr(e,t,s,n){return(e!==t||J(n.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&Tn(e,s)}function Tn(e,t){return J(t.enabled,e)!==!1&&e.isStaleByTime(be(t.staleTime,e))}function Fa(e,t){return!Yt(e.getCurrentResult(),t)}var La=class extends Fi{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:s}=e,n=super.createResult(e,t),{isFetching:r,isRefetching:i,isError:o,isRefetchError:a}=n,u=s.fetchMeta?.fetchMore?.direction,l=o&&u==="forward",c=r&&u==="forward",h=o&&u==="backward",d=r&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Oa(t,s.data),hasPreviousPage:xa(t,s.data),isFetchNextPageError:l,isFetchingNextPage:c,isFetchPreviousPageError:h,isFetchingPreviousPage:d,isRefetchError:a&&!l&&!h,isRefetching:i&&!c&&!d}}},Na=class extends xi{#t;#e;#s;#n;constructor(e){super(),this.#t=e.client,this.mutationId=e.mutationId,this.#s=e.mutationCache,this.#e=[],this.state=e.state||Li(),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.#s.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#i({type:"continue"})},s={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#n=Oi({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):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.#s.canRun(this)});const n=this.state.status==="pending",r=!this.#n.canStart();try{if(n)t();else{this.#i({type:"pending",variables:e,isPaused:r}),this.#s.config.onMutate&&await this.#s.config.onMutate(e,this,s);const o=await this.options.onMutate?.(e,s);o!==this.state.context&&this.#i({type:"pending",context:o,variables:e,isPaused:r})}const i=await this.#n.start();return await this.#s.config.onSuccess?.(i,e,this.state.context,this,s),await this.options.onSuccess?.(i,e,this.state.context,s),await this.#s.config.onSettled?.(i,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(i,null,e,this.state.context,s),this.#i({type:"success",data:i}),i}catch(i){try{await this.#s.config.onError?.(i,e,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(i,e,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,i,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,i,e,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#i({type:"error",error:i}),i}finally{this.#s.runNext(this)}}#i(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,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{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),H.batch(()=>{this.#e.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function Li(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Da=class extends st{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#s=0}#t;#e;#s;build(e,t,s){const n=new Na({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(n),n}add(e){this.#t.add(e);const t=Ot(e);if(typeof t=="string"){const s=this.#e.get(t);s?s.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 s=this.#e.get(t);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Ot(e);if(typeof t=="string"){const s=this.#e.get(t)?.find(n=>n.state.status==="pending");return!s||s===e}else return!0}runNext(e){const t=Ot(e);return typeof t=="string"?this.#e.get(t)?.find(s=>s!==e&&s.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(s=>Jn(t,s))}findAll(e={}){return this.getAll().filter(t=>Jn(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 ja=class extends st{#t;#e=void 0;#s;#n;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.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&De(t.mutationKey)!==De(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#r(e)}getCurrentResult(){return this.#e}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#i(),this.#r()}mutate(e,t){return this.#n=t,this.#s?.removeObserver(this),this.#s=this.#t.getMutationCache().build(this.#t,this.options),this.#s.addObserver(this),this.#s.execute(e)}#i(){const e=this.#s?.state??Li();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.#n&&this.hasListeners()){const t=this.#e.variables,s=this.#e.context,n={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,t,s,n)}catch(r){Promise.reject(r)}try{this.#n.onSettled?.(e.data,null,t,s,n)}catch(r){Promise.reject(r)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,t,s,n)}catch(r){Promise.reject(r)}try{this.#n.onSettled?.(void 0,e.error,t,s,n)}catch(r){Promise.reject(r)}}}this.listeners.forEach(t=>{t(this.#e)})})}},Ga=class extends st{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,s){const n=t.queryKey,r=t.queryHash??wn(n,t);let i=this.get(r);return i||(i=new Pa({client:e,queryKey:n,queryHash:r,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(n)}),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(s=>Wn(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Wn(e,s)):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()})})}},kf=class{#t;#e;#s;#n;#i;#r;#a;#l;constructor(e={}){this.#t=e.queryCache||new Ga,this.#e=e.mutationCache||new Da,this.#s=e.defaultOptions||{},this.#n=new Map,this.#i=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#a=bn.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),s=this.#t.build(this,t),n=s.state.data;return n===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(be(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:s})=>[t,s.data])}setQueryData(e,t,s){const n=this.defaultQueryOptions({queryKey:e}),r=this.#t.get(n.queryHash)?.state.data,i=ya(t,r);if(i!==void 0)return this.#t.build(this,n).setData(i,{...s,manual:!0})}setQueriesData(e,t,s){return H.batch(()=>this.#t.findAll(e).map(({queryKey:n})=>[n,this.setQueryData(n,t,s)]))}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(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#t;return H.batch(()=>(s.findAll(e).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},n=H.batch(()=>this.#t.findAll(e).map(r=>r.cancel(s)));return Promise.all(n).then(q).catch(q)}invalidateQueries(e,t={}){return H.batch(()=>(this.#t.findAll(e).forEach(s=>{s.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},n=H.batch(()=>this.#t.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,s);return s.throwOnError||(i=i.catch(q)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(n).then(q)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#t.build(this,t);return s.isStaleByTime(be(t.staleTime,s))?s.fetch(t):Promise.resolve(s.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.#s}setDefaultOptions(e){this.#s=e}setQueryDefaults(e,t){this.#n.set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(n=>{vt(e,n.queryKey)&&Object.assign(s,n.defaultOptions)}),s}setMutationDefaults(e,t){this.#i.set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#i.values()],s={};return t.forEach(n=>{vt(e,n.mutationKey)&&Object.assign(s,n.defaultOptions)}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#s.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=wn(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===En&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#s.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},I=Ei(Cn(),1),L=fa(),Ni=I.createContext(void 0),Di=e=>{const t=I.useContext(Ni);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Ff=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,L.jsx)(Ni.Provider,{value:e,children:t})),ji=I.createContext(!1),$a=()=>I.useContext(ji),Lf=ji.Provider;function Ba(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ua=I.createContext(Ba()),Ha=()=>I.useContext(Ua),za=(e,t,s)=>{const n=s?.state.error&&typeof e.throwOnError=="function"?_n(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||n)&&(t.isReset()||(e.retryOnMount=!1))},Va=e=>{I.useEffect(()=>{e.clearReset()},[e])},qa=({result:e,errorResetBoundary:t,throwOnError:s,query:n,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&n&&(r&&e.data===void 0||_n(s,[e.error,n])),Ka=e=>{if(e.suspense){const s=r=>r==="static"?r:Math.max(r??1e3,1e3),n=e.staleTime;e.staleTime=typeof n=="function"?(...r)=>s(n(...r)):s(n),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Qa=(e,t)=>e.isLoading&&e.isFetching&&!t,Wa=(e,t)=>e?.suspense&&t.isPending,nr=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function Gi(e,t,s){const n=$a(),r=Ha(),i=Di(s),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const a=i.getQueryCache().get(o.queryHash);o._optimisticResults=n?"isRestoring":"optimistic",Ka(o),za(o,r,a),Va(r);const u=!i.getQueryCache().get(o.queryHash),[l]=I.useState(()=>new t(i,o)),c=l.getOptimisticResult(o),h=!n&&e.subscribed!==!1;if(I.useSyncExternalStore(I.useCallback(d=>{const f=h?l.subscribe(H.batchCalls(d)):q;return l.updateResult(),f},[l,h]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),I.useEffect(()=>{l.setOptions(o)},[o,l]),Wa(o,c))throw nr(o,l,r);if(qa({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,n)&&(u?nr(o,l,r):a?.promise)?.catch(q).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?c:l.trackResult(c)}function Nf(e,t){return Gi(e,Fi,t)}function Df(e,t){const s=Di(t),[n]=I.useState(()=>new ja(s,e));I.useEffect(()=>{n.setOptions(e)},[n,e]);const r=I.useSyncExternalStore(I.useCallback(o=>n.subscribe(H.batchCalls(o)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),i=I.useCallback((o,a)=>{n.mutate(o,a).catch(q)},[n]);if(r.error&&_n(n.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:i,mutateAsync:r.mutate}}function jf(e,t){return Gi(e,La,t)}var rr=I.use,Mn=I.useLayoutEffect;function _e(e){return e[e.length-1]}function $i(e,t){return typeof e=="function"?e(t):e}var An=Object.prototype.hasOwnProperty;function Bi(e){for(const t in e)if(An.call(e,t))return!0;return!1}var Kt=()=>Object.create(null),Ke=(e,t)=>we(e,t,!0);function we(e,t,s,n=0){if(e===t)return e;if(n++>500)return t;const r=Array.isArray(e)&&Array.isArray(t);if(!r&&!(es(e)&&es(t)))return t;const i=Object.keys(e),o=i.length,a=Object.keys(t),u=a.length;if(r?o!==e.length||u!==t.length||o&&_e(i)!==`${o-1}`||u&&_e(a)!==`${u-1}`:o!==Object.getOwnPropertyNames(e).length||u!==Object.getOwnPropertyNames(t).length||Object.getOwnPropertySymbols(t).length)return t;let l=0,c,h,d;if(r){for(;l<u&&(d=l,h=e[d],c=t[d],c=h===c?h:typeof h=="object"?we(h,c,s,n):c,c===h);l++);if(l===u&&o===u)return e}else{let p=o===u,g=!0;for(;l<u;l++){d=a[l],h=e[d];const v=t[d];c=h===v?h:typeof h=="object"?we(h,v,s,n):v,p&&=c===h&&(i[l]===d||An.call(e,d)),g&&=Object.is(c,v),i[l]=c}if(p)return Object.getOwnPropertySymbols(e).length?t:e;if(g)return t}const f=r?a.fill(0):s?Kt():{};for(let p=0;p<u;p++)d=r?p:a[p],r?(h=e[d],p>l&&(c=t[d],c=h===c?h:typeof h=="object"?we(h,c,s,n):c),f[d]=p<l?h:c):f[d]=i[p];return f}function es(e){return!e||typeof e!="object"?!1:(Object.getPrototypeOf(e)?.constructor??Object)===Object}function ve(e,t,s,n){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,s,n))return!1}return!0}if(es(e)&&es(t)){if(s){for(const i in t)if((n||t[i]!==void 0)&&!ve(e[i],t[i],s,n))return!1;return!0}let r=0;if(n)r=Object.keys(e).length;else for(const i in e)e[i]!==void 0&&r++;for(const i in t)if((n||t[i]!==void 0)&&(r--===0||!ve(e[i],t[i],s,n)))return!1;return r===0}return!1}function Ja(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 Xa=/[\x00-\x1f\x7f"<>`{}]/g;function Ya(e){return e.replace(Xa,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function ir(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,s=>{try{return decodeURI(s)}catch{return s}})}return Ya(t)}var Za=["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 Ui=/^[\x00-\x20]*[\\/][\t\n\r]*[\\/]/;function Hi(e,t){if(!e)return!1;if(Ui.test(e))return!0;const s=yt(e);return s?!t.has(s):!1}function at(e){if(!e)return e;let t=e;if(/[%\\\x00-\x1f\x7f]/.test(e)){const s=/%25|%5C/gi;let n=0,r;for(t="";(r=s.exec(e))!==null;)t+=ir(e.slice(n,r.index))+r[0],n=s.lastIndex;t+=ir(n?e.slice(n):e)}return t}function el(e){return/[\s\u0080-\uFFFF]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function tl(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;return!0}function On(){throw new Error("Invariant failed")}function Ye(e){return e.replace(/\/{2,}/g,"/")}function zi(e){return e==="/"?e:e.replace(/^\/+/,"")}function de(e){const t=e.length;return t>1&&e[t-1]==="/"?e.replace(/\/+$/,""):e}function Vi(e){return de(zi(e))}function or(e,t){return e?.endsWith("/")&&e!=="/"&&e!==`${t}/`?e.slice(0,-1):e}function ar(e,t,s="never",n){if(t.includes("//")&&(t=Ye(t)),t.startsWith("/"))return t.length===1||s==="preserve"?t:s==="always"?t.endsWith("/")?t:`${t}/`:t.endsWith("/")?t.slice(0,-1):t;const r=t===".";let i;if(n){i=r?e:e+"\0"+t;const l=n.get(i);if(l)return l}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 l=t.split("/");for(let c=0,h=l.length;c<h;c++){const d=l[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)===""?s==="never"&&o.pop():s==="always"&&o.push(""));const a=o.join("/"),u=(r?Ye(a):a)||"/";return i&&n&&n.set(i,u),u}function sl(e){const t=new Map(e.map(n=>[encodeURIComponent(n),n])),s=new RegExp([...t.keys()].join("|").replace(/[.*()]/g,"\\$&"),"g");return n=>n.replace(s,r=>t.get(r)??r)}function nl(e){return e==null||e===""}function rl(e,t,s){if(typeof t!="string")return""+(t??void 0);const n=e==="_splat";if(n&&(!t||/^[a-zA-Z0-9\-._~!/]*$/.test(t)))return t;let r=encodeURIComponent(t);return n&&(r=r.replaceAll("%2F","/")),s?s(r):r}function lr(e,t,s,n,r){const i=e.endsWith("/")?"/":"";let o="";for(const a of t){if(typeof a=="string"){o+=a;continue}const[u,l,c,h]=a,d=u===2,f=d&&h!==void 0?h+i:h;let p=s[l];if(!(u===3&&p==null)){if(r&&(r[l]=p,d&&(r["*"]=p)),d&&nl(p)){if(c==="/"&&!f)continue;p=""}o+=c+rl(l,p,n)+(f||"")}}return o+i||"/"}function et(e){return e?.isNotFound===!0}function il(){try{return sessionStorage}catch{return}}var ol="tsr-scroll-restoration-v1_3",qi=il();function al(){try{return JSON.parse(qi?.getItem("tsr-scroll-restoration-v1_3")||"{}")}catch{return{}}}function ll(){try{qi?.setItem(ol,JSON.stringify(Je))}catch{}}var Je=al(),ur="data-scroll-restoration-id",ul=e=>e.state.__TSR_key||e.href;function cl(e){const t=e.getAttribute(ur);if(t)return`[${ur}="${t}"]`;let s="",n=e,r;for(;r=n.parentNode;){let i=1,o=n;for(;o=o.previousElementSibling;)i++;const a=`${n.localName}:nth-child(${i})`;s=s?`${a} > ${s}`:a,n=r}return s}var xt=!1,Qt="window";function Js(e){try{return typeof e=="function"?e():document.querySelector(e)}catch{}}function cr(e){const t=new Set;for(const s of e){if(s===Qt)continue;const n=Js(s);n&&t.add(n)}return t}function dl(e,t){const s=t??e.options.scrollRestoration,n=e._scroll;s&&(n.restoring=!0);const r=e.options.getScrollRestorationKey||ul,i=new Set,o=a=>{const u=Je[a]||={};for(const l of i)l===document?u[Qt]={scrollX,scrollY}:l.isConnected&&(u[cl(l)]={scrollX:l.scrollLeft,scrollY:l.scrollTop})};s&&!n.restoration&&(n.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())),ll()})),!n.reset&&(n.reset=!0,e.subscribe("onRendered",a=>{const u=e.options.scrollRestorationBehavior,l=e.options.scrollToTopSelectors,c=n.next,h=n.hash;let d;if(i.clear(),n.next=!0,n.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(n.restoring&&p&&p!==f){const g=Je[p];if(g){let v=Je[f];for(const m in g){if(m===Qt){if(c)continue}else{const S=Js(m);if(!S||c&&l&&(d??=cr(l),d.has(S)))continue}v||(v=Je[f]={}),v[m]??=g[m]}}}xt=!0;try{const g=a.toLocation.hash,v=a.toLocation.state.__hashScrollIntoViewOptions??!0;let m=!1;if(c){!g&&l&&(d??=cr(l));const S=g&&v&&h,C=n.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:u}),m=!0}else{const y=Js(b);y&&(y.scrollLeft=w,y.scrollTop=R,d?.delete(y))}}if(!g){const b={top:0,left:0,behavior:u};if(m||scrollTo(b),d)for(const w of d)w.scrollTo(b)}}!m&&g&&v&&document.getElementById(g)?.scrollIntoView(v)}finally{xt=!1}}))}function hl(e,t=String){let s;for(const n in e){const r=e[n];r!==void 0&&(s||=new URLSearchParams).set(n,t(r))}return s?s.toString():""}function Rs(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function fl(e){const t=new URLSearchParams(e),s=Object.create(null);for(const[n,r]of t.entries()){const i=s[n];i==null?s[n]=Rs(r):Array.isArray(i)?i.push(Rs(r)):s[n]=[i,Rs(r)]}return s}var Ki=/^(?:\s|["[{\d-]|fa|nu|tr)/,pl=ml(JSON.parse),gl=vl(JSON.stringify,JSON.parse);function ml(e){const t=e===JSON.parse;return s=>{s[0]==="?"&&(s=s.substring(1));const n=fl(s);for(const r in n){const i=n[r];if(typeof i=="string"){if(t&&!Ki.test(i))continue;try{n[r]=e(i)}catch{}}}return n}}function vl(e,t){const s=t===JSON.parse;function n(r){if(r&&typeof r=="object")try{return e(r)}catch{}else if(t&&typeof r=="string"){if(s&&!Ki.test(r))return r;try{return t(r),e(r)}catch{}}return r}return r=>{const i=hl(r,n);return i?`?${i}`:""}}var ft="__root__";function Sl(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 s=new Response(null,{status:e.statusCode,headers:t});if(s.options=e,e.throw)throw s;return s}function Qi(e){return e instanceof Response&&!!e.options}function ts(e){const t=new Map;let s,n;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 u=s?.next().value;for(;!u||u.visited;)u?u.visited=!1:s=t.values(),u=s.next().value;u===n&&(s=void 0),t.delete(u.key)}const a={key:r,value:i,visited:!1};n=a,t.set(r,a)},clear(){t.clear(),s=void 0,n=void 0}}}var Re=4,Wi=5;function yl(e){const t=e.names;if(t)return t;const s=[];for(const n of e)typeof n!="string"&&s.push(n[1]);return e.names=s}function Il(e,t,s){const n=e.substring(t,s);if(n.charCodeAt(0)===36)return n.length===1?[2,"_splat","",void 0]:[1,n.substring(1),"",""];const r=n.indexOf("{");if(r>=0){const i=n.indexOf("}",r),o=n.charCodeAt(r+1)===45,a=r+(o?3:2);if(i>=0&&n.charCodeAt(a-1)===36&&(!o||a<i)){const u=n.substring(a,i);return[o?3:u?1:2,u||"_splat",n.substring(0,r),e.substring(t+i+1,u?s:e.length)]}}return n}function It(e,t,s,n,r,i){let o=s;const a=t.fullPath??t.from,u=t.options,l=a.length,c=a.endsWith("/")?l-1:l,h=u?.caseSensitive??e,d=u?.params?.parse??u?.parseParams;let f,p=i?s-1:0;if(!n||a.includes("$")){f=i?.slice()??[];const m=_e(f);m&&typeof m!="string"&&m[0]===2&&(f[f.length-1]=[m[0],m[1],m[2],m[3]===void 0?void 0:m[3]+a.substring(s-(a[s-2]==="/"?2:1),c)],p=l)}for(;o<l;){const m=o,S=a.indexOf("/",m);let C=S===-1?l:S;const b=Il(a,m,C);o=C+1;let w;if(typeof b=="string"){if(!n)continue;let R=b,y;h?y=n.static??=new Map:(R=b.toLowerCase(),y=n.staticInsensitive??=new Map);const _=y.get(R);if(_)w=_;else{const O=Fe(n);w=O,y.set(R,O)}}else{const R=b[0];let y=b[2],_=b[3]??"";if(R===2&&(C=l,o=C+1),f&&p<C&&(p<m-1&&f.push(a.substring(p,m-1)),b[2]="/"+y,R===2&&b[3]!==void 0&&c<l&&(b[3]=_.slice(0,-1)),f.push(b),p=C),!n)continue;const O=h&&!!(y||_);h||(y=y.toLowerCase(),_=_.toLowerCase());const T=R===1?n.dynamic??=[]:R===3?n.optional??=[]:n.wildcard??=[],A=R!==2&&!d&&T.find(M=>!M.parse&&M.caseSensitive===O&&M.prefix===y&&M.suffix===_);if(A)w=A;else{const M=Fe(n,R,O,y,_);w=M,T.push(M),T.length===2&&r?.push(T)}}n=w}f&&p<c&&f.push(a.substring(p,c));const g=f?.slice();if(!n)return g;if(d&&t.children&&!t.isRoot&&t.id&&t.id.charCodeAt(t.id.lastIndexOf("/")+1)===95){const m=Fe(n,Wi);(n.pathless??=[]).push(m),n=m}const v=(t.path||!t.children)&&!t.isRoot;if(v&&c<l){const m=Fe(n,Re);n.index=m,n=m}return n.parse=d??null,n.priority=u?.params?.priority??0,n.route||(n.data=g,v&&(n.route=t)),[n,o,g]}function Ji(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,s,n,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:s,prefix:n,suffix:r}}function Rl(e,t){const s=Fe(),n=[];function r(i,o,a,u){const[l,c,h]=It(!1,i,o,a,n,u);if(i.children)for(const d of i.children)r(d,c,l,h)}for(const i of e)r(i,1,s);for(const i of n)i.sort(Ji);t.masksTree=s,t.flatCache=ts(1e3)}function Cl(e,t){e||="/";const s=t.flatCache.get(e);if(s!==void 0)return s;const n=xn(e,t.masksTree);return t.flatCache.set(e,n),n}function bl(e,t,s,n,r){e||="/",n||="/";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)),xn(n,o,s)}function wl(e,t,s=!1){const n=s?e:`nofuzz\0${e}`,r=t.matchCache.get(n);if(r!==void 0)return r;e||="/";let i;try{i=xn(e,t.segmentTree,s)}catch(o){if(o instanceof URIError)i=null;else throw o}return i&&(i.branch=Yi(i.route)),t.matchCache.set(n,i),i}function El(e,t=!1){const s=Fe(),n=[],r={},i={};let o=0;function a(u,l,c,h){if(u.init(o),u.id in r&&On(),r[u.id]=u,o!==0&&u.path){const g=de(u.fullPath);(!i[g]||u.fullPath.endsWith("/"))&&(i[g]=u)}o++;const[d,f,p]=It(t,u,l,c,n,h);if(u._interpolation=p,u.children)for(const g of u.children)a(g,f,d,p)}a(e,1,s);for(const u of n)u.sort(Ji);return{processedTree:{segmentTree:s,singleCache:ts(1e3),matchCache:ts(1e3),flatCache:null,masksTree:null},routesById:r,routesByPath:i}}function xn(e,t,s=!1){const n=e.split("/"),r=Tl(e,n,t,s);if(!r)return null;const[i]=Xi(e,n,r);return{route:r.node.route,rawParams:i}}function Xi(e,t,s){const n=_l(s.node),r=s.node.data&&yl(s.node.data),i=Object.create(null);let o=s.extract?.part??0,a=s.extract?.node??0,u=s.extract?.path??0,l=s.extract?.param??0;for(;a<n.length;o++,a++,u++){const c=n[a];if(c.kind===Re)break;if(c.kind===Wi){o--,u--;continue}const h=t[o],d=u;if(h&&(u+=h.length),c.kind===1||c.kind===3){const f=r[l++];if(c.kind===3&&s.skipped&1<<a){o--,u=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 s.rawParams&&Object.assign(i,s.rawParams),[i,{part:o,node:a,path:u,param:l}]}function Yi(e){const t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function _l(e){const t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function Tl(e,t,s,n){if(e==="/"&&s.index)return{node:s.index,skipped:0};const r=!_e(t),i=r&&e!=="/",o=t.length-(r?1:0),a=[{node:s,index:1,skipped:0,statics:0,dynamics:0,optionals:0}];let u=null,l=null;for(;a.length;){const c=a.pop(),{node:h,index:d,skipped:f,statics:p,dynamics:g,optionals:v}=c;let{extract:m,rawParams:S}=c;if(h.kind===2&&h.route&&!kt(l,c))continue;if(h.parse){if(!dr(e,t,c))continue;S=c.rawParams,m=c.extract}n&&h.route&&h.kind!==Re&&kt(u,c)&&(u=c);const C=d===o;if(C&&(h.route&&(!i||h.kind===Re||h.kind===2)&&kt(l,c)&&(l=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:v,extract:m,rawParams:S};let y=!0;if(h.index.parse&&(dr(e,t,R)||(y=!1)),y){if(!g&&!v&&!f&&Ml(p,o))return R;kt(l,R)&&(l=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("/"),A=T.slice(-O.length);if((y.caseSensitive?A:A.toLowerCase())!==O||T.length-O.length<_.length)continue}a.push({node:y,index:o,skipped:f,statics:p,dynamics:g,optionals:v,extract:m,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:v,extract:m,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 A=_.caseSensitive?b:w??=b.toLowerCase();if(O&&!A.startsWith(O)||T&&A.indexOf(T,A.length-T.length)<O.length)continue}a.push({node:_,index:d+1,skipped:f,statics:p,dynamics:g,optionals:v+Pt(o,d),extract:m,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:v,extract:m,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:v,extract:m,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:v,extract:m,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:v,extract:m,rawParams:S})}}if(l)return l;if(n&&u){let c=u.index;for(let d=0;d<u.index;d++)c+=t[d].length;const h=c===e.length?"/":e.slice(c);return u.rawParams??=Object.create(null),u.rawParams["**"]=decodeURIComponent(h),u}return null}function Pt(e,t){return 2**(e-t-1)}function Ml(e,t){return e===2**(t-1)-1}function dr(e,t,s){let n,r;try{[n,r]=Xi(e,t,s)}catch{return null}if(s.rawParams=n,s.extract=r,!s.node.parse)return!0;try{if(s.node.parse(n)===!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 Al(e,t,s){const n=Vi(e),r=`/${n}`,i=t?r:r.toLowerCase(),o=`${i}/`,a={input:({url:u})=>{const l=t?u.pathname:u.pathname.toLowerCase();return l===i?u.pathname="/":l.startsWith(o)&&(u.pathname=u.pathname.slice(r.length)),u},output:({url:u})=>(u.pathname=Ye(`/${n}${u.pathname}`),u)};return s?{input:({url:u})=>Xs(s,a.input({url:u})),output:({url:u})=>a.output({url:Zi(s,u)})}:a}function Xs(e,t){const s=e?.input?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function Zi(e,t){const s=e?.output?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function Ol(e,t){const{createMutableStore:s,createReadonlyStore:n,batch:r}=t,i=new Map,o=s("idle"),a=s(e),u=s(void 0),l=s([]),c=n(()=>l.get().map(g=>i.get(g).get())),h=n(()=>({status:o.get(),isLoading:o.get()==="pending",matches:c.get(),location:a.get(),resolvedLocation:u.get()}));function d(g){let v=i.get(g);return v||(v=s(void 0),i.set(g,v)),v}const f={status:o,location:a,resolvedLocation:u,ids:l,matches:c,byRoute:i,__store:h,getMatchStore:d,setMatches:p};function p(g){const v=l.get(),m=g.map(S=>S.routeId);r(()=>{tl(v,m)||l.set(m);for(const S of v)m.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",hr="popstate",fr="beforeunload",xl=/^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/;function Wt(e){const t=xl.exec(e);return t?"/"+e.slice(t[0].length):e}function eo(e){return/[\x00-\x1f\x7f]/.test(e)&&(e=e.replace(/[\x00-\x1f\x7f]/g,t=>`
2
+ \r`.includes(t)?"":encodeURIComponent(t))),Wt(e)}function Pl(e){let t=e.getLocation();const s=new Set,n=o=>{t=e.getLocation(),s.forEach(a=>a({location:t,action:o}))},r=o=>{e.notifyOnIndexChange??!0?n(o):t=e.getLocation()},i=async({task:o,navigateOpts:a,...u})=>{if(a?.ignoreBlocker??!1){o();return}const l=e.getBlockers?.()??[],c=u.type==="PUSH"||u.type==="REPLACE";if(typeof document<"u"&&l.length&&c)for(const h of l){const d=ss(u.path,u.state);if(await h.blockerFn({currentLocation:t,nextLocation:d,action:u.type})){e.onBlocked?.();return}}o()};return{get location(){return t},get length(){return e.getLength()},subscribers:s,subscribe:o=>(s.add(o),()=>{s.delete(o)}),push:(o,a,u)=>{const l=t.state[Ee];a=pr(l+1,a),i({task:()=>{e.pushState(o,a),n({type:"PUSH"})},navigateOpts:u,type:"PUSH",path:o,state:a})},replace:(o,a,u)=>{const l=t.state[Ee];a=pr(l,a),i({task:()=>{e.replaceState(o,a),n({type:"REPLACE"})},navigateOpts:u,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 u=e.getBlockers?.()??[];e.setBlockers?.(u.filter(l=>l!==o))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:n,_getBlockers:()=>e.getBlockers?.()??[]}}function pr(e,t){const s=Pn();return{...t,key:s,__TSR_key:s,[Ee]:e}}function kl(e){const t=e?.window??(typeof document<"u"?window:void 0),s=t.history.pushState,n=t.history.replaceState;let r=[];const i=()=>r,o=y=>r=y,a=y=>eo(e?.createHref?e.createHref(y):y),u=e?.parseLocation??(()=>ss(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){const y=Pn();t.history.replaceState({[Ee]:0,key:y,__TSR_key:y},"")}let l=u(),c,h=!1,d=!1,f=!1,p=!1;const g=()=>l;let v;const m=()=>{v&&(R._ignoreSubscribers=!0,(v[2]?t.history.pushState:t.history.replaceState)(v[1],"",v[0]),R._ignoreSubscribers=!1,v=void 0,c=void 0)},S=(y,_,O)=>{const T=e?.createHref?a(_):void 0,A=!!v;A||(c=l),l=ss(_,O),v=[T??l.href,O,v?.[2]||y],A||queueMicrotask(()=>m())},C=y=>{l=u(),R.notify({type:y})},b=async()=>{if(p=!1,d){d=!1;return}const y=u(),_=y.state[Ee]-l.state[Ee],O=_===1,T=_===-1,A=!O&&!T||h;h=!1;const M=A?"GO":T?"BACK":"FORWARD",x=A?{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:l,nextLocation:y,action:M})){d=!0,t.history.go(-_),R.notify(x);return}}}l=u(),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 A=T.enableBeforeUnload??!0;if(A===!0){_=!0;break}if(typeof A=="function"&&A()===!0){_=!0;break}}if(_)return y.preventDefault(),y.returnValue=""},R=Pl({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:m,destroy:()=>{t.history.pushState=s,t.history.replaceState=n,t.removeEventListener(fr,w,{capture:!0}),t.removeEventListener(hr,b)},onBlocked:()=>{c&&l!==c&&(l=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(fr,w,{capture:!0}),t.addEventListener(hr,b),t.history.pushState=function(...y){const _=s.apply(t.history,y);return R._ignoreSubscribers||C("PUSH"),_},t.history.replaceState=function(...y){const _=n.apply(t.history,y);return R._ignoreSubscribers||C("REPLACE"),_},R}function ss(e,t){const s=eo(e),n=s.indexOf("#"),r=s.indexOf("?");if(!t){const i=Pn();t={[Ee]:0,key:i,__TSR_key:i}}return{href:s,pathname:s.substring(0,n>0?r>0?Math.min(n,r):n:r>0?r:s.length),hash:n>-1?s.substring(n):"",search:r>-1?s.slice(r,n===-1?void 0:n):"",state:t}}function Pn(){return(Math.random()+1).toString(36).substring(7)}function Cs(e,t){return e.protocol!=="http:"&&e.protocol!=="https:"||e.origin!==t||!!e.username||!!e.password}function bs(e){return e.pathname+e.search+e.hash}function gr(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function us(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function mr({key:e,__TSR_key:t,__TSR_index:s,__hashScrollIntoViewOptions:n,...r}){return r}function Fl(e){return e.findIndex(t=>t.status==="error"||t.status==="notFound"||t._notFound)+1}function Ll(e,t,s,n,r,i){n&&(t=t.slice(0,n)),r&&(s=s.slice(0,r));for(const o of t){if(i&&e._tx!==i)return;s.some(a=>a.routeId===o.routeId)||e.routesById[o.routeId].options.onLeave?.(o)}for(const o of s){if(i&&e._tx!==i)return;e.routesById[o.routeId].options[t.some(a=>a.routeId===o.routeId)?"onStay":"onEnter"]?.(o)}}var Nl=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 s=>(s(),!1),this.update=s=>{const n=this.options;this.options={...n,...s},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=kl()),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||n?.rewrite!==i||n?.caseSensitive!==this.options.caseSensitive;if(o&&(this.basepath=r,this.rewrite=r!=="/"&&Vi(r)?Al(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=Ol(this.latestLocation,a),dl(this)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const s=El(this.routeTree,this.options.caseSensitive);return this.options.routeMasks&&Rl(this.options.routeMasks,s.processedTree),{...s,resolvePathCache:ts(1e3)}},this.subscribe=(s,n)=>{const r={eventType:s,fn:n};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=s=>{for(const n of this.subscribers)if(n.eventType===s.type)try{n.fn(s)}catch(r){console.error(r)}},this.parseLocation=(s,n)=>{const r=({pathname:u,search:l,hash:c,href:h},d)=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(u)){const v=this.options.parseSearch(l),m=this.options.stringifySearch(v);return{href:u+m+c,publicHref:u+m+c,pathname:at(u),external:!1,searchStr:m,search:Ke(n?.search,v),hash:at(c.slice(1)),state:we(n?.state,d)}}const f=Xs(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&&Cs(f,this.origin),searchStr:g,search:Ke(n?.search,p),hash:at(f.hash.slice(1)),state:we(n?.state,d)}},i=r(s,s.state),{__tempLocation:o,__tempKey:a}=i.state;if(o&&(!a||a===this.tempLocationKey)){const u=r(o,{...o.state,__tempLocation:void 0,key:i.state.key,__TSR_key:i.state.__TSR_key});return u.maskedLocation=i,u}return i},this.matchRoutes=(s,n,r)=>typeof s=="string"?this.matchRoutesInternal({pathname:s,search:n},r):this.matchRoutesInternal(s,n),this.getMatchedRoutes=s=>{const n=Object.create(null),r=wl(de(s),this.processedTree,!0);return r&&Object.assign(n,r.rawParams),[r?.branch||[this.routesById.__root__],n,r?.route]},this.buildLocation=s=>{{const o=this.staticLocations.get(s);if(o)return o}let n=!1;const r=(o={})=>{if(o.href){const P=ss(o.href,{});o={...o,to:Xs(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 u;const l=()=>(n=!0,a),c=()=>(n=!0,u??=this.matchRoutesLightweight(a)),h=o.to?`${o.to}`:".",d=ar(h[0]==="/"?"":o.unsafeRelative==="path"?l().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??=Yi(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 v=p?f?._interpolation??It(!1,{fullPath:d},0):void 0;let m;for(const P of g){const E=P.options.params?.stringify??P.options.stringifyParams;if(E){const G=c()[3];if(m??=ws(o.params,G),!Bi(m))break;m===G&&(m=Object.assign(Kt(),m));try{Object.assign(m,E(m))}catch{}}}m??=ws(o.params,jl(o.params,v)?c()[3]:Es);const S=s.leaveParams?d:Wt(at(v?lr(d,v,m,this.pathParamsDecoder):d)),C=Gl(g,s._includeValidateSearch),b=()=>{let P=c()[2];if(s._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?$l(C,b(),o):o.search===!0?b():typeof o.search=="function"?o.search(b()):o.search||Es,R=this.options.stringifySearch(w),y=o.hash===!0?l().hash:typeof o.hash=="function"?o.hash(l().hash):o.hash||void 0,_=y?`#${y}`:"",O=o.state?o.state===!0?l().state:typeof o.state=="function"?o.state(l().state):o.state:Es,T=`${S}${R}${_}`;let A,M,x=!1;if(this.rewrite){const P=new URL(T,this.origin),E=P.origin,G=Zi(this.rewrite,P);A=bs(P),Cs(G,E)?(M=G.href,x=!0):M=Wt(bs(G))}else A=el(T),M=A;return{publicHref:M,href:A,pathname:S,search:w,searchStr:R,state:O,hash:y??"",external:x,unmaskOnReload:o.unmaskOnReload}},i=r(s);if(s.mask)i.maskedLocation=r({from:s.from,...s.mask});else if(this.options.routeMasks){const o=Cl(i.pathname,this.processedTree);if(o){const a=Object.assign(Kt(),o.rawParams),{from:u,params:l,...c}=o.route,h=ws(l,a);i.maskedLocation=r({from:s.from,...c,params:h})}}return!n&&s._fromLocation&&!i.maskedLocation&&this.staticLocations.set(s,i),i},this.commitLocation=async({viewTransition:s,ignoreBlocker:n,...r})=>{const i=r.maskedLocation??r;if(i.external)return vr(this,i.publicHref,{replace:r.replace,ignoreBlocker:n});let o;const a=de(this.latestLocation.href)===de(r.href)&&ve(mr(r.state),mr(this.latestLocation.state)),u=this._commitPromise;let l;const c=new Promise(h=>{l=h});if(c.resolve=()=>{l(),u?.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=s,o=r.replace?"REPLACE":"PUSH",this.history[o==="REPLACE"?"replace":"push"](f.publicHref,f.state,{ignoreBlocker:n}),this.history.subscribers.size||this.load({action:{type:o}})}return this._scroll.next=r.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:s,resetScroll:n,hashScrollIntoView:r,viewTransition:i,ignoreBlocker:o,...a}={})=>{const u=this.buildLocation({...a,_includeValidateSearch:!0});this._pendingLocation=u;const l=this.commitLocation({...u,viewTransition:i,replace:s,resetScroll:n,hashScrollIntoView:r,ignoreBlocker:o});return queueMicrotask(()=>{this._pendingLocation===u&&(this._pendingLocation=void 0)}),l},this.navigate=async({to:s,reloadDocument:n,href:r,publicHref:i,...o})=>{const a=r?yt(r):void 0;if(a||n){if(s!==void 0||!r){const l=this.buildLocation({to:s,...o}),c=l.maskedLocation??l;r??=c.publicHref,i??=c.publicHref}return vr(this,!a&&i?i:r,o)}return this.buildAndCommitLocation({...o,href:r,to:s,_isNavigate:!0})},this.load=async s=>{this.updateLatestLocation(),s?.action&&(this._scroll.hash=s.action.type==="PUSH"||s.action.type==="REPLACE"),await Wl(this,s)},this.startViewTransition=s=>{const n=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,n&&typeof document.startViewTransition=="function"){let r;if(typeof n=="object"&&window.CSS?.supports?.("selector(:active-view-transition-type(a))")){const i=this.latestLocation,o=this.stores.resolvedLocation.get(),a=typeof n.types=="function"?n.types(us(i,o)):n.types;if(a===!1)return s();r={update:s,types:a}}else r=s;return document.startViewTransition(r).updateCallbackDone}return s()},this.invalidate=s=>{const n=this._committed,r=s?.filter,i=this._preloads,o=new Set,a=c=>{(!r||r(c))&&o.add(c.id)};n.forEach(a),this._cache.forEach(a),i?.forEach(c=>c.forEach(a)),this._tx?.[3].forEach(a);const u=[];for(const[c,h]of i??[])h.some(d=>o.has(d.id))&&(i.delete(c),u.push(c));const l=c=>{if(o.has(c.id)){const h=this.routesById[c.routeId],d={...c,invalid:!0,...(s?.forcePending||c.status==="error"||c.status==="notFound")&&gr(h)?{status:"pending",error:void 0}:void 0};return c._flight=void 0,d}return c};this._committed=n.map(l);for(const[c,h]of this._cache)o.has(c)&&(h.invalid=!0,s?.forcePending&&(h.status="pending"));for(const c of o)this._flights?.delete(c);for(const c of u)c.abort();return this.shouldViewTransition=!1,this.load({sync:s?.sync})},this.resolveRedirect=s=>{const n=s.options;let r=s.headers.get("Location")||n.href;if(!r){const o=this.buildLocation(n);r=(o.maskedLocation??o).publicHref||"/"}let i;if(Ui.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:Cs(o,this.origin)||(r=bs(o),i=void 0)}return i&&(n.reloadDocument=!0),n.href=r,s.headers.set("Location",r),s},this.clearCache=s=>{const n=this._cache,r=this._preloads,i=s?.filter,o=[],a=[];for(const[l,c]of n)(!i||i(c))&&(a.push(l),o.push(c));const u=[];for(const[l,c]of r??[])(!i||c.some(i))&&(u.push(l),o.push(...c));for(const l of a)n.delete(l);for(const l of u)r.delete(l);for(const l of o){const c=l._flight;l._flight=void 0,c&&!--c[2]&&(this._flights?.get(l.id)===c&&this._flights.delete(l.id),u.push(c[1]))}for(const l of u)l.abort()},this.loadRouteChunk=Ze,this.preloadRoute=s=>Jl(this,s),this.matchRoute=(s,n)=>{const r={...s,to:s.to?ar(s.from||"",s.to,this.options.trailingSlash,this.resolvePathCache):void 0,params:s.params||{},leaveParams:!0},i=this.buildLocation(r),o=this.stores.status.get()==="pending";if(n?.pending&&!o)return!1;const a=n?.pending??!o?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),u=bl(i.pathname,n?.caseSensitive??!1,n?.fuzzy??!1,a.pathname,this.processedTree);return!u||s.params&&!ve(u.rawParams,s.params,!0)?!1:n?.includeSearch??!0?ve(a.search,i.search,!0)?u.rawParams:!1:u.rawParams},this.getStoreConfig=t,e.pathParamsAllowedCharacters?.length&&(this.pathParamsDecoder=sl(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??gl,parseSearch:e.parseSearch??pl,protocolAllowlist:e.protocolAllowlist??Za}),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[s,n,r]=this.getMatchedRoutes(e.pathname);let i=s,o=!1;(r?r.path!=="/"&&n["**"]:de(e.pathname))&&(this.options.notFoundRoute?i=[...i,this.options.notFoundRoute]:o=!0);const a=o?Bl(this.options.notFoundMode,i):void 0,u=new Array(i.length),l=this._committed,c=(d,f)=>{const p=l[f];return p?.routeId===d.id?p:d===this.options.notFoundRoute?l.find(g=>g.routeId===d.id):void 0};let h;for(let d=0;d<i.length;d++){const f=i[d],p=u[d-1];let g,v,m;{const x=p?.search??e.search,P=p?._strictSearch??void 0;try{const E=Jt(f.options.validateSearch,{...x})??void 0;g={...x,...E},v={...P,...E}}catch(E){let G=E;if(E instanceof ns||(G=new ns(E.message,{cause:E})),t?.throwOnError)throw G;g=x,v={},m=G}}let S="",C="";try{S=f.options.loaderDeps?.({search:g})??"",C=S&&JSON.stringify(S)||""}catch(x){if(t?.throwOnError)throw x;m??=x}const b=Kt(),w=f._interpolation?lr(f.fullPath,f._interpolation,n,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{Sr(f,h)}catch(x){if(et(x)||Qi(x)?O=x:O=new Dl(x.message,{cause:x}),t?.throwOnError)throw O}const T=y?"stay":"enter";let A;if(_)A={..._,cause:T,search:Ke(y?y.search:_.search,g),_strictSearch:v,searchError:m};else{const x=gr(f)?"pending":"success";A={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:v,searchError:m,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 M=a===f.id;A._notFound&&!M&&(A.error=void 0),A._notFound=M,u[d]=A}for(let d=0;d<u.length;d++){const f=u[d];f.params=f.cause==="stay"?Ke(f.params,h):h,t?._controller&&(f.context={})}return u}matchRoutesLightweight(e){const t=_e(this.stores.ids.get()),s=t?this.stores.byRoute.get(t).get():void 0,n=s?.id,r=this.lightweightCache.get(e);if(r&&r[0]===n)return r[1];const[i,o]=this.getMatchedRoutes(e.pathname),a=_e(i),u={...e.search};for(const d of i)try{Object.assign(u,Jt(d.options.validateSearch,u))}catch{}const l=s&&s.routeId===a.id&&s.pathname===e.pathname;let c;if(l)c=s.params;else{const d=o;for(const f of i)try{Sr(f,d)}catch{}c=d}const h=[i,a.fullPath,u,c];return this.lightweightCache.set(e,[n,h]),h}};async function vr(e,t,{replace:s,ignoreBlocker:n}){if(!Hi(t,e.protocolAllowlist)){if(!n){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:s?"REPLACE":"PUSH"}))return}e.history._ignoreNextBeforeUnload?.(t),s?window.location.replace(t):window.location.href=t}}var ns=class extends Error{},Dl=class extends Error{};function Jt(e,t){if(e==null)return{};if("~standard"in e){const s=e["~standard"].validate(t);if(s instanceof Promise)throw new ns("Async validation not supported");if(s.issues)throw new ns(JSON.stringify(s.issues,void 0,2),{cause:s});return s.value}return"parse"in e?e.parse(t):typeof e=="function"?e(t):{}}function ws(e,t){if(e===void 0||e===!0)return t;const s=Object.create(null);return e===!1||e===null?s:typeof e=="function"?(Object.assign(s,t),Object.assign(s,e(s))):Object.assign(s,t,e)}function jl(e,t){return typeof e=="function"?!0:!t||e===!1||e===null?!1:e===void 0||e===!0||t.some(s=>typeof s!="string"&&!An.call(e,s[1]))}var Es=Object.freeze({});function Gl(e,t){const s=[];for(let n=0;n<e.length;n++){const r=e[n].options;if("search"in r)r.search?.middlewares&&s.push(...r.search.middlewares);else if(r.preSearchFilters||r.postSearchFilters){const o=({search:a,next:u})=>{const l=u(r.preSearchFilters?r.preSearchFilters.reduce((c,h)=>h(c),a):a);return r.postSearchFilters?r.postSearchFilters.reduce((c,h)=>h(c),l):l};s.push(o)}const i=r.validateSearch;if(t&&i){const o=({search:a,next:u,meta:l})=>{const c=u(a);try{const h=Jt(i,c);if(l&&h)for(const d in h)d in c||(l.defaulted||=new Map).set(d,h[d]);return{...c,...h}}catch{}return c};s.push(o)}}return s}function $l(e,t,s){const n=(r,i,o)=>{if(r>=e.length){if(!s.search)return{};if(s.search===!0)return i;const u=$i(s.search,i);return o&&(o.explicit=u),u}const a=(u,l)=>{if(l){const c=o||{};return{search:n(r+1,u,c),meta:c}}return n(r+1,u,o)};return e[r]({search:i,next:a,meta:o})};return n(0,t)}function Bl(e,t){if(e!=="root"){let s;for(let n=t.length-1;n>=0;n--){const r=t[n];if(r.options.notFoundComponent)return r.id;s||=r.children&&r.id}if(s)return s}return ft}function Sr(e,t){const s=e.options.params?.parse??e.options.parseParams;s&&Object.assign(t,s(t))}function Ys(e,t){return e.options[t]?.preload?.()}function Ul(e,t){const s=Ys(e,"component");let n=Ys(e,"pendingComponent");return t&&(n?n=n.then(t):t()),s&&n?Promise.all([s,n]).then(()=>{}):s??n}function Ze(e,t,s){const n=()=>t===!1?void 0:t?Ys(e,t):Ul(e,s),r=e._lazy;if(r)return r===!0?n():r.then(n);if(!e.lazyFn)return n();const i=e.lazyFn().then(o=>{{const{id:a,...u}=o.options;Object.assign(e.options,u),e._lazy=!0}},o=>{throw e._lazy=void 0,o});return e._lazy=i,i.then(n)}function kn(e){const t=e.findIndex(s=>s.status!=="success"||s._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var he=0,Se=1,cs=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((s,n)=>{const r=()=>n(t);t.addEventListener("abort",r,{once:!0}),Promise.resolve(e).then(s,n).then(()=>t.removeEventListener("abort",r))})}function Be(e,t){return e.routesById[t.routeId]}function Ct(e,t,s){return Qi(e)?[K,e]:et(e)?(e.routeId||=s,[cs,e]):t?(typeof e?.then=="function"&&(e=new Error("A Promise was thrown",{cause:e})),[Se,e]):[he,e]}function Fn(e,t){let s=Ct(t,!0,e.id);if(s[0]!==Se)return s;try{e.options.onError?.(s[1])}catch(n){s=Ct(n,!0,e.id)}return s}function pt(e,t,s,n,r){return r[0].signal.aborted?Te:Dn(e,t,s,Fn(s,n),r)}async function Hl(e,t,s,n,r,i){const[o,a]=t,u=s[0].signal,l=!!s[3];for(let c=s[6]??0;c<n;c++){const h=a[c],d=Be(e,h);h.abortController=s[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:l?"preload":h.cause,abortController:s[0],preload:l,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,s)]}if(u.aborted)return[c,Te];const g=h.paramsError??h.searchError;if(g!==void 0)return me(e,h),[c,pt(e,t,d,g,s)];const v=d.options.beforeLoad;if(!v)continue;const m=h.status;c>=i&&(h.status="pending",s[7]?.());try{bt(e,h,"beforeLoad",s[0]);const S=v({...p,search:h.search,context:h.context,...e.options.additionalContext}),C=await(typeof S?.then=="function"?$e(S,u):S);if(u.aborted)return[c,Te];const b=Dn(e,t,d,Ct(C,!1,d.id),s);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,s)]}finally{h.status=m,bt(e,h,!1,s[0])}}r()}function Ln(e,t,s){if(!(!s||--s[2])){if(e._flights?.get(t.id)===s){const n=e._tx;if(n&&!n[0].signal.aborted&&!n[3].includes(t)&&n[3].some(r=>r.id===t.id)&&n[3].some(r=>r.isFetching==="beforeLoad"))return;e._flights.delete(t.id)}return s[1]}}function me(e,t){const s=t._flight;t._flight=void 0,Ln(e,t,s)?.abort()}function W(e,t,s,n){const r=[];for(const i of t)if(!s?.includes(i)){const o=i._flight;if(i._flight=void 0,n&&o?.[2]===1&&e._flights?.get(i.id)===o&&s?.some(a=>a.id===i.id))o[2]=0;else{const a=Ln(e,i,o);a&&r.push(a)}}for(const i of r)i.abort()}function Nn(e){for(const t of e){const s=t._flight;s&&s[2]++}}function bt(e,t,s,n){if(t.isFetching=s,n&&e._tx?.[0]!==n)return;const r=e.stores.byRoute.get(t.routeId),i=r?.get();i?.id===t.id&&r.set({...i,isFetching:s})}function to(e,t,s,n,r,i,o){const a=t[0];return{params:s.params,location:a,navigate:u=>e.navigate({...u,_fromLocation:a}),cause:o?"preload":s.cause,abortController:r,preload:o,deps:s.loaderDeps,parentMatchPromise:i,context:s.context,route:n,...e.options.additionalContext}}async function yr(e,t,s,n,r,i,o){const a=o[0],u=a.signal;if(u.aborted)return Te;if(!r)return[he,void 0];let l=s._flight;bt(e,s,"loader",a);try{if(!l){const c=new AbortController;l=[Promise.resolve().then(()=>r(to(e,t,s,n,c,i,!!o[3]))).then(h=>Ct(h,!1,n.id),h=>Ct(h,!0,n.id)).then(h=>(h[0]!==he&&e._flights?.get(s.id)===l&&(e._flights.delete(s.id),l[2]||c.abort()),h[0]===Se&&l[2]?Fn(n,h[1]):h)),c,1],(e._flights??=new Map).set(s.id,l)}return s._flight=l,s.abortController=l[1],Dn(e,t,n,await $e(l[0],u),o)}catch(c){if(c!==u||!u.aborted)throw c;return me(e,s),Te}finally{bt(e,s,!1,a)}}function Ir(e,t,s){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=s):e.invalid=!0)}function zl(e,t,s){const n=e._cache.get(t.id);if(n!==s||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),n&&me(e,n)}function Rr(e,t){return t[0]===Se||t[0]===cs?{...e,status:t[0]===Se?"error":"notFound",error:t[1],_flight:void 0}:e}function Vl(e,t,s,n,r,i,o){const a=t[1][s],u=Be(e,a),l=!!i[3],c=e._cache.get(a.id);let h,d=!1,f;try{if(a.status==="success"&&(h=u.options.shouldReload,typeof h=="function"&&(h=h(to(e,t,a,u,i[0],r,l))),i[0].signal.aborted&&(f=Te)),!f)if(a.status!=="success")d=!0;else{const M=l||a.preload?u.options.preloadStaleTime??e.options.defaultPreloadStaleTime??3e4:u.options.staleTime??e.options.defaultStaleTime??0;d=!!(a.invalid||h||h===void 0&&Date.now()-a.updatedAt>=M&&(i[5]||a.cause==="enter"||i[2].some(x=>x.routeId===a.routeId&&x.id!==a.id)))}}catch(M){a.invalid=!0,me(e,a),f=pt(e,t,u,M,i)}const p=u.options.loader,g=typeof p=="function",v=g?p:p?.handler,m=!l||u.options.preload!==!1;let S=m&&p?e._flights?.get(a.id):void 0;S===a._flight||f?S=void 0:S&&!d&&!l&&h===void 0?d=!0:d||(S=void 0);const C=!!(p&&d&&a.status==="success"&&!l&&!i[4]&&((g?void 0:p.staleReloadMode)??e.options.defaultStaleReloadMode)!=="blocking"),b=d&&m,w=b&&!C&&(a.status!=="success"||!!p),R=s>=o?i[7]:void 0,y=u.lazyFn&&u._lazy!==!0?R:void 0;if(b&&!p&&(a.invalid=!1,a.updatedAt=Date.now()),S&&S[2]++,w){const M=a._flight;a._flight=S,Ln(e,a,M)?.abort(),s>=o&&(a.status="pending"),R?.()}b||(a.isFetching=!1);const _=!f&&w?yr(e,t,a,u,v,r,i).then(M=>(Ir(a,M,l),M[0]===he&&(p&&!i[0].signal.aborted&&zl(e,a,c),s>=o&&(a.status="pending")),M)):Promise.resolve(f??[he,a.loaderData]),O=(async()=>{try{const x=Ze(u,void 0,y);x&&await $e(x,i[0].signal)}catch(x){if(!t[1].some((P,E)=>E<=s&&(P.status==="error"||P.status==="notFound"||P._notFound)))return[s,pt(e,t,u,x,i)]}const M=await _;w&&M[0]===he&&a.status==="pending"&&!i[0].signal.aborted&&(a.status="success",R?.())})();if(n.push([s,_,O]),!C)return _.then(M=>Rr(a,M));const T={...a,status:"pending",preload:!1,_flight:S};a.invalid=!1,a.isFetching="loader";const A=yr(e,t,T,u,v,r,i).then(M=>(a.isFetching=!1,Ir(T,M,!1),M));return(t[2]??=[]).push([s,A,O,T]),A.then(M=>Rr(T,M))}async function Zs(e,t,s,n,r=0){const i=s?.[1][1];let o=i?.routeId?t.findIndex(a=>a.routeId===i.routeId):s?.[0]??t.length-1;o<0&&(o=0);for(let a=o;a>=0;a--){const u=Be(e,t[a]);try{const l=Ze(u,!1);l&&await $e(l,n)}catch(l){if(l===n&&n.aborted)throw l}if(u.options.notFoundComponent)return a}return i?.routeId?o:r}function Le(e,t){t[2]&&(W(e,t[2].map(s=>s[3])),t[2]=void 0)}async function Cr(e,t,s,n){let r;try{await Promise.all(e.map(i=>i[1].then(async o=>{const a=i[0];if(!(n&&a>=await n)){if(o[0]>=K)throw[a,o];!r&&o[0]!==he&&(r=[a,o],await Promise.all((s??[]).map(u=>{if(!(u[0]<=a))return u[1].then(l=>{if(l[0]===K)throw[u[0],l]})})))}})))}catch(i){return i}return t??r}function Dn(e,t,s,n,r,i){for(;n[0]===K;){const o=n[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 n;const u=e.buildLocation({...a,_fromLocation:t[0],_includeValidateSearch:!0}),l=u.maskedLocation??u;if(l.external){const c=o.clone();return c.options={...a},c.headers.set("Location",l.publicHref),e.resolveRedirect(c),r[3]?[K,c]:[K,c,l]}return[K,o,u]}catch(u){n=i?[Se,u]:Fn(s,u),i=!0}}return n}async function so(e,t,s,n,r,i){const o=t[1];let a=await r,u=!1;const l=o.findIndex(f=>f._notFound),c=f=>f[1][0]===cs?Zs(e,o,f,n.signal):f[0];let h=l<0?o.length:l;if((a?.[1][0]??0)>=K)h=0;else if(a){h=a[2]??=await c(a);for(const f of s){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 s){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;u=!0,a=[0,[Se,new Error("Too many redirects")]]}const d=a?a[2]??await c(a):l;if(d>=0){const f=a?.[1],p=f?.[0],g=o[d],v=f?.[1],m=()=>{f&&(g._notFound=void 0,p===Se?g.status="error":(v.routeId=g.routeId,g.routeId===e.routeTree.id?(g.status="success",g._notFound=!0):g.status="notFound"),g.error=v,g.isFetching=!1)};m(),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")]),n.signal)}catch(C){if(C===n.signal&&n.signal.aborted)return Le(e,t),Te}f?u&&(n.abort(),await Promise.all([...s.map(C=>C[1]),...s.map(C=>C[2]),...(t[2]??[]).map(C=>C[1])]),Le(e,t),W(e,o),m()):g.status="success"}return t}async function no(e,t,s,n=0,r=t[1].length){const i=t[1];for(let o=n;o<r;o++){const a=i[o],u=Be(e,a).options;if(u.head||u.scripts)try{const l={ssr:e.options.ssr,matches:i,match:a,params:a.params,loaderData:a.loaderData},[c,h]=await $e(Promise.all([u.head?.(l),u.scripts?.(l)]),s);a.meta=c?.meta,a.links=c?.links,a.headScripts=c?.scripts,a.styles=c?.styles,a.scripts=h}catch(l){if(l===s&&s.aborted)break;console.error(l)}if(a.status!=="success"||a._notFound)break}return t}async function ro(e,t,s,n){const r=[t,s],i=n[0].signal;let o;try{const a=e.stores.matches.get();let u=s.findIndex(m=>m._notFound);if(e.options.notFoundMode!=="root"&&u>=0){const m=await Zs(e,s,void 0,i,u);s[u]._notFound=void 0,s[m]._notFound=!0,u=m}let l=u<0?s.length:u+1,c=0;for(;c<l&&c!==u;){const m=s[c],S=n[2][c],C=a[c];if(S?.id!==m.id||S.status!=="success"||m.preload||C?.id!==m.id||C.status!=="success"||(c++,S._notFound||C._notFound))break}const h=[],d=n[6]??0;let f=d?Promise.resolve(s[d-1]):void 0;const p=()=>{for(let m=d;m<l&&!i.aborted;m++)f=Vl(e,r,m,h,f,n,c)},g=await Hl(e,r,n,l,p,c);if(g){if(n[4]=!0,l=g[0],g[1][0]===cs){const m=await Zs(e,s,g,i);g[2]=m,l=Math.min(l,m+1)}else g[1][0]>=K&&(l=0);p()}if(!i.aborted&&!n[3]){const m=[];for(const[S,C]of e._flights??[])C[2]||(e._flights.delete(S),m.push(C[1]));for(const S of m)S.abort()}const v=so(e,r,h,n[0],Cr(h,g,r[2]),n[7]);r[2]?.length&&(r[3]=Cr(r[2],void 0,void 0,v.then(m=>Rt(m)?0:kn(s).length,()=>0))),o=await v}catch(a){if(Le(e,r),a===i&&i.aborted)return Te;throw a}return Rt(o)?o:no(e,o,i,n[6]===s.length?n[6]:0)}function en(e,t){if(e._tx!==t)return;const s=t[3],n=e.stores.matches.get();let r=e._pending;for(let i=0;i<s.length;i++){const o=s[i],a=o.status==="success"&&!o._notFound,u=n[i]?.id===o.id&&n[i]?.status==="pending";if(a&&!u)continue;const l=Be(e,o),c=a||o.invalid?0:l.options.pendingMs??e.options.defaultPendingMs,h=l.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=l.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,u?Date.now()+d:t[4]+c,void 0,u||void 0,h]),r[4]&&!f&&r[5]===h)return;if(r[5]=h,!r[4]){clearTimeout(r[3]);const v=r[2]-Date.now();if(v>0){r[3]=setTimeout(()=>en(e,t),v);return}r[2]=0}const p=s.map(v=>({...v,_flight:void 0}));p[i].status="pending";const g=r[4]=e.startTransition(()=>e.stores.setMatches(p),p).then(v=>(v&&e._pending===r&&r[4]===g&&!r[2]&&(r[2]=Date.now()+d),v));return}}function lt(e,t){const s=e._pending;(e._tx===t||!e._tx?.[3].some(n=>n.id===s?.[1]))&&(clearTimeout(s?.[3]),e._pending=void 0)}async function br(e,t){const s=e._pending;if(!s)return;clearTimeout(s[3]);const n=s[2]-Date.now();if(!s[4]||n<=0||!kn(t[3]).some(i=>i.id===s[1]))return;let r;try{await $e(new Promise(i=>{r=setTimeout(i,n)}),t[0].signal)}catch{}clearTimeout(r)}function io(e,t){e._committed=t,e.stores.setMatches(t)}function ql(e,t,s,n){const r=e._committed,i=e._lifecycleEnd,o=e._cache;for(const c of s)c.preload=!1,n&&(c._assetEnd=void 0);const a=kn(s).length,u=new Map;{const c=Date.now(),h=new Set;for(let d=0;d<s.length;d++){const f=s[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)||u.set(d.id,o.get(d.id)===d?d:{...d,_flight:void 0,isFetching:!1,context:{}})}}t[3]=[],e._cache=u;const l=e._lifecycleEnd=Fl(s);io(e,s),W(e,[...o.values(),...r].filter(c=>c._flight&&u.get(c.id)!==c),s),Ll(e,r,s,i,l,t)}async function Ft(e,t){let s=e._tx;for(;s&&s!==t;)t=s,await s[5],s=e._tx}function oo(e,t,s){const n=s[1].options,r=s[2];if(!r)return e.navigate({...n,replace:!0,ignoreBlocker:!0});if(n.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:n.viewTransition,replace:!0,resetScroll:n.resetScroll,hashScrollIntoView:n.hashScrollIntoView,ignoreBlocker:!0});return queueMicrotask(()=>{e._pendingLocation===r&&(e._pendingLocation=void 0)}),i}async function Kl(e,t,s,n,r){const i=s.map(u=>({...u}));Nn(i);for(const u of n)me(e,i[u[0]]),i[u[0]]=u[3];const o=[t[2],i];let a;try{a=await so(e,o,n,t[0],r)}catch(u){throw W(e,i),u}if(Rt(a)){W(e,i),a[0]===K&&e._tx===t&&e._committed===s&&await oo(e,t,a);return}if(await no(e,a,t[0].signal),e._tx!==t||e._committed!==s){W(e,i);return}for(const u of i){const l=e._cache.get(u.id);l?._flight&&l._flight===u._flight&&(e._cache.delete(u.id),me(e,l))}io(e,i),W(e,s,i)}async function Ql(e,t,s,n,r,i){const o=await ro(e,t[2],t[3],[t[0],t[1],e._committed,void 0,r,s,i,n]);if(Rt(o)){const h=o[0]===K&&e._tx===t;if((!h||o[1].options.reloadDocument)&&lt(e,t),W(e,t[3]),t[3]=[],!h)return;if(e._tx!==t){lt(e,t);return}await oo(e,t,o);return}const a=o[1];if(e._tx===t&&await br(e,t),e._tx!==t){lt(e,t),W(e,a),Le(e,o);return}const u=t[2],l=us(u,e.stores.resolvedLocation.get()),c=o[2];await e.startViewTransition(async()=>{if(e._tx===t&&await br(e,t),e._tx!==t){lt(e,t),W(e,a),Le(e,o);return}const h=()=>{lt(e,t),ql(e,t,a,i),e._tx===t&&(e.emit({type:"onLoad",...l}),e._tx===t&&e.emit({type:"onBeforeRouteMount",...l}))},d=await e.startTransition(h,a);if(e._tx!==t){Le(e,o);return}c?.length&&Kl(e,t,a,c,o[3]).catch(console.error),e.batch(()=>{e.stores.resolvedLocation.set(u),e.stores.status.set("idle"),e._tx===t&&e.emit({type:"onResolved",...l}),d&&e._tx===t&&e.emit({type:"onRendered",...l})}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0)})}async function Wl(e,t){const s=e._tx,n=e.stores.resolvedLocation.get(),r=n??e.stores.location.get(),i=e.latestLocation,o=e._pendingLocation,a=o?.href===i.href?o._redirects??0:0,u=e._handoff,l=u?.[0](),c=new AbortController,h=e._preflight;if(e._preflight=c,l||u?.[1](),h?.abort(),!c.signal.aborted){const b=us(i,n);e.emit({type:"onBeforeNavigate",...b}),c.signal.aborted||e.emit({type:"onBeforeLoad",...b})}if(c.signal.aborted){await Ft(e,s);return}const d=r.href===i.href;let f=c;const p=e.matchRoutes(i,{_controller:c});Nn(p);const g=l?u[1](p):void 0;if(g?f=l:l?.abort(),c.signal.aborted){W(e,p),await Ft(e,s);return}e._preflight=void 0;let v;const m=()=>Ql(e,C,d,()=>en(e,C),t?.sync,g),S=t?.sync?new Promise(b=>v=b):Promise.resolve().then(m),C=[f,a,i,p,Date.now(),S.then(()=>Ft(e,C))];if(e._tx=C,s){for(const b of e.stores.matches.get()){if(e._tx!==C)break;b.isFetching&&bt(e,b,!1)}s[0].abort(),W(e,s[3],C[3],!0)}if(e._tx!==C){W(e,C[3]),C[3]=[],v?.(),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))&&en(e,C),v?.(m()),await C[5]}async function Jl(e,t){let s=e.buildLocation(t);for(let n=0;;n++){const r=e._committed,i=new AbortController;let o,a,u;try{try{o=e.matchRoutes(s,{_controller:i}),Nn(o),a=(e._preloads??=new Map).set(i,o),u=await ro(e,s,o,[i,n,r,!0])}finally{a&&(a=a.delete(i),W(e,o)),i.abort()}if(!Rt(u))return u[1];if(!a||u.length<3)return;s=u[2]}catch(l){et(l)||console.error(l);return}}}var Xl="Error preloading route! ☝️",ao=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 s=this.options,n=!s?.path&&!s?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=ft:this.parentRoute||On();let r=n?ft:s?.path;r&&r!=="/"&&(r=zi(r));const i=s?.id||r,o=n?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=>Sl({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.")}},Yl=class extends ao{constructor(e){super(e)}},jn=class extends I.Component{constructor(...e){super(...e),this.state={error:0},this.reset=()=>{this.setState({error:0})}}static getDerivedStateFromProps(e,t){const s=e.getResetKey();return t.error&&t.resetKey!==s?{resetKey:s,error:0}:{resetKey:s}}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??Zl,{error:e[0],reset:this.reset}):this.props.children}};function Zl({error:e}){const[t,s]=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:()=>s(n=>!n),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 eu=()=>!0,tu=()=>!1;function su({children:e,fallback:t=null}){return(0,L.jsx)(I.Fragment,{children:lo()?e:t})}function lo(){return I.useSyncExternalStore(nu,eu,tu)}function nu(){return()=>{}}var uo=I.createContext(null);function Z(e){const t=I.useContext(uo);return t||void 0,t}var ds=I.createContext(void 0),ru=I.createContext(void 0);function iu({update:e,notify:t,unwatched:s}){return{link:n,unlink:r,propagate:i,checkDirty:o,shallowPropagate:a};function n(l,c,h){const d=c.depsTail;if(d!==void 0&&d.dep===l)return;const f=d!==void 0?d.nextDep:c.deps;if(f!==void 0&&f.dep===l){f.version=h,c.depsTail=f;return}const p=l.subsTail;if(p!==void 0&&p.version===h&&p.sub===c)return;const g=c.depsTail=l.subsTail={version:h,dep:l,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:l.subs=g}function r(l,c=l.sub){const h=l.dep,d=l.prevDep,f=l.nextDep,p=l.nextSub,g=l.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&&s(h),f}function i(l){let c=l.nextSub,h;e:do{const d=l.sub;let f=d.flags;if(f&60?f&12?f&4?!(f&48)&&u(l,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=(l=p).nextSub;g!==void 0&&(h={value:c,prev:h},c=g);continue}}if((l=c)!==void 0){c=l.nextSub;continue}for(;h!==void 0;)if(l=h.value,h=h.prev,l!==void 0){c=l.nextSub;continue e}break}while(!0)}function o(l,c){let h,d=0,f=!1;e:do{const p=l.dep,g=p.flags;if(c.flags&16)f=!0;else if((g&17)===17){if(e(p)){const v=p.subs;v.nextSub!==void 0&&a(v),f=!0}}else if((g&33)===33){(l.nextSub!==void 0||l.prevSub!==void 0)&&(h={value:l,prev:h}),l=p.deps,c=p,++d;continue}if(!f){const v=l.nextDep;if(v!==void 0){l=v;continue}}for(;d--;){const v=c.subs,m=v.nextSub!==void 0;if(m?(l=h.value,h=h.prev):l=v,f){if(e(c)){m&&a(v),c=l.sub;continue}f=!1}else c.flags&=-33;c=l.sub;const S=l.nextDep;if(S!==void 0){l=S;continue e}}return f}while(!0)}function a(l){do{const c=l.sub,h=c.flags;(h&48)===32&&(c.flags=h|16,(h&6)===2&&t(c))}while((l=l.nextSub)!==void 0)}function u(l,c){let h=c.depsTail;for(;h!==void 0;){if(h===l)return!0;h=h.prevDep}return!1}}function ou(e,t,s){const n=typeof e=="object",r=n?e:void 0;return{next:(n?e.next:e)?.bind(r),error:(n?e.error:t)?.bind(r),complete:(n?e.complete:s)?.bind(r)}}var tn=[],Xt=0,{link:wr,unlink:au,propagate:lu,checkDirty:co,shallowPropagate:Er}=iu({update(e){return e._update()},notify(e){tn[sn++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,rs(e))}}),Lt=0,sn=0,ce,nn=0;function uu(e){try{++nn,e()}finally{--nn||ho()}}function rs(e){const t=e.depsTail;let s=t!==void 0?t.nextDep:e.deps;for(;s!==void 0;)s=au(s,e)}function ho(){if(!(nn>0)){for(;Lt<sn;){const e=tn[Lt];tn[Lt++]=void 0,e.notify()}Lt=0,sn=0}}function _r(e,t){const s=typeof e=="function",n=e,r={_snapshot:s?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:s?0:1,get(){return ce!==void 0&&wr(r,ce,Xt),r._snapshot},subscribe(i){const o=ou(i),a={current:!1},u=cu(()=>{r.get(),a.current?o.next?.(r._snapshot):a.current=!0});return{unsubscribe:()=>{u.stop()}}},_update(i){const o=ce,a=t?.compare??Object.is;if(s)ce=r,++Xt,r.depsTail=void 0;else if(i===void 0)return!1;s&&(r.flags=5);try{const u=r._snapshot,l=typeof i=="function"?i(u):i===void 0&&s?n(u):i;return u===void 0||!a(u,l)?(r._snapshot=l,!0):!1}finally{ce=o,s&&(r.flags&=-5),rs(r)}}};return s?(r.flags=17,r.get=function(){const i=r.flags;if(i&16||i&32&&co(r.deps,r)){if(r._update()){const o=r.subs;o!==void 0&&Er(o)}}else i&32&&(r.flags=i&-33);return ce!==void 0&&wr(r,ce,Xt),r._snapshot}):r.set=function(i){if(r._update(i)){const o=r.subs;o!==void 0&&(lu(o),Er(o),ho())}},r}function cu(e){const t=()=>{const n=ce;ce=s,++Xt,s.depsTail=void 0,s.flags=6;try{return e()}finally{ce=n,s.flags&=-5,rs(s)}},s={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){const n=this.flags;n&16||n&32&&co(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,rs(this)}};return t(),s}var du=tt((e=>{var t=Cn();function s(d,f){return d===f&&(d!==0||1/d===1/f)||d!==d&&f!==f}var n=typeof Object.is=="function"?Object.is:s,r=t.useState,i=t.useEffect,o=t.useLayoutEffect,a=t.useDebugValue;function u(d,f){var p=f(),g=r({inst:{value:p,getSnapshot:f}}),v=g[0].inst,m=g[1];return o(function(){v.value=p,v.getSnapshot=f,l(v)&&m({inst:v})},[d,p,f]),i(function(){return l(v)&&m({inst:v}),d(function(){l(v)&&m({inst:v})})},[d]),a(p),p}function l(d){var f=d.getSnapshot;d=d.value;try{var p=f();return!n(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:u;e.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:h})),hu=tt(((e,t)=>{t.exports=du()})),fu=tt((e=>{var t=Cn(),s=hu();function n(c,h){return c===h&&(c!==0||1/c===1/h)||c!==c&&h!==h}var r=typeof Object.is=="function"?Object.is:n,i=s.useSyncExternalStore,o=t.useRef,a=t.useEffect,u=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(c,h,d,f,p){var g=o(null);if(g.current===null){var v={hasValue:!1,value:null};g.current=v}else v=g.current;g=u(function(){function S(y){if(!C){if(C=!0,b=y,y=f(y),p!==void 0&&v.hasValue){var _=v.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 m=i(c,g[0],g[1]);return a(function(){v.hasValue=!0,v.value=m},[m]),l(m),m}})),pu=tt(((e,t)=>{t.exports=fu()})),gu=pu();function mu(e,t){return e===t}function ye(e,t=n=>n,s){const n=s?.compare??mu,r=(0,I.useCallback)(o=>{const{unsubscribe:a}=e.subscribe(o);return a},[e]),i=(0,I.useCallback)(()=>e.get(),[e]);return(0,gu.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Tr={};function fo(e,t){const s=I.useRef();return n=>{const r=e?.select?e.select(n):n;return e?.structuralSharing??t.options.defaultStructuralSharing?s.current=we(s.current,r):r}}function Ue(e){const t=Z(),s=I.useContext(e.from?ru:ds),n=e.from??s,r=t.stores.getMatchStore(n),i=fo(e,t),o=ye(r,a=>a?i(a):Tr);if(o!==Tr)return o;(e.shouldThrow??!0)&&On()}function po(e){return Ue({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function go(e){const{select:t,...s}=e;return Ue({...s,select:n=>t?t(n.loaderDeps):n.loaderDeps})}function mo(e){return Ue({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const s=e.strict===!1?t.params:t._strictParams;return e.select?e.select(s):s}})}function vo(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 Gn(e){const t=Z();return I.useCallback(s=>t.navigate({...s,from:s.from??e?.from}),[e?.from,t])}function Gf(e){const t=Z(),s=Gn(),n=I.useRef(null);return Mn(()=>{n.current!==e&&(s(e),n.current=e)},[t,e,s]),null}function So(e){return Ue({...e,select:t=>e.select?e.select(t.context):t.context})}function vu(...e){const t=I.useRef(e),s=t.current;return e.forEach((n,r)=>{ve(s[r],n,!1,!0)||(s[r]=n)}),t.current}function Nt(e,t){e.preloadRoute(t).catch(s=>{console.warn(s),console.warn(Xl)})}var Su={compare:(e,t)=>e[0]===t[0]&&e[1]===t[1]};function yu(e,t){const s=typeof e=="string"&&yt(e);if(s)return t.has(s)?e:null}function Iu(e,t,s,n,r){const i=or(e.pathname,n),o=or(t.pathname,n);return(s?.exact?i!==o:!(i.startsWith(o)&&(i.length===o.length||i[o.length]==="/")))||(s?.includeSearch??!0)&&!ve(e.search,t.search,!s?.exact,s?.explicitUndefined)?!1:s?.includeHash?r&&e.hash===t.hash:!0}function Ru(e,t,s){const n=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:u,preloadDelay:l,hashScrollIntoView:c,replace:h,startTransition:d,resetScroll:f,viewTransition:p,ignoreBlocker:g,disabled:v,target:m,onClick:S,onBlur:C,onFocus:b,onMouseEnter:w,onMouseLeave:R,onTouchStart:y}=e,_=lo(),[O,T,A]=vu(e.search,e.params,o),[M,x]=I.useMemo(()=>[e,{...e}],[n,e.from,e._fromLocation,e.hash,e.to,O,T,e.state,e.mask,e.unsafeRelative]),P=I.useCallback($=>{const te=yu(a,n.protocolAllowlist);if(te!==void 0)return[te??void 0];M._fromLocation||(x._fromLocation=$);const Mt=n.buildLocation(x),ot=_u(Mt,n,v);return[ot,!v&&(!ot||yt(ot))?void 0:Iu($,Mt,A,n.basepath,_)]},[A,v,_,M,x,n,a]),[E,G]=ye(n.stores.location,P,Su),nt=G===void 0?E:void 0,rt=v||E===void 0,_t=I.useRef(!1),fe=e.reloadDocument||nt||rt?!1:u??n.options.defaultPreload,it=l??n.options.defaultPreloadDelay??0,He=I.useCallback($=>{const te=$?.isIntersecting;if(!(te??fe==="intent")){te===!1&&_s(r);return}if(!it){Nt(n,M);return}gt.has(r)||gt.set(r,setTimeout(()=>{gt.delete(r),Nt(n,M)},it))},[n,M,r,fe,it]);I.useEffect(()=>{fe==="render"&&!_t.current&&(_t.current=!0,Nt(n,M));let $;return fe==="viewport"&&r.current&&typeof IntersectionObserver=="function"&&($=new IntersectionObserver(te=>He(te.pop()),{rootMargin:"100px"}),$.observe(r.current)),()=>{$?.disconnect(),_s(r)}},[n,M,fe,He,r]);const ee=wu(e,s);if(ee.ref=t?i:r,nt)return ee.href=nt,ee;const vs=$=>{const te=m??$.currentTarget.getAttribute("target");!rt&&!($.metaKey||$.altKey||$.ctrlKey||$.shiftKey)&&!$.defaultPrevented&&(!te||te==="_self")&&$.button===0&&($.preventDefault(),n.navigate({...M,replace:h,resetScroll:f,hashScrollIntoView:c,startTransition:d,viewTransition:p,ignoreBlocker:g}))},Ss=()=>{fe==="intent"&&Nt(n,M)},Tt=()=>{fe==="intent"&&_s(r)};return ee.onClick=Qe(S,vs),ee.onBlur=Qe(C,Tt),ee.onFocus=Qe(b,He),ee.onMouseEnter=Qe(w,He),ee.onMouseLeave=Qe(R,Tt),ee.onTouchStart=Qe(y,Ss),Eu(ee,e,G,E,rt,s)}var Cu={},bu={className:"active"},yo=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 wu(e,t){const s={};for(const n in e)yo.has(n)||n==="type"&&t!==void 0||n==="disabled"&&t==="a"||(s[n]=e[n]);return s}function Eu(e,t,s,n,r,i){const{activeProps:o,inactiveProps:a,className:u,style:l,target:c}=t,h=$i(s?o:a,{})??(s?bu:Cu);Object.assign(e,h),e.href=n,i!=="a"&&(e.disabled=r),e.target=c;const d=h.style;(l||d)&&(e.style=l&&d?{...l,...d}:l||d);const f=h.className;return(u||f)&&(e.className=u?f?`${u} ${f}`:u:f),r&&(e.role="link",e["aria-disabled"]=!0),s&&(e["data-status"]="active",e["aria-current"]="page"),e}var gt=new WeakMap,_s=e=>{clearTimeout(gt.get(e)),gt.delete(e)},Qe=(e,t)=>e?s=>s.defaultPrevented||(e(s),s.defaultPrevented||t(s)):t;function _u(e,t,s){if(s)return;const n=e.maskedLocation??e,r=n.external?n.publicHref:t.history.createHref(n.publicHref)||"/";if(!((n.external||r!==n.publicHref)&&Hi(r,t.protocolAllowlist)))return r}var Io=I.memo(I.forwardRef((e,t)=>{const s=e._asChild||"a",n=Ru(e,t,s),r=typeof e.children=="function"?e.children({isActive:n["data-status"]==="active"}):e.children;return I.createElement(s,n,r)}),Tu);function Tu(e,t){let s=0;for(const n in t)if(s++,e[n]!==t[n]&&(!yo.has(n)||!ve(e[n],t[n],!1,!0)))return!1;for(const n in e)s--;return s===0}var Mu=class extends ao{constructor(e){super(e),this.useMatch=t=>Ue({...t,from:this.id}),this.useRouteContext=t=>So({...t,from:this.id}),this.useSearch=t=>vo({...t,from:this.id}),this.useParams=t=>mo({...t,from:this.id}),this.useLoaderDeps=t=>go({...t,from:this.id}),this.useLoaderData=t=>po({...t,from:this.id}),this.useNavigate=()=>Gn({from:this.fullPath}),this.Link=I.forwardRef((t,s)=>(0,L.jsx)(Io,{ref:s,from:this.fullPath,...t}))}};function Au(e){return new Mu(e)}var Ou=class extends Yl{constructor(e){super(e),this.useMatch=t=>Ue({...t,from:this.id}),this.useRouteContext=t=>So({...t,from:this.id}),this.useSearch=t=>vo({...t,from:this.id}),this.useParams=t=>mo({...t,from:this.id}),this.useLoaderDeps=t=>go({...t,from:this.id}),this.useLoaderData=t=>po({...t,from:this.id}),this.useNavigate=()=>Gn({from:this.fullPath}),this.Link=I.forwardRef((t,s)=>(0,L.jsx)(Io,{ref:s,from:this.fullPath,...t}))}};function $f(e){return new Ou(e)}function Bf(e){return t=>{const s=Au(t);return s.isRoot=!1,s}}function Uf(e,t){let s,n,r;const i=()=>(s||(r=void 0,s=e().then(a=>{s=void 0,o.preload=void 0,n=a[t??"default"]}).catch(a=>{s=void 0,r=a})),s),o=function(u){if(r){if(Ja(r)&&typeof sessionStorage<"u"){const l=`tanstack_router_reload:${r.message}`;if(!sessionStorage.getItem(l))throw sessionStorage.setItem(l,"1"),window.location.reload(),new Promise(()=>{})}throw r}if(!n)if(rr)rr(i());else throw i();return I.createElement(n,u)};return o.preload=i,o}function xu(e){const t=Z(),s=`not-found-${ye(t.stores.location,n=>n.pathname)}-${ye(t.stores.status)}`;return(0,L.jsx)(jn,{getResetKey:()=>s,onCatch:(n,r)=>{if(et(n))e.onCatch?.(n,r);else throw n},errorComponent:({error:n})=>{if(et(n))return e.fallback?.(n);throw n},children:e.children})}function Pu(){return(0,L.jsx)("p",{children:"Not Found"})}function Xe(e){return(0,L.jsx)(L.Fragment,{children:e.children})}function Ro(e,t,s){return t.options.notFoundComponent?(0,L.jsx)(t.options.notFoundComponent,{...s}):e.options.defaultNotFoundComponent?(0,L.jsx)(e.options.defaultNotFoundComponent,{...s}):(0,L.jsx)(Pu,{})}function hs(e,t){const s=t?.options.pendingComponent??e.options.defaultPendingComponent;return s?(0,L.jsx)(s,{}):null}var ku=(e,t)=>e[0]===t[0]&&e[1]===t[1],Co=(e,t,s)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||s===!1||s==="data-only"||!e.ssr,bo=I.memo(function({routeId:t}){const s=Z();return(0,L.jsx)(Fu,{router:s,match:ye(s.stores.getMatchStore(t))})});function Fu({router:e,match:t}){const s=e.routesById[t.routeId],n=hs(e,s),r=s.options.errorComponent??e.options.defaultErrorComponent,i=s.options.onCatch??e.options.defaultOnCatch,o=s.isRoot?s.options.notFoundComponent??e.options.notFoundRoute?.options.component:s.options.notFoundComponent,a=t.ssr===!1||t.ssr==="data-only",u=Co(e,s,t.ssr)&&(s.options.wrapInSuspense??n??(s.options.errorComponent?.preload||a))?I.Suspense:Xe,l=r?jn:Xe,c=o?xu:Xe;return(0,L.jsxs)(s.isRoot?s.options.shellComponent??Xe:Xe,{children:[(0,L.jsx)(ds.Provider,{value:t.routeId,children:(0,L.jsx)(u,{fallback:n,children:(0,L.jsx)(l,{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)(su,{fallback:n,children:(0,L.jsx)(Mr,{match:t})}):(0,L.jsx)(Mr,{match:t})})})})}),null]})}var Mr=I.memo(function({match:t}){const s=Z(),n=t.routeId,r=s.routesById[n],i=I.useMemo(()=>{const a=(r.options.remountDeps??s.options.defaultRemountDeps)?.({routeId:n,loaderDeps:t.loaderDeps,params:t._strictParams,search:t._strictSearch});return a?JSON.stringify(a):void 0},[n,t.loaderDeps,t._strictParams,t._strictSearch,r.options.remountDeps,s.options.defaultRemountDeps]),o=I.useMemo(()=>{const a=r.options.component??s.options.defaultComponent;return a?(0,L.jsx)(a,{},i):(0,L.jsx)(Lu,{})},[i,r.options.component,s.options.defaultComponent]);if(t.status==="pending"){if(s.ssr&&!Co(s,r,t.ssr))return o;if(s._tx)throw s._tx[5];return hs(s,r)}if(t.status==="notFound")return Ro(s,r,t.error);if(t.status==="error")throw t.error;return o}),Lu=I.memo(function(){const t=Z(),s=I.useContext(ds);let n,r,i;{const a=t.stores.getMatchStore(s);[n,r]=ye(a,u=>[!!u._notFound,u.error],{compare:ku}),i=ye(t.stores.ids,u=>u[u.indexOf(s)+1])}if(n)return Ro(t,t.routesById[s],r);if(!i)return null;const o=(0,L.jsx)(bo,{routeId:i});return s==="__root__"?(0,L.jsx)(I.Suspense,{fallback:hs(t),children:o}):o});function wo(e,t){const s=e[1];e.length=0,s?.(t)}function Nu({t:e}){const t=Z(),s=t._rendered??=[];return t.startTransition=(n,r)=>new Promise(i=>{wo(s,!1),s.push(r,i),e(t),I.startTransition(n)}),Mn(()=>{const n=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}),n;const o=t.stores.resolvedLocation.get();return o?.href===r.href&&o.state.__TSR_key===r.state.__TSR_key?s.push(t.stores.matches.get(),a=>{a&&t.emit({type:"onRendered",...us(o,o)})}):t._tx||t.load({sync:!0}).catch(console.error),n},[t,t.history]),null}function Du(){const e=Z(),t=e.routesById[ft],s=hs(e,t),n=e.ssr?Xe:I.Suspense,r=(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(Nu,{t:I.useState()[1]}),(0,L.jsx)(n,{fallback:s,children:(0,L.jsx)(ju,{})})]});return e.options.InnerWrap?(0,L.jsx)(e.options.InnerWrap,{children:r}):r}function ju(){const e=Z(),t=e._rendered,s=ye(e.stores.matches,o=>t[0]??o),n=s[0],r=n?.routeId;Mn(()=>{t[0]===s&&wo(t,!0)},[t,s]);const i=r?(0,L.jsx)(bo,{routeId:r}):null;return(0,L.jsx)(ds.Provider,{value:r,children:e.options.disableGlobalCatchBoundary?i:(0,L.jsx)(jn,{getResetKey:()=>n,onCatch:void 0,children:i})})}var Gu=e=>({createMutableStore:_r,createReadonlyStore:_r,batch:uu}),Hf=e=>new $u(e),$u=class extends Nl{constructor(e){super(e,Gu)}};function Bu({router:e,children:t,...s}){Bi(s)&&e.update({...e.options,...s,context:{...e.options.context,...s.context}});const n=(0,L.jsx)(uo.Provider,{value:e,children:t});return e.options.Wrap?(0,L.jsx)(e.options.Wrap,{children:n}):n}function zf({router:e,...t}){return(0,L.jsx)(Bu,{router:e,...t,children:(0,L.jsx)(Du,{})})}function Uu(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 s=!!(e.condition??!0),n=e.blockerFn;return{shouldBlockFn:async()=>s&&n!==void 0?await n():s,enableBeforeUnload:s,withResolver:n===void 0}}function Vf(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:r=!1,withResolver:i=!1}=Uu(e,t),o=Z(),{history:a}=o,[u,l]=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(m){const S=o.parseLocation(m),[,C,b]=o.getMatchedRoutes(S.pathname);return b===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:C,search:o.options.parseSearch(m.search)}:{routeId:b.id,fullPath:b.fullPath,pathname:S.pathname,params:C,search:o.options.parseSearch(m.search)}}const f=d(h.currentLocation),p=d(h.nextLocation);if(f.routeId==="__notFound__"&&p.routeId!=="__notFound__")return!1;const g=await s({action:h.action,current:f,next:p});if(!i)return g;if(!g)return!1;const v=await new Promise(m=>{l({status:"blocked",current:f,next:p,action:h.action,proceed:()=>m(!1),reset:()=>m(!0)})});return l({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),v};return r?void 0:a.block({blockerFn:c,enableBeforeUnload:n})},[s,n,r,i,a,o]),u}function qf(e){const t=Z();return ye(t.stores.location,fo(e,t))}function Ce(e,t){return typeof e=="function"?e(t):e}function Y(e,t){return s=>{t.setState(n=>({...n,[e]:Ce(s,n[e])}))}}function fs(e){return e instanceof Function}function Hu(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function zu(e,t){const s=[],n=r=>{r.forEach(i=>{s.push(i);const o=t(i);o!=null&&o.length&&n(o)})};return n(e),s}function k(e,t,s){let n=[],r;return i=>{let o;s.key&&s.debug&&(o=Date.now());const a=e(i);if(!(a.length!==n.length||a.some((l,c)=>n[c]!==l)))return r;n=a;let u;if(s.key&&s.debug&&(u=Date.now()),r=t(...a),s==null||s.onChange==null||s.onChange(r),s.key&&s.debug&&s!=null&&s.debug()){const l=Math.round((Date.now()-o)*100)/100,c=Math.round((Date.now()-u)*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(l,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%);`,s?.key)}return r}}function F(e,t,s,n){return{debug:()=>{var r;return(r=e?.debugAll)!=null?r:e[t]},key:!1,onChange:n}}function Vu(e,t,s,n){const r=()=>{var o;return(o=i.getValue())!=null?o:e.options.renderFallbackValue},i={id:`${t.id}_${s.id}`,row:t,column:s,getValue:()=>t.getValue(n),renderValue:r,getContext:k(()=>[e,s,t,i],(o,a,u,l)=>({table:o,column:a,row:u,cell:l,getValue:l.getValue,renderValue:l.renderValue}),F(e.options,"debugCells","cell.getContext"))};return e._features.forEach(o=>{o.createCell==null||o.createCell(i,s,t,e)},{}),i}function qu(e,t,s,n){var r,i;const o={...e._getDefaultColumnDef(),...t},a=o.accessorKey;let u=(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,l;if(o.accessorFn?l=o.accessorFn:a&&(a.includes(".")?l=h=>{let d=h;for(const p of a.split(".")){var f;d=(f=d)==null?void 0:f[p]}return d}:l=h=>h[o.accessorKey]),!u)throw new Error;let c={id:`${String(u)}`,accessorFn:l,parent:n,depth:s,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,s){var n;let r={id:(n=s.id)!=null?n:t.id,column:t,index:s.index,isPlaceholder:!!s.isPlaceholder,placeholderId:s.placeholderId,depth:s.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 Ku={createTable:e=>{e.getHeaderGroups=k(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n,r)=>{var i,o;const a=(i=n?.map(c=>s.find(h=>h.id===c)).filter(Boolean))!=null?i:[],u=(o=r?.map(c=>s.find(h=>h.id===c)).filter(Boolean))!=null?o:[],l=s.filter(c=>!(n!=null&&n.includes(c.id))&&!(r!=null&&r.includes(c.id)));return Dt(t,[...a,...l,...u],e)},F(e.options,z,"getHeaderGroups")),e.getCenterHeaderGroups=k(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n,r)=>(s=s.filter(i=>!(n!=null&&n.includes(i.id))&&!(r!=null&&r.includes(i.id))),Dt(t,s,e,"center")),F(e.options,z,"getCenterHeaderGroups")),e.getLeftHeaderGroups=k(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,s,n)=>{var r;return Dt(t,(r=n?.map(i=>s.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,s,n)=>{var r;return Dt(t,(r=n?.map(i=>s.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(s=>s.headers).flat(),F(e.options,z,"getFlatHeaders")),e.getLeftFlatHeaders=k(()=>[e.getLeftHeaderGroups()],t=>t.map(s=>s.headers).flat(),F(e.options,z,"getLeftFlatHeaders")),e.getCenterFlatHeaders=k(()=>[e.getCenterHeaderGroups()],t=>t.map(s=>s.headers).flat(),F(e.options,z,"getCenterFlatHeaders")),e.getRightFlatHeaders=k(()=>[e.getRightHeaderGroups()],t=>t.map(s=>s.headers).flat(),F(e.options,z,"getRightFlatHeaders")),e.getCenterLeafHeaders=k(()=>[e.getCenterFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),F(e.options,z,"getCenterLeafHeaders")),e.getLeftLeafHeaders=k(()=>[e.getLeftFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),F(e.options,z,"getLeftLeafHeaders")),e.getRightLeafHeaders=k(()=>[e.getRightFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),F(e.options,z,"getRightLeafHeaders")),e.getLeafHeaders=k(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,s,n)=>{var r,i,o,a,u,l;return[...(r=(i=t[0])==null?void 0:i.headers)!=null?r:[],...(o=(a=s[0])==null?void 0:a.headers)!=null?o:[],...(u=(l=n[0])==null?void 0:l.headers)!=null?u:[]].map(c=>c.getLeafHeaders()).flat()},F(e.options,z,"getLeafHeaders"))}};function Dt(e,t,s,n){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 u=[];const l=(h,d)=>{const f={depth:d,id:[n,`${d}`].filter(Boolean).join("_"),headers:[]},p=[];h.forEach(g=>{const v=[...p].reverse()[0],m=g.column.depth===f.depth;let S,C=!1;if(m&&g.column.parent?S=g.column.parent:(S=g.column,C=!0),v&&v?.column===S)v.subHeaders.push(g);else{const b=Ar(s,S,{id:[n,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}),u.push(f),d>0&&l(p,d-1)};l(t.map((h,d)=>Ar(s,h,{depth:o,index:d})),o-1),u.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(m=>{let{colSpan:S,rowSpan:C}=m;f+=S,g.push(C)})):f=1;const v=Math.min(...g);return p=p+v,d.colSpan=f,d.rowSpan=p,{colSpan:f,rowSpan:p}});return c((r=(i=u[0])==null?void 0:i.headers)!=null?r:[]),u}var Qu=(e,t,s,n,r,i,o)=>{let a={id:t,index:n,original:s,depth:r,parentId:o,_valuesCache:{},_uniqueValuesCache:{},getValue:u=>{if(a._valuesCache.hasOwnProperty(u))return a._valuesCache[u];const l=e.getColumn(u);if(l!=null&&l.accessorFn)return a._valuesCache[u]=l.accessorFn(a.original,n),a._valuesCache[u]},getUniqueValues:u=>{if(a._uniqueValuesCache.hasOwnProperty(u))return a._uniqueValuesCache[u];const l=e.getColumn(u);if(l!=null&&l.accessorFn)return l.columnDef.getUniqueValues?(a._uniqueValuesCache[u]=l.columnDef.getUniqueValues(a.original,n),a._uniqueValuesCache[u]):(a._uniqueValuesCache[u]=[a.getValue(u)],a._uniqueValuesCache[u])},renderValue:u=>{var l;return(l=a.getValue(u))!=null?l:e.options.renderFallbackValue},subRows:i??[],getLeafRows:()=>zu(a.subRows,u=>u.subRows),getParentRow:()=>a.parentId?e.getRow(a.parentId,!0):void 0,getParentRows:()=>{let u=[],l=a;for(;;){const c=l.getParentRow();if(!c)break;u.push(c),l=c}return u.reverse()},getAllCells:k(()=>[e.getAllLeafColumns()],u=>u.map(l=>Vu(e,a,l,l.id)),F(e.options,"debugRows","getAllCells")),_getAllCellsByColumnId:k(()=>[a.getAllCells()],u=>u.reduce((l,c)=>(l[c.column.id]=c,l),{}),F(e.options,"debugRows","getAllCellsByColumnId"))};for(let u=0;u<e._features.length;u++){const l=e._features[u];l==null||l.createRow==null||l.createRow(a,e)}return a},Wu={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()}}},Eo=(e,t,s)=>{var n,r;const i=s==null||(n=s.toString())==null?void 0:n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(i))};Eo.autoRemove=e=>oe(e);var _o=(e,t,s)=>{var n;return!!(!((n=e.getValue(t))==null||(n=n.toString())==null)&&n.includes(s))};_o.autoRemove=e=>oe(e);var To=(e,t,s)=>{var n;return((n=e.getValue(t))==null||(n=n.toString())==null?void 0:n.toLowerCase())===s?.toLowerCase()};To.autoRemove=e=>oe(e);var Mo=(e,t,s)=>{var n;return(n=e.getValue(t))==null?void 0:n.includes(s)};Mo.autoRemove=e=>oe(e);var Ao=(e,t,s)=>!s.some(n=>{var r;return!((r=e.getValue(t))!=null&&r.includes(n))});Ao.autoRemove=e=>oe(e)||!(e!=null&&e.length);var Oo=(e,t,s)=>s.some(n=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)});Oo.autoRemove=e=>oe(e)||!(e!=null&&e.length);var xo=(e,t,s)=>e.getValue(t)===s;xo.autoRemove=e=>oe(e);var Po=(e,t,s)=>e.getValue(t)==s;Po.autoRemove=e=>oe(e);var $n=(e,t,s)=>{let[n,r]=s;const i=e.getValue(t);return i>=n&&i<=r};$n.resolveFilterValue=e=>{let[t,s]=e,n=typeof t!="number"?parseFloat(t):t,r=typeof s!="number"?parseFloat(s):s,i=t===null||Number.isNaN(n)?-1/0:n,o=s===null||Number.isNaN(r)?1/0:r;if(i>o){const a=i;i=o,o=a}return[i,o]};$n.autoRemove=e=>oe(e)||oe(e[0])&&oe(e[1]);var ge={includesString:Eo,includesStringSensitive:_o,equalsString:To,arrIncludes:Mo,arrIncludesAll:Ao,arrIncludesSome:Oo,equals:xo,weakEquals:Po,inNumberRange:$n};function oe(e){return e==null||e===""}var Ju={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:Y("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const s=t.getCoreRowModel().flatRows[0],n=s?.getValue(e.id);return typeof n=="string"?ge.includesString:typeof n=="number"?ge.inNumberRange:typeof n=="boolean"||n!==null&&typeof n=="object"?ge.equals:Array.isArray(n)?ge.arrIncludes:ge.weakEquals},e.getFilterFn=()=>{var s,n;return fs(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(s=(n=t.options.filterFns)==null?void 0:n[e.columnDef.filterFn])!=null?s:ge[e.columnDef.filterFn]},e.getCanFilter=()=>{var s,n,r;return((s=e.columnDef.enableColumnFilter)!=null?s:!0)&&((n=t.options.enableColumnFilters)!=null?n:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var s;return(s=t.getState().columnFilters)==null||(s=s.find(n=>n.id===e.id))==null?void 0:s.value},e.getFilterIndex=()=>{var s,n;return(s=(n=t.getState().columnFilters)==null?void 0:n.findIndex(r=>r.id===e.id))!=null?s:-1},e.setFilterValue=s=>{t.setColumnFilters(n=>{const r=e.getFilterFn(),i=n?.find(c=>c.id===e.id),o=Ce(s,i?i.value:void 0);if(Or(r,o,e)){var a;return(a=n?.filter(c=>c.id!==e.id))!=null?a:[]}const u={id:e.id,value:o};if(i){var l;return(l=n?.map(c=>c.id===e.id?u:c))!=null?l:[]}return n!=null&&n.length?[...n,u]:[u]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const s=e.getAllLeafColumns(),n=r=>{var i;return(i=Ce(t,r))==null?void 0:i.filter(o=>{const a=s.find(u=>u.id===o.id);return!(a&&Or(a.getFilterFn(),o.value,a))})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(n)},e.resetColumnFilters=t=>{var s,n;e.setColumnFilters(t?[]:(s=(n=e.initialState)==null?void 0:n.columnFilters)!=null?s:[])},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 Or(e,t,s){return(e&&e.autoRemove?e.autoRemove(t,s):!1)||typeof t>"u"||typeof t=="string"&&!t}var Xu=(e,t,s)=>s.reduce((n,r)=>{const i=r.getValue(e);return n+(typeof i=="number"?i:0)},0),Yu=(e,t,s)=>{let n;return s.forEach(r=>{const i=r.getValue(e);i!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}),n},Zu=(e,t,s)=>{let n;return s.forEach(r=>{const i=r.getValue(e);i!=null&&(n<i||n===void 0&&i>=i)&&(n=i)}),n},ec=(e,t,s)=>{let n,r;return s.forEach(i=>{const o=i.getValue(e);o!=null&&(n===void 0?o>=o&&(n=r=o):(n>o&&(n=o),r<o&&(r=o)))}),[n,r]},tc=(e,t)=>{let s=0,n=0;if(t.forEach(r=>{let i=r.getValue(e);i!=null&&(i=+i)>=i&&(++s,n+=i)}),s)return n/s},sc=(e,t)=>{if(!t.length)return;const s=t.map(i=>i.getValue(e));if(!Hu(s))return;if(s.length===1)return s[0];const n=Math.floor(s.length/2),r=s.sort((i,o)=>i-o);return s.length%2!==0?r[n]:(r[n-1]+r[n])/2},nc=(e,t)=>Array.from(new Set(t.map(s=>s.getValue(e))).values()),rc=(e,t)=>new Set(t.map(s=>s.getValue(e))).size,ic=(e,t)=>t.length,Ts={sum:Xu,min:Yu,max:Zu,extent:ec,mean:tc,median:sc,unique:nc,uniqueCount:rc,count:ic},oc={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,s;return(t=(s=e.getValue())==null||s.toString==null?void 0:s.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(s=>s!=null&&s.includes(e.id)?s.filter(n=>n!==e.id):[...s??[],e.id])},e.getCanGroup=()=>{var s,n;return((s=e.columnDef.enableGrouping)!=null?s:!0)&&((n=t.options.enableGrouping)!=null?n:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var s;return(s=t.getState().grouping)==null?void 0:s.includes(e.id)},e.getGroupedIndex=()=>{var s;return(s=t.getState().grouping)==null?void 0:s.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const s=e.getCanGroup();return()=>{s&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const s=t.getCoreRowModel().flatRows[0],n=s?.getValue(e.id);if(typeof n=="number")return Ts.sum;if(Object.prototype.toString.call(n)==="[object Date]")return Ts.extent},e.getAggregationFn=()=>{var s,n;if(!e)throw new Error;return fs(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(s=(n=t.options.aggregationFns)==null?void 0:n[e.columnDef.aggregationFn])!=null?s:Ts[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var s,n;e.setGrouping(t?[]:(s=(n=e.initialState)==null?void 0:n.grouping)!=null?s:[])},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=s=>{if(e._groupingValuesCache.hasOwnProperty(s))return e._groupingValuesCache[s];const n=t.getColumn(s);return n!=null&&n.columnDef.getGroupingValue?(e._groupingValuesCache[s]=n.columnDef.getGroupingValue(e.original),e._groupingValuesCache[s]):e.getValue(s)},e._groupingValuesCache={}},createCell:(e,t,s,n)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===s.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var r;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((r=s.subRows)!=null&&r.length)}}};function ac(e,t,s){if(!(t!=null&&t.length)||!s)return e;const n=e.filter(r=>!t.includes(r.id));return s==="remove"?n:[...t.map(r=>e.find(i=>i.id===r)).filter(Boolean),...n]}var lc={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:Y("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=k(s=>[mt(t,s)],s=>s.findIndex(n=>n.id===e.id),F(t.options,"debugColumns","getIndex")),e.getIsFirstColumn=s=>{var n;return((n=mt(t,s)[0])==null?void 0:n.id)===e.id},e.getIsLastColumn=s=>{var n;const r=mt(t,s);return((n=r[r.length-1])==null?void 0:n.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var s;e.setColumnOrder(t?[]:(s=e.initialState.columnOrder)!=null?s:[])},e._getOrderColumnsFn=k(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,s,n)=>r=>{let i=[];if(!(t!=null&&t.length))i=r;else{const o=[...t],a=[...r];for(;a.length&&o.length;){const u=o.shift(),l=a.findIndex(c=>c.id===u);l>-1&&i.push(a.splice(l,1)[0])}i=[...i,...a]}return ac(i,s,n)},F(e.options,"debugTable","_getOrderColumnsFn"))}},Ms=()=>({left:[],right:[]}),uc={getInitialState:e=>({columnPinning:Ms(),...e}),getDefaultOptions:e=>({onColumnPinningChange:Y("columnPinning",e)}),createColumn:(e,t)=>{e.pin=s=>{const n=e.getLeafColumns().map(r=>r.id).filter(Boolean);t.setColumnPinning(r=>{var i,o;if(s==="right"){var a,u;return{left:((a=r?.left)!=null?a:[]).filter(h=>!(n!=null&&n.includes(h))),right:[...((u=r?.right)!=null?u:[]).filter(h=>!(n!=null&&n.includes(h))),...n]}}if(s==="left"){var l,c;return{left:[...((l=r?.left)!=null?l:[]).filter(h=>!(n!=null&&n.includes(h))),...n],right:((c=r?.right)!=null?c:[]).filter(h=>!(n!=null&&n.includes(h)))}}return{left:((i=r?.left)!=null?i:[]).filter(h=>!(n!=null&&n.includes(h))),right:((o=r?.right)!=null?o:[]).filter(h=>!(n!=null&&n.includes(h)))}})},e.getCanPin=()=>e.getLeafColumns().some(s=>{var n,r,i;return((n=s.columnDef.enablePinning)!=null?n:!0)&&((r=(i=t.options.enableColumnPinning)!=null?i:t.options.enablePinning)!=null?r:!0)}),e.getIsPinned=()=>{const s=e.getLeafColumns().map(a=>a.id),{left:n,right:r}=t.getState().columnPinning,i=s.some(a=>n?.includes(a)),o=s.some(a=>r?.includes(a));return i?"left":o?"right":!1},e.getPinnedIndex=()=>{var s,n;const r=e.getIsPinned();return r?(s=(n=t.getState().columnPinning)==null||(n=n[r])==null?void 0:n.indexOf(e.id))!=null?s:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=k(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(s,n,r)=>{const i=[...n??[],...r??[]];return s.filter(o=>!i.includes(o.column.id))},F(t.options,"debugRows","getCenterVisibleCells")),e.getLeftVisibleCells=k(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(s,n)=>(n??[]).map(r=>s.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],(s,n)=>(n??[]).map(r=>s.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 s,n;return e.setColumnPinning(t?Ms():(s=(n=e.initialState)==null?void 0:n.columnPinning)!=null?s:Ms())},e.getIsSomeColumnsPinned=t=>{var s;const n=e.getState().columnPinning;if(!t){var r,i;return!!((r=n.left)!=null&&r.length||(i=n.right)!=null&&i.length)}return!!((s=n[t])!=null&&s.length)},e.getLeftLeafColumns=k(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,s)=>(s??[]).map(n=>t.find(r=>r.id===n)).filter(Boolean),F(e.options,"debugColumns","getLeftLeafColumns")),e.getRightLeafColumns=k(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,s)=>(s??[]).map(n=>t.find(r=>r.id===n)).filter(Boolean),F(e.options,"debugColumns","getRightLeafColumns")),e.getCenterLeafColumns=k(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n)=>{const r=[...s??[],...n??[]];return t.filter(i=>!r.includes(i.id))},F(e.options,"debugColumns","getCenterLeafColumns"))}};function cc(e){return e||(typeof document<"u"?document:null)}var jt={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},As=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),dc={getDefaultColumnDef:()=>jt,getInitialState:e=>({columnSizing:{},columnSizingInfo:As(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:Y("columnSizing",e),onColumnSizingInfoChange:Y("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var s,n,r;const i=t.getState().columnSizing[e.id];return Math.min(Math.max((s=e.columnDef.minSize)!=null?s:jt.minSize,(n=i??e.columnDef.size)!=null?n:jt.size),(r=e.columnDef.maxSize)!=null?r:jt.maxSize)},e.getStart=k(s=>[s,mt(t,s),t.getState().columnSizing],(s,n)=>n.slice(0,e.getIndex(s)).reduce((r,i)=>r+i.getSize(),0),F(t.options,"debugColumns","getStart")),e.getAfter=k(s=>[s,mt(t,s),t.getState().columnSizing],(s,n)=>n.slice(e.getIndex(s)+1).reduce((r,i)=>r+i.getSize(),0),F(t.options,"debugColumns","getAfter")),e.resetSize=()=>{t.setColumnSizing(s=>{let{[e.id]:n,...r}=s;return r})},e.getCanResize=()=>{var s,n;return((s=e.columnDef.enableResizing)!=null?s:!0)&&((n=t.options.enableColumnResizing)!=null?n:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let s=0;const n=r=>{if(r.subHeaders.length)r.subHeaders.forEach(n);else{var i;s+=(i=r.column.getSize())!=null?i:0}};return n(e),s},e.getStart=()=>{if(e.index>0){const s=e.headerGroup.headers[e.index-1];return s.getStart()+s.getSize()}return 0},e.getResizeHandler=s=>{const n=t.getColumn(e.column.id),r=n?.getCanResize();return i=>{if(!n||!r||(i.persist==null||i.persist(),Os(i)&&i.touches&&i.touches.length>1))return;const o=e.getSize(),a=e?e.getLeafHeaders().map(m=>[m.column.id,m.column.getSize()]):[[n.id,n.getSize()]],u=Os(i)?Math.round(i.touches[0].clientX):i.clientX,l={},c=(m,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,A]=O;l[T]=Math.round(Math.max(A+A*_,0)*100)/100}),{...C,deltaOffset:y,deltaPercentage:_}}),(t.options.columnResizeMode==="onChange"||m==="end")&&t.setColumnSizing(C=>({...C,...l})))},h=m=>c("move",m),d=m=>{c("end",m),t.setColumnSizingInfo(S=>({...S,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},f=cc(s),p={moveHandler:m=>h(m.clientX),upHandler:m=>{f?.removeEventListener("mousemove",p.moveHandler),f?.removeEventListener("mouseup",p.upHandler),d(m.clientX)}},g={moveHandler:m=>(m.cancelable&&(m.preventDefault(),m.stopPropagation()),h(m.touches[0].clientX),!1),upHandler:m=>{var S;f?.removeEventListener("touchmove",g.moveHandler),f?.removeEventListener("touchend",g.upHandler),m.cancelable&&(m.preventDefault(),m.stopPropagation()),d((S=m.touches[0])==null?void 0:S.clientX)}},v=hc()?{passive:!1}:!1;Os(i)?(f?.addEventListener("touchmove",g.moveHandler,v),f?.addEventListener("touchend",g.upHandler,v)):(f?.addEventListener("mousemove",p.moveHandler,v),f?.addEventListener("mouseup",p.upHandler,v)),t.setColumnSizingInfo(m=>({...m,startOffset:u,startSize:o,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:n.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 s;e.setColumnSizing(t?{}:(s=e.initialState.columnSizing)!=null?s:{})},e.resetHeaderSizeInfo=t=>{var s;e.setColumnSizingInfo(t?As():(s=e.initialState.columnSizingInfo)!=null?s:As())},e.getTotalSize=()=>{var t,s;return(t=(s=e.getHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,s;return(t=(s=e.getLeftHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,s;return(t=(s=e.getCenterHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,s;return(t=(s=e.getRightHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0}}},Gt=null;function hc(){if(typeof Gt=="boolean")return Gt;let e=!1;try{const t={get passive(){return e=!0,!1}},s=()=>{};window.addEventListener("test",s,t),window.removeEventListener("test",s)}catch{e=!1}return Gt=e,Gt}function Os(e){return e.type==="touchstart"}var fc={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:Y("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=s=>{e.getCanHide()&&t.setColumnVisibility(n=>({...n,[e.id]:s??!e.getIsVisible()}))},e.getIsVisible=()=>{var s,n;const r=e.columns;return(s=r.length?r.some(i=>i.getIsVisible()):(n=t.getState().columnVisibility)==null?void 0:n[e.id])!=null?s:!0},e.getCanHide=()=>{var s,n;return((s=e.columnDef.enableHiding)!=null?s:!0)&&((n=t.options.enableHiding)!=null?n:!0)},e.getToggleVisibilityHandler=()=>s=>{e.toggleVisibility==null||e.toggleVisibility(s.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=k(()=>[e.getAllCells(),t.getState().columnVisibility],s=>s.filter(n=>n.column.getIsVisible()),F(t.options,"debugRows","_getAllVisibleCells")),e.getVisibleCells=k(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(s,n,r)=>[...s,...n,...r],F(t.options,"debugRows","getVisibleCells"))},createTable:e=>{const t=(s,n)=>k(()=>[n(),n().filter(r=>r.getIsVisible()).map(r=>r.id).join("_")],r=>r.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),F(e.options,"debugColumns",s));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=s=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(s),e.resetColumnVisibility=s=>{var n;e.setColumnVisibility(s?{}:(n=e.initialState.columnVisibility)!=null?n:{})},e.toggleAllColumnsVisible=s=>{var n;s=(n=s)!=null?n:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((r,i)=>({...r,[i.id]:s||!(i.getCanHide!=null&&i.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(s=>!(s.getIsVisible!=null&&s.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(s=>s.getIsVisible==null?void 0:s.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>s=>{var n;e.toggleAllColumnsVisible((n=s.target)==null?void 0:n.checked)}}};function mt(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}var pc={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()}}},gc={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:Y("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var s;const n=(s=e.getCoreRowModel().flatRows[0])==null||(s=s._getAllCellsByColumnId()[t.id])==null?void 0:s.getValue();return typeof n=="string"||typeof n=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var s,n,r,i;return((s=e.columnDef.enableGlobalFilter)!=null?s:!0)&&((n=t.options.enableGlobalFilter)!=null?n:!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,s;const{globalFilterFn:n}=e.options;return fs(n)?n:n==="auto"?e.getGlobalAutoFilterFn():(t=(s=e.options.filterFns)==null?void 0:s[n])!=null?t:ge[n]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},mc={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:Y("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,s=!1;e._autoResetExpanded=()=>{var n,r;if(!t){e._queue(()=>{t=!0});return}if((n=(r=e.options.autoResetAll)!=null?r:e.options.autoResetExpanded)!=null?n:!e.options.manualExpanding){if(s)return;s=!0,e._queue(()=>{e.resetExpanded(),s=!1})}},e.setExpanded=n=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(n),e.toggleAllRowsExpanded=n=>{n??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=n=>{var r,i;e.setExpanded(n?{}:(r=(i=e.initialState)==null?void 0:i.expanded)!=null?r:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(n=>n.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>n=>{n.persist==null||n.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const n=e.getState().expanded;return n===!0||Object.values(n).some(Boolean)},e.getIsAllRowsExpanded=()=>{const n=e.getState().expanded;return typeof n=="boolean"?n===!0:!(!Object.keys(n).length||e.getRowModel().flatRows.some(r=>!r.getIsExpanded()))},e.getExpandedDepth=()=>{let n=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(r=>{const i=r.split(".");n=Math.max(n,i.length)}),n},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=s=>{t.setExpanded(n=>{var r;const i=n===!0?!0:!!(n!=null&&n[e.id]);let o={};if(n===!0?Object.keys(t.getRowModel().rowsById).forEach(a=>{o[a]=!0}):o=n,s=(r=s)!=null?r:!i,!i&&s)return{...o,[e.id]:!0};if(i&&!s){const{[e.id]:a,...u}=o;return u}return n})},e.getIsExpanded=()=>{var s;const n=t.getState().expanded;return!!((s=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?s:n===!0||n?.[e.id])},e.getCanExpand=()=>{var s,n,r;return(s=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?s:((n=t.options.enableExpanding)!=null?n:!0)&&!!((r=e.subRows)!=null&&r.length)},e.getIsAllParentsExpanded=()=>{let s=!0,n=e;for(;s&&n.parentId;)n=t.getRow(n.parentId,!0),s=n.getIsExpanded();return s},e.getToggleExpandedHandler=()=>{const s=e.getCanExpand();return()=>{s&&e.toggleExpanded()}}}},rn=0,on=10,xs=()=>({pageIndex:rn,pageSize:on}),vc={getInitialState:e=>({...e,pagination:{...xs(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:Y("pagination",e)}),createTable:e=>{let t=!1,s=!1;e._autoResetPageIndex=()=>{var n,r;if(!t){e._queue(()=>{t=!0});return}if((n=(r=e.options.autoResetAll)!=null?r:e.options.autoResetPageIndex)!=null?n:!e.options.manualPagination){if(s)return;s=!0,e._queue(()=>{e.resetPageIndex(),s=!1})}},e.setPagination=n=>{const r=i=>Ce(n,i);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(r)},e.resetPagination=n=>{var r;e.setPagination(n?xs():(r=e.initialState.pagination)!=null?r:xs())},e.setPageIndex=n=>{e.setPagination(r=>{let i=Ce(n,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=n=>{var r,i;e.setPageIndex(n?rn:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageIndex)!=null?r:rn)},e.resetPageSize=n=>{var r,i;e.setPageSize(n?on:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageSize)!=null?r:on)},e.setPageSize=n=>{e.setPagination(r=>{const i=Math.max(1,Ce(n,r.pageSize)),o=r.pageSize*r.pageIndex,a=Math.floor(o/i);return{...r,pageIndex:a,pageSize:i}})},e.setPageCount=n=>e.setPagination(r=>{var i;let o=Ce(n,(i=e.options.pageCount)!=null?i:-1);return typeof o=="number"&&(o=Math.max(-1,o)),{...r,pageCount:o}}),e.getPageOptions=k(()=>[e.getPageCount()],n=>{let r=[];return n&&n>0&&(r=[...new Array(n)].fill(null).map((i,o)=>o)),r},F(e.options,"debugTable","getPageOptions")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:n}=e.getState().pagination,r=e.getPageCount();return r===-1?!0:r===0?!1:n<r-1},e.previousPage=()=>e.setPageIndex(n=>n-1),e.nextPage=()=>e.setPageIndex(n=>n+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 n;return(n=e.options.pageCount)!=null?n:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var n;return(n=e.options.rowCount)!=null?n:e.getPrePaginationRowModel().rows.length}}},Ps=()=>({top:[],bottom:[]}),Sc={getInitialState:e=>({rowPinning:Ps(),...e}),getDefaultOptions:e=>({onRowPinningChange:Y("rowPinning",e)}),createRow:(e,t)=>{e.pin=(s,n,r)=>{const i=n?e.getLeafRows().map(u=>{let{id:l}=u;return l}):[],o=r?e.getParentRows().map(u=>{let{id:l}=u;return l}):[],a=new Set([...o,e.id,...i]);t.setRowPinning(u=>{var l,c;if(s==="bottom"){var h,d;return{top:((h=u?.top)!=null?h:[]).filter(g=>!(a!=null&&a.has(g))),bottom:[...((d=u?.bottom)!=null?d:[]).filter(g=>!(a!=null&&a.has(g))),...Array.from(a)]}}if(s==="top"){var f,p;return{top:[...((f=u?.top)!=null?f:[]).filter(g=>!(a!=null&&a.has(g))),...Array.from(a)],bottom:((p=u?.bottom)!=null?p:[]).filter(g=>!(a!=null&&a.has(g)))}}return{top:((l=u?.top)!=null?l:[]).filter(g=>!(a!=null&&a.has(g))),bottom:((c=u?.bottom)!=null?c:[]).filter(g=>!(a!=null&&a.has(g)))}})},e.getCanPin=()=>{var s;const{enableRowPinning:n,enablePinning:r}=t.options;return typeof n=="function"?n(e):(s=n??r)!=null?s:!0},e.getIsPinned=()=>{const s=[e.id],{top:n,bottom:r}=t.getState().rowPinning,i=s.some(a=>n?.includes(a)),o=s.some(a=>r?.includes(a));return i?"top":o?"bottom":!1},e.getPinnedIndex=()=>{var s,n;const r=e.getIsPinned();if(!r)return-1;const i=(s=r==="top"?t.getTopRows():t.getBottomRows())==null?void 0:s.map(o=>{let{id:a}=o;return a});return(n=i?.indexOf(e.id))!=null?n:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var s,n;return e.setRowPinning(t?Ps():(s=(n=e.initialState)==null?void 0:n.rowPinning)!=null?s:Ps())},e.getIsSomeRowsPinned=t=>{var s;const n=e.getState().rowPinning;if(!t){var r,i;return!!((r=n.top)!=null&&r.length||(i=n.bottom)!=null&&i.length)}return!!((s=n[t])!=null&&s.length)},e._getPinnedRows=(t,s,n)=>{var r;return((r=e.options.keepPinnedRows)==null||r?(s??[]).map(i=>{const o=e.getRow(i,!0);return o.getIsAllParentsExpanded()?o:null}):(s??[]).map(i=>t.find(o=>o.id===i))).filter(Boolean).map(i=>({...i,position:n}))},e.getTopRows=k(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,s)=>e._getPinnedRows(t,s,"top"),F(e.options,"debugRows","getTopRows")),e.getBottomRows=k(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,s)=>e._getPinnedRows(t,s,"bottom"),F(e.options,"debugRows","getBottomRows")),e.getCenterRows=k(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,s,n)=>{const r=new Set([...s??[],...n??[]]);return t.filter(i=>!r.has(i.id))},F(e.options,"debugRows","getCenterRows"))}},yc={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 s;return e.setRowSelection(t?{}:(s=e.initialState.rowSelection)!=null?s:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(s=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const n={...s},r=e.getPreGroupedRowModel().flatRows;return t?r.forEach(i=>{i.getCanSelect()&&(n[i.id]=!0)}):r.forEach(i=>{delete n[i.id]}),n})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(s=>{const n=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),r={...s};return e.getRowModel().rows.forEach(i=>{an(r,i.id,n,!0,e)}),r}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=k(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,s)=>Object.keys(t).length?ks(e,s):{rows:[],flatRows:[],rowsById:{}},F(e.options,"debugTable","getSelectedRowModel")),e.getFilteredSelectedRowModel=k(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,s)=>Object.keys(t).length?ks(e,s):{rows:[],flatRows:[],rowsById:{}},F(e.options,"debugTable","getFilteredSelectedRowModel")),e.getGroupedSelectedRowModel=k(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,s)=>Object.keys(t).length?ks(e,s):{rows:[],flatRows:[],rowsById:{}},F(e.options,"debugTable","getGroupedSelectedRowModel")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:s}=e.getState();let n=!!(t.length&&Object.keys(s).length);return n&&t.some(r=>r.getCanSelect()&&!s[r.id])&&(n=!1),n},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(r=>r.getCanSelect()),{rowSelection:s}=e.getState();let n=!!t.length;return n&&t.some(r=>!s[r.id])&&(n=!1),n},e.getIsSomeRowsSelected=()=>{var t;const s=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return s>0&&s<e.getFilteredRowModel().flatRows.length},e.getIsSomePageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(s=>s.getCanSelect()).some(s=>s.getIsSelected()||s.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(s,n)=>{const r=e.getIsSelected();t.setRowSelection(i=>{var o;if(s=typeof s<"u"?s:!r,e.getCanSelect()&&r===s)return i;const a={...i};return an(a,e.id,s,(o=n?.selectChildren)!=null?o:!0,t),a})},e.getIsSelected=()=>{const{rowSelection:s}=t.getState();return Bn(e,s)},e.getIsSomeSelected=()=>{const{rowSelection:s}=t.getState();return ln(e,s)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:s}=t.getState();return ln(e,s)==="all"},e.getCanSelect=()=>{var s;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(s=t.options.enableRowSelection)!=null?s:!0},e.getCanSelectSubRows=()=>{var s;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(s=t.options.enableSubRowSelection)!=null?s:!0},e.getCanMultiSelect=()=>{var s;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(s=t.options.enableMultiRowSelection)!=null?s:!0},e.getToggleSelectedHandler=()=>{const s=e.getCanSelect();return n=>{var r;s&&e.toggleSelected((r=n.target)==null?void 0:r.checked)}}}},an=(e,t,s,n,r)=>{var i;const o=r.getRow(t,!0);s?(o.getCanMultiSelect()||Object.keys(e).forEach(a=>delete e[a]),o.getCanSelect()&&(e[t]=!0)):delete e[t],n&&(i=o.subRows)!=null&&i.length&&o.getCanSelectSubRows()&&o.subRows.forEach(a=>an(e,a.id,s,n,r))};function ks(e,t){const s=e.getState().rowSelection,n=[],r={},i=function(o,a){return o.map(u=>{var l;const c=Bn(u,s);if(c&&(n.push(u),r[u.id]=u),(l=u.subRows)!=null&&l.length&&(u={...u,subRows:i(u.subRows)}),c)return u}).filter(Boolean)};return{rows:i(t.rows),flatRows:n,rowsById:r}}function Bn(e,t){var s;return(s=t[e.id])!=null?s:!1}function ln(e,t,s){var n;if(!((n=e.subRows)!=null&&n.length))return!1;let r=!0,i=!1;return e.subRows.forEach(o=>{if(!(i&&!r)&&(o.getCanSelect()&&(Bn(o,t)?i=!0:r=!1),o.subRows&&o.subRows.length)){const a=ln(o,t);a==="all"?i=!0:(a==="some"&&(i=!0),r=!1)}}),r?"all":i?"some":!1}var un=/([0-9]+)/gm,Ic=(e,t,s)=>ko(Me(e.getValue(s)).toLowerCase(),Me(t.getValue(s)).toLowerCase()),Rc=(e,t,s)=>ko(Me(e.getValue(s)),Me(t.getValue(s))),Cc=(e,t,s)=>Un(Me(e.getValue(s)).toLowerCase(),Me(t.getValue(s)).toLowerCase()),bc=(e,t,s)=>Un(Me(e.getValue(s)),Me(t.getValue(s))),wc=(e,t,s)=>{const n=e.getValue(s),r=t.getValue(s);return n>r?1:n<r?-1:0},Ec=(e,t,s)=>Un(e.getValue(s),t.getValue(s));function Un(e,t){return e===t?0:e>t?1:-1}function Me(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function ko(e,t){const s=e.split(un).filter(Boolean),n=t.split(un).filter(Boolean);for(;s.length&&n.length;){const r=s.shift(),i=n.shift(),o=parseInt(r,10),a=parseInt(i,10),u=[o,a].sort();if(isNaN(u[0])){if(r>i)return 1;if(i>r)return-1;continue}if(isNaN(u[1]))return isNaN(o)?-1:1;if(o>a)return 1;if(a>o)return-1}return s.length-n.length}var ut={alphanumeric:Ic,alphanumericCaseSensitive:Rc,text:Cc,textCaseSensitive:bc,datetime:wc,basic:Ec},_c={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 s=t.getFilteredRowModel().flatRows.slice(10);let n=!1;for(const r of s){const i=r?.getValue(e.id);if(Object.prototype.toString.call(i)==="[object Date]")return ut.datetime;if(typeof i=="string"&&(n=!0,i.split(un).length>1))return ut.alphanumeric}return n?ut.text:ut.basic},e.getAutoSortDir=()=>{const s=t.getFilteredRowModel().flatRows[0];return typeof s?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var s,n;if(!e)throw new Error;return fs(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(s=(n=t.options.sortingFns)==null?void 0:n[e.columnDef.sortingFn])!=null?s:ut[e.columnDef.sortingFn]},e.toggleSorting=(s,n)=>{const r=e.getNextSortingOrder(),i=typeof s<"u"&&s!==null;t.setSorting(o=>{const a=o?.find(f=>f.id===e.id),u=o?.findIndex(f=>f.id===e.id);let l=[],c,h=i?s:r==="desc";if(o!=null&&o.length&&e.getCanMultiSort()&&n?a?c="toggle":c="add":o!=null&&o.length&&u!==o.length-1?c="replace":a?c="toggle":c="replace",c==="toggle"&&(i||r||(c="remove")),c==="add"){var d;l=[...o,{id:e.id,desc:h}],l.splice(0,l.length-((d=t.options.maxMultiSortColCount)!=null?d:Number.MAX_SAFE_INTEGER))}else c==="toggle"?l=o.map(f=>f.id===e.id?{...f,desc:h}:f):c==="remove"?l=o.filter(f=>f.id!==e.id):l=[{id:e.id,desc:h}];return l})},e.getFirstSortDir=()=>{var s,n;return((s=(n=e.columnDef.sortDescFirst)!=null?n:t.options.sortDescFirst)!=null?s:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=s=>{var n,r;const i=e.getFirstSortDir(),o=e.getIsSorted();return o?o!==i&&((n=t.options.enableSortingRemoval)==null||n)&&(!(s&&(r=t.options.enableMultiRemove)!=null)||r)?!1:o==="desc"?"asc":"desc":i},e.getCanSort=()=>{var s,n;return((s=e.columnDef.enableSorting)!=null?s:!0)&&((n=t.options.enableSorting)!=null?n:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var s,n;return(s=(n=e.columnDef.enableMultiSort)!=null?n:t.options.enableMultiSort)!=null?s:!!e.accessorFn},e.getIsSorted=()=>{var s;const n=(s=t.getState().sorting)==null?void 0:s.find(r=>r.id===e.id);return n?n.desc?"desc":"asc":!1},e.getSortIndex=()=>{var s,n;return(s=(n=t.getState().sorting)==null?void 0:n.findIndex(r=>r.id===e.id))!=null?s:-1},e.clearSorting=()=>{t.setSorting(s=>s!=null&&s.length?s.filter(n=>n.id!==e.id):[])},e.getToggleSortingHandler=()=>{const s=e.getCanSort();return n=>{s&&(n.persist==null||n.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(n):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var s,n;e.setSorting(t?[]:(s=(n=e.initialState)==null?void 0:n.sorting)!=null?s:[])},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())}},Tc=[Ku,fc,lc,uc,Wu,Ju,pc,gc,_c,oc,mc,vc,Sc,yc,dc];function Mc(e){var t,s;const n=[...Tc,...(t=e._features)!=null?t:[]];let r={_features:n};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={...(s=e.initialState)!=null?s:{}};r._features.forEach(h=>{var d;a=(d=h.getInitialState==null?void 0:h.getInitialState(a))!=null?d:a});const u=[];let l=!1;const c={_features:n,options:{...i,...e},initialState:a,_queue:h=>{u.push(h),l||(l=!0,Promise.resolve().then(()=>{for(;u.length;)u.shift()();l=!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(v=>{const m=qu(r,v,g,p),S=v;return m.columns=S.columns?d(S.columns,m,g+1):[],m})};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 Kf(){return e=>k(()=>[e.options.data],t=>{const s={rows:[],flatRows:[],rowsById:{}},n=function(r,i,o){i===void 0&&(i=0);const a=[];for(let l=0;l<r.length;l++){const c=Qu(e,e._getRowId(r[l],l,o),r[l],l,i,void 0,o?.id);if(s.flatRows.push(c),s.rowsById[c.id]=c,a.push(c),e.options.getSubRows){var u;c.originalSubRows=e.options.getSubRows(r[l],l),(u=c.originalSubRows)!=null&&u.length&&(c.subRows=n(c.originalSubRows,i+1,c))}}return a};return s.rows=n(t),s},F(e.options,"debugTable","getRowModel",()=>e._autoResetPageIndex()))}function Qf(){return e=>k(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,s)=>{if(!s.rows.length||!(t!=null&&t.length))return s;const n=e.getState().sorting,r=[],i=n.filter(u=>{var l;return(l=e.getColumn(u.id))==null?void 0:l.getCanSort()}),o={};i.forEach(u=>{const l=e.getColumn(u.id);l&&(o[u.id]={sortUndefined:l.columnDef.sortUndefined,invertSorting:l.columnDef.invertSorting,sortingFn:l.getSortingFn()})});const a=u=>{const l=u.map(c=>({...c}));return l.sort((c,h)=>{for(let f=0;f<i.length;f+=1){var d;const p=i[f],g=o[p.id],v=g.sortUndefined,m=(d=p?.desc)!=null?d:!1;let S=0;if(v){const C=c.getValue(p.id),b=h.getValue(p.id),w=C===void 0,R=b===void 0;if(w||R){if(v==="first")return w?-1:1;if(v==="last")return w?1:-1;S=w&&R?0:w?v:-v}}if(S===0&&(S=g.sortingFn(c,h,p.id)),S!==0)return m&&(S*=-1),g.invertSorting&&(S*=-1),S}return c.index-h.index}),l.forEach(c=>{var h;r.push(c),(h=c.subRows)!=null&&h.length&&(c.subRows=a(c.subRows))}),l};return{rows:a(s.rows),flatRows:r,rowsById:s.rowsById}},F(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function Wf(e,t){return e?Ac(e)?I.createElement(e,t):e:null}function Ac(e){return Oc(e)||typeof e=="function"||xc(e)}function Oc(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function xc(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Jf(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[s]=I.useState(()=>({current:Mc(t)})),[n,r]=I.useState(()=>s.current.initialState);return s.current.setOptions(i=>({...i,...e,state:{...n,...e.state},onStateChange:o=>{r(o),e.onStateChange==null||e.onStateChange(o)}})),s.current}var Pc=Ei(ha(),1);function We(e,t,s){let n=s.initialDeps??[],r,i=!0;function o(){var a,u,l;let c;s.key&&((a=s.debug)!=null&&a.call(s))&&(c=Date.now());const h=e();if(!(h.length!==n.length||h.some((f,p)=>n[p]!==f)))return r;n=h;let d;if(s.key&&((u=s.debug)!=null&&u.call(s))&&(d=Date.now()),r=t(...h),s.key&&((l=s.debug)!=null&&l.call(s))){const f=Math.round((Date.now()-c)*100)/100,p=Math.round((Date.now()-d)*100)/100,g=p/16,v=(m,S)=>{for(m=String(m);m.length<S;)m=" "+m;return m};console.info(`%c⏱ ${v(p,5)} /${v(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%);`,s?.key)}return s?.onChange&&!(i&&s.skipInitialOnChange)&&s.onChange(r),i=!1,r}return o.updateDeps=a=>{n=a},o}function xr(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var kc=(e,t)=>Math.abs(e-t)<1.01,Fc=(e,t,s)=>{let n;return function(...r){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,r),s)}},Pr=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},Lc=e=>e,Nc=e=>{const t=Math.max(e.startIndex-e.overscan,0),s=Math.min(e.endIndex+e.overscan,e.count-1),n=[];for(let r=t;r<=s;r++)n.push(r);return n},Dc=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const r=o=>{const{width:a,height:u}=o;t({width:Math.round(a),height:Math.round(u)})};if(r(Pr(s)),!n.ResizeObserver)return()=>{};const i=new n.ResizeObserver(o=>{const a=()=>{const u=o[0];if(u?.borderBoxSize){const l=u.borderBoxSize[0];if(l){r({width:l.inlineSize,height:l.blockSize});return}}r(Pr(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(s,{box:"border-box"}),()=>{i.unobserve(s)}},kr={passive:!0},Fr=typeof window>"u"?!0:"onscrollend"in window,jc=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let r=0;const i=e.options.useScrollendEvent&&Fr?()=>{}:Fc(n,()=>{t(r,!1)},e.options.isScrollingResetDelay),o=c=>()=>{const{horizontal:h,isRtl:d}=e.options;r=h?s.scrollLeft*(d&&-1||1):s.scrollTop,i(),t(r,c)},a=o(!0),u=o(!1);s.addEventListener("scroll",a,kr);const l=e.options.useScrollendEvent&&Fr;return l&&s.addEventListener("scrollend",u,kr),()=>{s.removeEventListener("scroll",a),l&&s.removeEventListener("scrollend",u)}},Gc=(e,t,s)=>{if(t?.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},$c=(e,{adjustments:t=0,behavior:s},n)=>{var r,i;const o=e+t;(i=(r=n.scrollElement)==null?void 0:r.scrollTo)==null||i.call(r,{[n.options.horizontal?"left":"top"]:o,behavior:s})},Bc=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,s,n;return((n=(s=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:s.now)==null?void 0:n.call(s))??Date.now()},this.observer=(()=>{let t=null;const s=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(n=>{n.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 n;(n=s())==null||n.disconnect(),t=null},observe:n=>{var r;return(r=s())==null?void 0:r.observe(n,{box:"border-box"})},unobserve:n=>{var r;return(r=s())==null?void 0:r.unobserve(n)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([s,n])=>{typeof n>"u"&&delete t[s]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Lc,rangeExtractor:Nc,onChange:()=>{},measureElement:Gc,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 s,n;(n=(s=this.options).onChange)==null||n.call(s,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 s=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==s){if(this.cleanup(),!s){this.maybeNotify();return}this.scrollElement=s,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(n=>{this.observer.observe(n)}),this.unsubs.push(this.options.observeElementRect(this,n=>{this.scrollRect=n,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(n,r)=>{this.scrollAdjustments=0,this.scrollDirection=r?this.getScrollOffset()<n?"forward":"backward":null,this.scrollOffset=n,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,s)=>{const n=new Map,r=new Map;for(let i=s-1;i>=0;i--){const o=t[i];if(n.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&&n.set(o.lane,!0),n.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,s,n,r,i,o,a)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:s,scrollMargin:n,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a}),{key:!1}),this.getMeasurements=We(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:s,scrollMargin:n,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a},u)=>{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 l=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,l),h=new Array(o).fill(void 0);for(let d=0;d<l;d++){const f=c[d];f&&(h[f.lane]=d)}for(let d=l;d<t;d++){const f=r(d),p=this.laneAssignments.get(d);let g,v;const m=a==="estimate"||u.has(f);if(p!==void 0&&this.options.lanes>1){g=p;const w=h[g],R=w!==void 0?c[w]:void 0;v=R?R.end+this.options.gap:s+n}else{const w=this.options.lanes===1?c[d-1]:this.getFurthestMeasurement(c,d);v=w?w.end+this.options.gap:s+n,g=w?w.lane:d%this.options.lanes,this.options.lanes>1&&m&&this.laneAssignments.set(d,g)}const S=u.get(f),C=typeof S=="number"?S:this.options.estimateSize(d),b=v+C;c[d]={index:d,start:v,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,s,n,r)=>this.range=t.length>0&&s>0?Uc({measurements:t,outerSize:s,scrollOffset:n,lanes:r}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=We(()=>{let t=null,s=null;const n=this.calculateRange();return n&&(t=n.startIndex,s=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,s]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,s]},(t,s,n,r,i)=>r===null||i===null?[]:t({startIndex:r,endIndex:i,overscan:s,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const s=this.options.indexAttribute,n=t.getAttribute(s);return n?parseInt(n,10):(console.warn(`Missing attribute name '${s}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var s;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const n=this.scrollState.index??((s=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:s.index);if(n!==void 0&&this.range){const r=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,n-r),o=Math.min(this.options.count-1,n+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 s=this.indexFromElement(t),n=this.options.getItemKey(s),r=this.elementsCache.get(n);r!==t&&(r&&this.observer.unobserve(r),this.observer.observe(t),this.elementsCache.set(n,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(s)&&this.resizeItem(s,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,s)=>{var n;const r=this.measurementsCache[t];if(!r)return;const i=s-(this.itemSizeCache.get(r.key)??r.size);i!==0&&(((n=this.scrollState)==null?void 0:n.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,s)),this.notify(!1))},this.getVirtualItems=We(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,s)=>{const n=[];for(let r=0,i=t.length;r<i;r++){const o=s[t[r]];n.push(o)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const s=this.getMeasurements();if(s.length!==0)return xr(s[Fo(0,s.length-1,n=>xr(s[n]).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,s,n=0)=>{if(!this.scrollElement)return 0;const r=this.getSize(),i=this.getScrollOffset();s==="auto"&&(s=t>=i+r?"end":"start"),s==="center"?t+=(n-r)/2:s==="end"&&(t-=r);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,s="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[t];if(!i)return;if(s==="auto")if(i.end>=r+n-this.options.scrollPaddingEnd)s="end";else if(i.start<=r+this.options.scrollPaddingStart)s="start";else return[r,s];if(s==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),s];const o=s==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,s,i.size),s]},this.scrollToOffset=(t,{align:s="start",behavior:n="auto"}={})=>{const r=this.getOffsetForAlignment(t,s),i=this.now();this.scrollState={index:null,align:s,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:s="auto",behavior:n="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const r=this.getOffsetForIndex(t,s);if(!r)return;const[i,o]=r,a=this.now();this.scrollState={index:t,align:o,behavior:n,startedAt:a,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:s="auto"}={})=>{const n=this.getScrollOffset()+t,r=this.now();this.scrollState={index:null,align:"start",behavior:s,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const s=this.getMeasurements();let n;if(s.length===0)n=this.options.paddingStart;else if(this.options.lanes===1)n=((t=s[s.length-1])==null?void 0:t.end)??0;else{const r=Array(this.options.lanes).fill(null);let i=s.length-1;for(;i>=0&&r.some(o=>o===null);){const o=s[i];r[o.lane]===null&&(r[o.lane]=o.end),i--}n=Math.max(...r.filter(o=>o!==null))}return Math.max(n-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:s,behavior:n})=>{this.options.scrollToFn(t,{behavior:n,adjustments:s},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,s=1,n=t!==this.scrollState.lastTargetOffset;if(!n&&kc(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=s){this.scrollState=null;return}}else this.scrollState.stableFrames=0,n&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior="auto",this._scrollToOffset(t,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}},Fo=(e,t,s,n)=>{for(;e<=t;){const r=(e+t)/2|0,i=s(r);if(i<n)e=r+1;else if(i>n)t=r-1;else return r}return e>0?e-1:0};function Uc({measurements:e,outerSize:t,scrollOffset:s,lanes:n}){const r=e.length-1,i=u=>e[u].start;if(e.length<=n)return{startIndex:0,endIndex:r};let o=Fo(0,r,i,s),a=o;if(n===1)for(;a<r&&e[a].end<s+t;)a++;else if(n>1){const u=Array(n).fill(0);for(;a<r&&u.some(c=>c<s+t);){const c=e[a];u[c.lane]=c.end,a++}const l=Array(n).fill(s+t);for(;o>=0&&l.some(c=>c>=s);){const c=e[o];l[c.lane]=c.start,o--}o=Math.max(0,o-o%n),a=Math.min(r,a+(n-1-a%n))}return{startIndex:o,endIndex:a}}var Lr=typeof document<"u"?I.useLayoutEffect:I.useEffect;function Hc({useFlushSync:e=!0,...t}){const s=I.useReducer(()=>({}),{})[1],n={...t,onChange:(i,o)=>{var a;e&&o?(0,Pc.flushSync)(s):s(),(a=t.onChange)==null||a.call(t,i,o)}},[r]=I.useState(()=>new Bc(n));return r.setOptions(n),Lr(()=>r._didMount(),[]),Lr(()=>r._willUpdate()),r}function Xf(e){return Hc({observeElementRect:Dc,observeElementOffset:jc,scrollToFn:$c,...e})}function zc(){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 Vc=/^[a-z][a-z0-9-]{0,63}$/,qc="x-byok-";function re(e){return typeof e=="string"&&Vc.test(e)}function Nr(e){if(!re(e))throw new Error(`Invalid BYOK provider id: ${e}`);return`${qc}${e}`}function Kc(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"||!re(t.provider)||!("message"in t)||typeof t.message!="string")}var cn=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name="ByokMissingError",this.provider=e}},is=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}},Lo=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},No=new WeakMap;function Wc(e){const t=Object.entries(e.keys()).filter(n=>!!n[1]).map(n=>n[0]).filter(re);if(t.length===1)return t[0];const s=No.get(e)??[];if(s.length===1)return s[0]}function Oe(e){if(!re(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 Jc(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 Dr(e){if(typeof e!="object"||e===null)return{};const t={};for(const[s,n]of Object.entries(e))re(s)&&typeof n=="string"&&n.length>0&&(t[s]=n);return t}var Xc=class{storage;#t={};#e={};#s;#n=null;#i=!1;#r={};#a={};#l=new Set;#h;#o=null;#u;constructor(e={}){this.storage=e.storage??zc();const t=[];for(const s of e.providers??[]){const n=Oe(s.id);t.push(n),s.with?.length&&(this.#a[n]=s.with.map(r=>Oe(r.id)))}No.set(this,t),this.#s=!!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.#s,prompt:this.#n,storageError:this.#o}}keys(){return{...this.#t}}request(e,t){this.#n={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 s of this.#p(e)){const n=this.#t[s];n&&(t[Nr(s)]=n)}return t}for(const[s,n]of Object.entries(this.#t))n&&(t[Nr(s)]=n);return t}async prepare(e){if(await this.#u,this.storage.unlockable&&this.#s&&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 is(t,"missing")}}async update(e,t){await this.#u;let s,n;if(t===void 0){if(!this.#n)throw new Error("byok.update(key) cannot run when prompt is null");s=this.#n.provider,n=e}else s=Oe(e),n=t;if(n=n.trim(),n.length===0)throw new Error("BYOK key must be non-empty");this.storage.unlockable&&this.#s&&await this.unlock();const r=this.#t,i={...this.#e},o=this.#s,a=this.#n,u=this.#o,l={...this.#t,[s]:n};try{await this.storage.save(l)}catch(c){throw this.#t=r,this.#e=i,this.#s=o,this.#n=a,this.#o=u,this.#e[s]={state:"error",masked:$t(n),message:Bt(c,`Failed to persist ${s} key`)},this.#c(),c}this.#t=l,this.#e[s]={state:"set",masked:$t(n)},this.#s=!1,this.#n=null,this.#o=null,this.#c()}async clear(e){if(await this.#u,e){Oe(e),this.storage.unlockable&&this.#s&&await this.unlock();const i=this.#t,o={...this.#e},a={...this.#t};delete a[e];try{await this.storage.save(a)}catch(u){throw this.#t=i,this.#e=o,this.#c(),u}this.#t=a,delete this.#e[e],this.#c();return}const t=this.#t,s=this.#e,n=this.#s,r=this.#n;try{await this.storage.clear()}catch(i){throw this.#t=t,this.#e=s,this.#s=n,this.#n=r,this.#c(),i}this.#t={},this.#e={},this.#s=!1,this.#n=null,this.#o=null,this.#c()}async unlock(){if(await this.#u,!!this.storage.unlockable)try{const e=Dr(await this.storage.load());this.#t={...e,...this.#t};for(const[t,s]of Object.entries(e)){if(!re(t)||!s)continue;const n=this.#e[t];(!n||n.state==="locked")&&(this.#e[t]={state:"set",masked:$t(s)})}this.#s=!1,this.#o=null,this.#c()}catch(e){if(Jc(e)){const t=this.#g();if(t)throw this.request(t,"locked"),new is(t,"locked")}throw this.#o=Bt(e,"Failed to unlock keyring"),this.#c(),e instanceof Error?e:new Error(String(e))}}#g(){if(this.#n&&re(this.#n.provider))return this.#n.provider;for(const[e,t]of Object.entries(this.#e))if(t?.state==="locked"&&re(e))return e}async#m(){if(this.storage.unlockable){if(!this.storage.peek)return;try{const e=await this.storage.peek();for(const[t,s]of Object.entries(e))!re(t)||this.#e[t]||(this.#e[t]={state:"locked",masked:s||"••"});this.#s=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=Dr(await this.storage.load());this.#t={...e,...this.#t};for(const[t,s]of Object.entries(e))!re(t)||!s||(this.#e[t]={state:"set",masked:$t(s)});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 Yf(e={}){return new Xc(e)}var dn=class extends Error{missingFeature;constructor(e){super(Yc(e)),this.name="UnsupportedResponseStreamError",this.missingFeature=e}};function Yc(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 Zc(e){if(!e.body)throw new dn("Response.body");if(typeof e.body.getReader!="function")throw new dn("Response.body.getReader");return e.body.getReader()}function ed(){if(typeof globalThis.TextDecoder!="function")throw new dn("TextDecoder");return new globalThis.TextDecoder}function td(e){if(!e.startsWith("data:"))return e;const t=e.slice(5);return t.startsWith(" ")?t.slice(1):t}function jr(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 sd(e){const t=jr(e.createdAt),s=e.parts.map(i=>{if(i.type!=="tool-result")return i;const o=jr(i.createdAt),{createdAt:a,...u}=i;return o?{...u,createdAt:o}:u}),{createdAt:n,...r}=e;return t?{...r,parts:s,createdAt:t}:{...r,parts:s}}function hn(e){return e.map(sd)}function Gr(e){return Object.keys(e).length>0?e:void 0}function Do(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)&&"promptTokens"in e}function nd(e,t){return Do(e)?e:Array.isArray(e)?$r(e,t):$r(void 0,t)}function $r(e,t){const s=e?.[0];if(s==null&&t==null)return;const{promptTokensDetails:n,completionTokensDetails:r,...i}=t??{},o=Gr({...s?.cachedInputTokens!==void 0?{cachedTokens:s.cachedInputTokens}:{},...n}),a=Gr({...s?.reasoningTokens!==void 0?{reasoningTokens:s.reasoningTokens}:{},...r});return{promptTokens:s?.inputTokens??0,completionTokens:s?.outputTokens??0,totalTokens:s?.totalTokens??0,...i,...o!==void 0?{promptTokensDetails:o}:{},...a!==void 0?{completionTokensDetails:a}:{}}}function Br(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function jo(e,t){if(t==null)return e;if(e==null)return{...t};const s={...e,...t};return Br(e.tanstack)&&Br(t.tanstack)&&(s.tanstack={...e.tanstack,...t.tanstack}),s}function B(e){if(e==null)return;const t="metadata"in e?e.metadata:void 0,s=(t!=null&&typeof t=="object"&&!Array.isArray(t)?t:e).tanstack;if(!(s==null||typeof s!="object"||Array.isArray(s)))return s}function Go(e,t){const s=e.metadata,n=B(e)??{};return{...e,metadata:{...s??{},tanstack:{...n,...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})({}),rd=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 id(e){const t=new TextEncoder().encode(e),s=t.length*8,n=t.length+1,r=n+(56-n%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(s/4294967296)),o.setUint32(r-4,s>>>0);let a=1779033703,u=3144134277,l=1013904242,c=2773480762,h=1359893119,d=2600822924,f=528734635,p=1541459225;const g=new Uint32Array(64);for(let m=0;m<r;m+=64){for(let T=0;T<16;T++)g[T]=o.getUint32(m+T*4);for(let T=16;T<64;T++){const A=g[T-15]??0,M=g[T-2]??0,x=le(A,7)^le(A,18)^A>>>3,P=le(M,17)^le(M,19)^M>>>10;g[T]=(g[T-16]??0)+x+(g[T-7]??0)+P>>>0}let S=a,C=u,b=l,w=c,R=h,y=d,_=f,O=p;for(let T=0;T<64;T++){const A=le(R,6)^le(R,11)^le(R,25),M=R&y^~R&_,x=O+A+M+(rd[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,u=u+C>>>0,l=l+b>>>0,c=c+w>>>0,h=h+R>>>0,d=d+y>>>0,f=f+_>>>0,p=p+O>>>0}const v=m=>(m>>>0).toString(16).padStart(8,"0");return v(a)+v(u)+v(l)+v(c)+v(h)+v(d)+v(f)+v(p)}function od(e){return`sha256:${id(e)}`}function fn(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 s;if(Array.isArray(e)){const n=[];for(let r=0;r<e.length;r++)n.push(fn(e[r],t));s=`[${n.join(",")}]`}else{const n=e;s=`{${Object.keys(n).sort().map(r=>`${JSON.stringify(r)}:${fn(n[r],t)}`).join(",")}}`}return t.delete(e),s}function je(e){return fn(e,new WeakSet)}function Ge(e,t=od){if(typeof e!="string")throw new TypeError("Interrupt digests require canonical JSON text.");return t(e)}function $o(e){e===null||typeof e!="object"||Object.isFrozen(e)||(Object.values(e).forEach($o),Object.freeze(e))}function U(e){const t=JSON.parse(je(e));return $o(t),t}function ad(e){const t=[...e].sort((r,i)=>r.interruptId.localeCompare(i.interruptId)),s=U(t),n=je(s);return Object.freeze({resolutions:s,canonicalResolutions:n,fingerprint:Ge(n)})}function Ur(e){const t={};for(const[s,n]of Object.entries(e))s!=="$schema"&&(t[s]=n);return t}function Bo(e){return(typeof e=="object"||typeof e=="function")&&e!==null}function Et(e){if(!Bo(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 Ae(e){return Bo(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 ld(e){return Object.keys(e).length>0?e:void 0}function Hr(e){if(Array.isArray(e)){const s=e.map(r=>os(r,r.required||[])),n=s.map(r=>r.nullWidening??{});return{schema:s.map(r=>r.schema),itemMap:n.some(r=>Object.keys(r).length>0)?n:void 0}}const t=os(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function os(e,t=[]){const s={...e},n={};if(s.type==="object"&&s.properties){const r={...s.properties},i=Object.keys(r),o={};for(const a of i){const u=r[a];if(!u)continue;const l=!t.includes(a);let c=!1,h;if(u.type==="object"&&u.properties){const d=os(u,u.required||[]);r[a]=l?{...d.schema,type:["object","null"]}:d.schema,c=l,h=d.nullWidening}else if(u.type==="array"&&u.items){const d=Hr(u.items);r[a]={...u,items:d.schema,...l?{type:["array","null"]}:{}},c=l,h=d.itemMap?{items:d.itemMap}:void 0}else l&&(u.type&&!Array.isArray(u.type)?(r[a]={...u,type:[u.type,"null"]},c=!0):Array.isArray(u.type)&&!u.type.includes("null")&&(r[a]={...u,type:[...u.type,"null"]},c=!0));(c||h)&&(o[a]={...h??{},...c?{widened:!0}:{}})}s.properties=r,s.required=i,s.additionalProperties=!1,Object.keys(o).length>0&&(n.properties=o)}if(s.type==="array"&&s.items){const r=Hr(s.items);s.items=r.schema,r.itemMap&&(n.items=r.itemMap)}return{schema:s,nullWidening:ld(n)}}function ud(e){if(Et(e)){const t=Ur(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(Ae(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:Ur(e)}function pn(e,t={}){if(!e)return;const{forStructuredOutput:s=!1}=t;if(!s&&!Et(e)&&!Ae(e))return e;const n=ud(e);return!n||typeof n!="object"||!s?n:os(n,n.required||[]).schema}var cd=class extends Error{name="StandardSchemaValidationError";issues;constructor(e){super(`Validation failed: ${e.map(t=>t.message||"Validation failed").join(", ")}`),this.issues=e}};function dd(e,t){if(!Ae(e))return t;const s=e["~standard"].validate(t);if(s instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!s.issues)return s.value;throw new cd(s.issues)}var hd=new Set(["$schema","$id","$ref","$defs","type","properties","required","additionalProperties","items","oneOf","anyOf","allOf","enum","const","format","minimum","maximum","minLength","maxLength","pattern"]);function Uo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Hn(e){return Uo(e)&&Object.keys(e).some(t=>hd.has(t))}function fd(e){return Ae(e)||Et(e)||Hn(e)}function pd(e){if(!Uo(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(s=>s==="approve"||s==="reject")&&t.every(s=>fd(e[s]))}function gd(e){const t={};for(const[s,n]of Object.entries(e))t[s]=n;return t}function dt(e){if(Ae(e)){const t=Et(e)?gd(e["~standard"].jsonSchema.input({target:"draft-2020-12"})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Hn(e))return{source:e,jsonSchema:e};throw new TypeError("Expected a supported SchemaInput.")}function zr(e){const t={approved:{const:e.approved}},s=["approved"];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},s.push("payload")),{type:"object",properties:t,required:s,additionalProperties:!1}}function md(e,t){const s=t===void 0?null:dt(t);let n=null,r=null;if(e!==void 0)if(Ae(e)||Hn(e))n=dt(e),r=n;else if(pd(e))n=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:[zr({approved:!0,payload:n,inputSchema:s}),zr({approved:!1,payload:r,inputSchema:null})]},o=je(i),a=je({approve:n?.jsonSchema??null,reject:r?.jsonSchema??null});return{branches:{approve:n,reject:r},responseSchema:i,responseSchemaHash:Ge(o),approvalSchemaHash:Ge(a)}}function Vr(e){if(e===void 0)return Ge("undefined");const t=dt(e).jsonSchema??{standardValidator:"unserialized"};return Ge(je(t))}var ps="tanstack:interruptBinding",Ho=ps;function as(e){return e&&typeof e=="object"?e:null}function Q(e,t){return typeof e[t]=="string"?e[t]:void 0}function vd(e){const t=e.v;return t===void 0?!0:t===1}function zo(e){const t=as(e.metadata),s=t?as(t[Ho]):null;if(!s||Q(s,"interruptId")!==e.id||!vd(s))return;const n=Q(s,"kind"),r=Q(s,"interruptId"),i=Q(s,"responseSchemaHash"),o=Q(s,"expiresAt");if(!r||i===""||o!==void 0&&!Number.isFinite(Date.parse(o)))return;const a=1;if(n==="generic"){const c=Q(s,"definitionId"),h=Q(s,"key"),d=s.batchIndex,f=Q(s,"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:n,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 u=Q(s,"toolName"),l=Q(s,"toolCallId");if(!(!u||!l)){if(n==="client-tool-execution"){const c=Q(s,"outputSchemaHash");return c?{v:a,kind:n,interruptId:r,toolName:u,toolCallId:l,outputSchemaHash:c,responseSchemaHash:i,...o?{expiresAt:o}:{}}:void 0}if(n==="tool-approval"){const c=Q(s,"inputSchemaHash"),h=Q(s,"approvalSchemaHash");return!c||!h?void 0:{v:a,kind:n,interruptId:r,toolName:u,toolCallId:l,originalArgs:s.originalArgs,inputSchemaHash:c,approvalSchemaHash:h,responseSchemaHash:i,...o?{expiresAt:o}:{}}}}}function Sd(e){const t=zo(e);if(!t)return;const s=as(e.metadata),n=s?as(s[Ho]):null;if(!n)return;const r=Q(n,"interruptedRunId"),i=n.generation;if(!(!r||typeof i!="number"||!Number.isInteger(i)||i<0))return{...t,interruptedRunId:r,generation:i}}var yd="tanstack:interruptPayload";function Id(e,t){if(!Et(e))throw new TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{const s=e["~standard"].jsonSchema.input({target:"draft-07"});if(s===void 0)throw new TypeError("The exported schema is undefined.");if(typeof s=="function")throw new TypeError("The exported schema must not be a function.");if(Array.isArray(s))throw new TypeError("The exported schema must be a plain JSON object.");if(!s||typeof s!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(s)))throw new TypeError("The exported schema must be a plain JSON object.");const n={};for(const[r,i]of Object.entries(s))r!=="$schema"&&(n[r]=i);return{json:n,canonicalJson:je(n)}}catch(s){throw new TypeError(`${t} could not export compatible JSON Schema: ${s instanceof Error?s.message:String(s)}`)}}function Rd(e){return Ge(Id(e,"Interrupt schema").canonicalJson)}var Cd="tanstack:interruptContinuation";function bd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function wd(e){return{[Cd]:e}}function Ed(e){const t=zo(e);if(t?.kind!=="generic"||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;const s=bd(e.metadata)?e.metadata:void 0,n=s!==void 0&&Object.prototype.hasOwnProperty.call(s,"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}:{},...n?{payload:s[yd]}:{}}}var _d=new Set(["text","image","audio","video","document"]);function Td(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.type!="string"||!_d.has(t.type))return!1;if(t.type==="text")return typeof t.content=="string";const s=t.source;if(typeof s!="object"||s===null)return!1;const n=s;return typeof n.value!="string"?!1:n.type==="data"?typeof n.mimeType=="string":n.type==="url"}function gn(e){return Array.isArray(e)&&e.length>0&&e.every(Td)}function zn(e){return typeof e=="string"||gn(e)?e:JSON.stringify(e)}function Md(e){const t=e?.metadata;return typeof t=="object"&&t!==null&&t.providerExecuted===!0?t:null}function Vo(e){return Md(e)!==null}function Fs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ad(e){return e.type==="text"||e.type==="image"||e.type==="audio"||e.type==="video"||e.type==="document"}function Od(e){try{return JSON.stringify(e)??""}catch{return""}}function qr(e){return typeof e=="string"&&e!==""?e:void 0}function xd(e){if("encryptedValue"in e){const t=qr(e.encryptedValue);if(t!==void 0)return t}return qr(B(e)?.signature)}function qo(e){return e.length===0?null:e.every(t=>t.type==="text")?e.map(t=>t.content).join("")||null:e}function Ko(e){return e==null?"":typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.content).join("")}function Pd(e){return Array.isArray(e)?e:Ko(e)}function kd(e){if(!("role"in e)||e.role!=="tool")return e;const t=e,s=B(t)?.toolResult;if(!Fs(s)||"content"in s&&!gn(s.content))return e;const n={...e};if("id"in s||Reflect.deleteProperty(n,"id"),"createdAt"in s||Reflect.deleteProperty(n,"createdAt"),typeof s.id=="string"&&Reflect.set(n,"id",s.id),typeof s.createdAt=="string"){const i=ie(s.createdAt);i&&Reflect.set(n,"createdAt",i)}gn(s.content)&&Reflect.set(n,"content",s.content);const r=Reflect.get(t,"metadata");if(Fs(r)){const i=r.tanstack;if(Fs(i)){const{toolResult:o,...a}=i,u={...r};Object.keys(a).length?u.tanstack=a:delete u.tanstack,Object.keys(u).length?Reflect.set(n,"metadata",u):Reflect.deleteProperty(n,"metadata")}}return n}function ie(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=ie(e.createdAt),{createdAt:s,...n}=e;return t===void 0?n:{...n,createdAt:t}}function Wo(e){return ie(B(e)?.createdAt)}function mn(e){const t=ie(e.createdAt);return t!==void 0?{createdAt:t}:{}}function gs(e){return e.name!==void 0?{name:e.name}:{}}function ms(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 Kr(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function Jo(e,t){if(t.length===0)return e;const s=new Set(e.parts.filter(ms).map(r=>Kr(r))),n=t.filter(r=>!s.has(Kr(r)));return n.length===0?e:{...e,parts:[...e.parts,...n]}}function Fd(e){const t=e.parts.filter(ms),s=e.metadata??{},n=B(e),r={};n?.model!==void 0&&(r.model=n.model),n?.signature!==void 0&&(r.signature=n.signature),t.length>0&&(r.uiResources=t);const i={...s};return Object.keys(r).length>0?i.tanstack=r:delete i.tanstack,Object.keys(i).length>0?i:void 0}function Ld(e){return e.role==="system"?[]:e.role!=="assistant"?[Nd(e)]:jd(e)}function Nd(e){const t=[];for(const s of e.parts)Ad(s)&&t.push(s);return{id:e.id,role:e.role,content:qo(t),...gs(e),...mn(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function Qr(){return{contentParts:[],toolCalls:[]}}function Dd(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 jd(e){const t=[];let s=Qr(),n=[];const r=new Set,i={id:e.id,...gs(e),...mn(e)},o=Fd(e),a={...i,...o!==void 0&&{metadata:o}};function u(l=!1){const c=qo(s.contentParts),h=c!==null,d=s.toolCalls.length>0,f=n.length>0;(l||h||d||f)&&(t.push({...a,role:"assistant",content:c,...d&&{toolCalls:s.toolCalls},...f&&{thinking:n},...s.structuredOutput&&{structuredOutput:s.structuredOutput}}),n=[]),s=Qr()}for(const l of e.parts)switch(l.type){case"text":case"image":case"audio":case"video":case"document":s.contentParts.push(l);break;case"tool-call":Dd(l)&&s.toolCalls.push({id:l.id,type:"function",function:{name:l.name,arguments:l.arguments},...l.metadata!==void 0&&{metadata:l.metadata}});break;case"tool-result":u(t.length===0),(l.state==="complete"||l.state==="error")&&!r.has(l.toolCallId)&&(t.push({...l.id!==void 0&&{id:l.id},...mn(l),role:"tool",content:l.content,toolCallId:l.toolCallId,...l.name!==void 0&&{name:l.name},...l.metadata!==void 0&&{metadata:l.metadata},...l.error!==void 0&&{error:l.error}}),r.add(l.toolCallId));break;case"thinking":(l.content||l.signature)&&(s.toolCalls.some(Vo)&&u(),n.push({content:l.content,...l.signature&&{signature:l.signature}}));break;case"structured-output":if(l.status==="complete"){const c=l.raw!==""?l.raw:l.data!==void 0?Od(l.data):"";c!==""&&(s.contentParts.push({type:"text",content:c}),s.structuredOutput=l)}}u();for(const l of e.parts)if(l.type==="tool-call"&&(l.output!==void 0&&!r.has(l.id)&&(t.push({role:"tool",content:zn(l.output),toolCallId:l.id}),r.add(l.id)),l.output===void 0&&l.state==="approval-responded"&&l.approval?.approved!==void 0&&!r.has(l.id))){const c=l.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:l.id}),r.add(l.id)}return t.length===0&&t.push({...a,role:"assistant",content:null}),t}function ls(e,t){const s=[],n=ie(e.createdAt);if(e.role==="assistant"&&e.thinking?.length)for(const a of e.thinking)!a.content&&!a.signature||s.push({type:"thinking",content:a.content,...a.signature&&{signature:a.signature}});const r=e.structuredOutput??Xo(B(e)?.structuredOutput);if(e.role==="assistant"&&r){if(typeof e.content=="string"&&e.content&&e.content!==r.raw){const a=r.raw,u=a!==""&&e.content.endsWith(a)?e.content.slice(0,-a.length):e.content;u&&s.push({type:"text",content:u})}s.push(r)}else if(e.role==="tool"&&e.toolCallId)s.push({type:"tool-result",toolCallId:e.toolCallId,content:Pd(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},...n!==void 0&&{createdAt:n},...e.error!==void 0&&{error:e.error}});else if(Array.isArray(e.content))for(const a of e.content)s.push(a);else{const a=Ko(e.content);a&&s.push({type:"text",content:a})}if(e.toolCalls&&e.toolCalls.length>0)for(const a of e.toolCalls){let u;try{u=JSON.parse(a.function.arguments)}catch{u=void 0}s.push({type:"tool-call",id:a.id,name:a.function.name,arguments:a.function.arguments,state:"input-complete",...u!==void 0&&{input:u},...a.metadata!==void 0&&{metadata:a.metadata}})}const i={id:t||Ne(),role:e.role==="tool"?"assistant":e.role,parts:s,...gs(e),...n!==void 0&&{createdAt:n},...e.metadata!==void 0&&{metadata:e.metadata}},o=B(e)?.uiResources;return Jo(i,Array.isArray(o)?o.filter(ms):[])}function Gd(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:$d(e.content)});case"assistant":{const s=B(e),n=s?.toolCallMetadata,r=Xo(s?.structuredOutput),i=e.toolCalls?.map(o=>{const a=n!=null&&typeof n=="object"?n[o.id]:void 0;return a!==void 0?{...o,metadata:a}:o});return xe(e,ls({role:"assistant",content:e.content??null,...gs(e),...i&&{toolCalls:i},...r&&{structuredOutput:r}},t))}case"tool":{e=kd(e);const s=ie("createdAt"in e?e.createdAt:void 0)??Wo(e);return xe(e,ls({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}:{},...s!==void 0?{createdAt:s}:{},...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 s=xd(e),n=typeof e.content=="string"?e.content:"";return xe(e,{id:t,role:"assistant",parts:n||s!==void 0?[{type:"thinking",content:n,...s!==void 0?{signature:s}:{}}]:[]})}default:return xe(e,{id:t,role:"assistant",parts:[]})}}function xe(e,t){const s=t.parts.map(l=>Qo(l));s!==t.parts&&(t={...t,parts:s});const n="name"in e&&typeof e.name=="string"?e.name:void 0;let r=n!==void 0?{...t,name:n}:t,i;if("metadata"in e){const l=e.metadata;l!=null&&typeof l=="object"&&!Array.isArray(l)&&(i=l,r={...r,metadata:i})}const o=ie(r.createdAt)??(i!==void 0?Wo(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:l,...c}=r;r=c}const a=B(i)?.uiResources,u=Array.isArray(a)?a.filter(ms):[];return Jo(r,u)}function Xo(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 $d(e){if(typeof e=="string")return e?[{type:"text",content:e}]:[];const t=[];for(const s of e)s.type==="text"?t.push({type:"text",content:s.text}):s.type!=="binary"&&t.push(s);return t}function Bd(e,t){if("parts"in e){const s=e.parts.map(n=>Qo(n));return{...e,parts:s,id:e.id||t(),createdAt:ie(e.createdAt)??new Date}}else return{...ls(e,t()),createdAt:ie(e.createdAt)??new Date}}function Ne(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function Wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ls(e,t,s,n,r=!1){const i=Wr(e)?e:{},o=Wr(i.tanstack)?{...i.tanstack}:{};r&&delete o.uiResources;const a=ie(t),u={...s!==void 0?{id:s}:{},...a&&{createdAt:a.toISOString()},...Array.isArray(n)&&{content:n}},l={...i,tanstack:{...o,toolResult:u}};return Object.keys(l).length?l:void 0}function Ud(e,t){const s=[],n=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=Ds(Jd(o.id,o.toolCallId,i),n),f=Ls(o.metadata,o.createdAt,o.id,o.content);s.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:ls(o,o.id),u=a.parts;if(n.add(a.id),o.role==="system"){s.push(Ns(a,"system",{content:u.length>0?vn(u):o.content??""},u,r));continue}if(o.role==="user"){s.push(Ns(a,"user",{content:u.length>0?qd(u):o.content??""},u,r));continue}for(const d of u)if(d.type==="thinking"){const f={role:"reasoning",id:Yo(Wd(a.id,d),n),content:d.content};d.signature&&(f.encryptedValue=d.signature),s.push(f)}const l=vn(u),c=Qd(u);s.push(Ns(a,"assistant",{...l!==""&&{content:l},...c&&{toolCalls:c}},u,r));const h=new Set(u.flatMap(d=>d.type==="tool-result"?[d.toolCallId]:[]));for(const d of u)if(d.type==="tool-result"){const f=Ds(d.id??Sn(d.toolCallId),n),p=Ls(d.metadata,d.createdAt,d.id,d.content,!0);s.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?zn(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);s.push({role:"tool",id:Ds(Sn(d.id),n),toolCallId:d.id,content:g,metadata:Ls(void 0,void 0,void 0,p)})}}return s}function Ns(e,t,s,n,r){const i=Hd(e,n,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(s.content??"")}:t==="user"?{...o,role:t,content:s.content??""}:{...o,role:t,...typeof s.content=="string"&&{content:s.content},...s.toolCalls!==void 0&&{toolCalls:s.toolCalls}}}function Hd(e,t,s){const n={...e.metadata??{}},r=B(e),i={};r?.model!==void 0&&(i.model=r.model),r?.signature!==void 0&&(i.signature=r.signature);const o=ie(e.createdAt);o!==void 0&&(i.createdAt=o.toISOString());const a=zd(t,s);a&&(i.structuredOutput=a);const u={};for(const c of t)c.type==="tool-call"&&c.metadata!==void 0&&(u[c.id]=c.metadata);Object.keys(u).length>0&&(i.toolCallMetadata=u);const l=t.filter(c=>c.type==="ui-resource");return l.length>0&&(i.uiResources=l),Object.keys(i).length>0?n.tanstack=i:delete n.tanstack,Object.keys(n).length>0?n:void 0}function zd(e,t){for(const s of e)if(s.type==="structured-output"&&(t||s.status!=="complete"))return Vd(s,t)}function Vd(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 vn(e){const t=[];for(const s of e)s.type==="text"?t.push(s.content):s.type==="structured-output"&&s.status==="complete"&&s.raw!==""&&t.push(s.raw);return t.join("")}function qd(e){if(!e.some(s=>s.type==="image"||s.type==="audio"||s.type==="video"||s.type==="document"))return vn(e);const t=[];for(const s of e)s.type==="text"?t.push({type:"text",text:s.content}):(s.type==="image"||s.type==="audio"||s.type==="video"||s.type==="document")&&t.push(s);return t}function Kd(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 Qd(e){const t=[];for(const s of e)if(s.type==="tool-call"){const n=Kd(s.metadata);t.push({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments},...n!==void 0?{encryptedValue:n}:{}})}return t.length>0?t:void 0}function Wd(e,t){return`${e}-reasoning-${t.id??Xd(t.content)}`}function Sn(e){return`tool-${e}`}function Ds(e,t){return Yo(e,t)}function Yo(e,t){if(!t.has(e))return t.add(e),e;let s=2;for(;t.has(`${e}-${s}`);)s++;const n=`${e}-${s}`;return t.add(n),n}function Jd(e,t,s){const n=Sn(t);return e===void 0||s.has(e)?n:e}function Xd(e){let t=0;for(let s=0;s<e.length;s++)t=t*31+e.charCodeAt(s)|0;return Math.abs(t).toString(36)}function Yd(e){if((e.type===Ut.RUN_FINISHED||e.type===Ut.RUN_ERROR)&&(Array.isArray(e.usage)||Do(e.usage))){const t=nd(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 Zo(e){Yd(e);const t=B(e),s=e;if(t==null)return s;for(const[n,r]of Object.entries(t))n==="usage"||n==="interruptErrors"||s[n]===void 0&&r!==void 0&&(s[n]=r);return t.interruptErrors!==void 0&&(s["tanstack:interruptErrors"]=t.interruptErrors),s}function Jr(e){return typeof e=="string"&&e!==""?e:void 0}function ea(e){if("runId"in e){const t=Jr(e.runId);if(t!==void 0)return t}return Jr(B(e)?.runId)}var Xr=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})),Zd=tt((e=>{var t=e&&e.__createBinding||(Object.create?(function(l,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(l,d,f)}):(function(l,c,h,d){d===void 0&&(d=h),l[d]=c[h]})),s=e&&e.__exportStar||function(l,c){for(var h in l)h!=="default"&&!Object.prototype.hasOwnProperty.call(c,h)&&t(c,l,h)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var n=Xr();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return n.Allow}}),s(Xr(),e);var r=class extends Error{};e.PartialJSON=r;var i=class extends Error{};e.MalformedJSON=i;function o(l,c=n.Allow.ALL){if(typeof l!="string")throw new TypeError(`expecting str, got ${typeof l}`);if(!l.trim())throw new Error(`${l} is empty`);return a(l.trim(),c)}e.parseJSON=o;var a=(l,c)=>{const h=l.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"),l[d]==='"'?v():l[d]==="{"?m():l[d]==="["?S():l.substring(d,d+4)==="null"||n.Allow.NULL&c&&h-d<4&&"null".startsWith(l.substring(d))?(d+=4,null):l.substring(d,d+4)==="true"||n.Allow.BOOL&c&&h-d<4&&"true".startsWith(l.substring(d))?(d+=4,!0):l.substring(d,d+5)==="false"||n.Allow.BOOL&c&&h-d<5&&"false".startsWith(l.substring(d))?(d+=5,!1):l.substring(d,d+8)==="Infinity"||n.Allow.INFINITY&c&&h-d<8&&"Infinity".startsWith(l.substring(d))?(d+=8,1/0):l.substring(d,d+9)==="-Infinity"||n.Allow._INFINITY&c&&1<h-d&&h-d<9&&"-Infinity".startsWith(l.substring(d))?(d+=9,-1/0):l.substring(d,d+3)==="NaN"||n.Allow.NAN&c&&h-d<3&&"NaN".startsWith(l.substring(d))?(d+=3,NaN):C()),v=()=>{const w=d;let R=!1;for(d++;d<h&&(l[d]!=='"'||R&&l[d-1]==="\\");)R=l[d]==="\\"?!R:!1,d++;if(l.charAt(d)=='"')try{return JSON.parse(l.substring(w,++d-Number(R)))}catch(y){p(String(y))}else if(n.Allow.STR&c)try{return JSON.parse(l.substring(w,d-Number(R))+'"')}catch{return JSON.parse(l.substring(w,l.lastIndexOf("\\"))+'"')}f("Unterminated string literal")},m=()=>{d++,b();const w={};try{for(;l[d]!=="}";){if(b(),d>=h&&n.Allow.OBJ&c)return w;const R=v();b(),d++;try{w[R]=g()}catch(y){if(n.Allow.OBJ&c)return w;throw y}b(),l[d]===","&&d++}}catch{if(n.Allow.OBJ&c)return w;f("Expected '}' at end of object")}return d++,w},S=()=>{d++;const w=[];try{for(;l[d]!=="]";)w.push(g()),b(),l[d]===","&&d++}catch{if(n.Allow.ARR&c)return w;f("Expected ']' at end of array")}return d++,w},C=()=>{if(d===0){l==="-"&&p("Not sure what '-' is");try{return JSON.parse(l)}catch(R){if(n.Allow.NUM&c)try{return JSON.parse(l.substring(0,l.lastIndexOf("e")))}catch{}p(String(R))}}const w=d;for(l[d]==="-"&&d++;l[d]&&",]}".indexOf(l[d])===-1;)d++;d==h&&!(n.Allow.NUM&c)&&f("Unterminated number literal");try{return JSON.parse(l.substring(w,d))}catch{l.substring(w,d)==="-"&&f("Not sure what '-' is");try{return JSON.parse(l.substring(w,l.lastIndexOf("e")))}catch(y){p(String(y))}}},b=()=>{for(;d<h&&`
9
+ \r `.includes(l[d]);)d++};return g()},u=o;e.parse=u})),eh=Zd(),th=class{parse(e){if(!(!e||e.trim()===""))try{return(0,eh.parse)(e)}catch{return}}},ta=new th;function sh(e){return ta.parse(e)}var nh=class{shouldEmit(e,t){return!0}};function rh(e){const t=new Error(e.message||e.error?.message||"An error occurred"),s=e.code??e.error?.code;return s!==void 0&&Object.assign(t,{code:s}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}function ih(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type==="text"?r[r.length-1]={type:"text",content:s}:r.push({type:"text",content:s}),{...n,parts:r}})}function Ht(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.find(l=>l.type==="tool-call"&&l.id===s.id),o=s.metadata??i?.metadata,a=s.input??i?.input,u={type:"tool-call",id:s.id,name:s.name,arguments:s.arguments,state:s.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)]=u:r.push(u),{...n,parts:r}})}function Yr(e,t,s,n,r,i){return e.map(o=>{if(o.id!==t)return o;const a=[...o.parts],u=a.findIndex(c=>c.type==="tool-result"&&c.toolCallId===s),l={type:"tool-result",toolCallId:s,content:n,state:r,...i&&{error:i}};return u>=0?a[u]=l:a.push(l),{...o,parts:a}})}function Zr(e,t,s,n){return e.map(r=>{if(r.id!==t)return r;const i=[...r.parts],o=i.find(a=>a.type==="tool-call"&&a.id===s);if(o){const a=i.indexOf(o);i[a]={...o,state:"approval-requested",approval:{id:n,needsApproval:!0}}}return{...r,parts:i}})}function ei(e,t,s,n,r){return e.map(i=>{const o=[...i.parts],a=o.find(u=>u.type==="tool-call"&&u.id===t);if(a){const u=o.indexOf(a);o[u]={...a,output:r?{error:r}:s,state:n??(r?"error":"complete")}}return{...i,parts:o}})}function oh(e,t,s){return e.map(n=>{const r=[...n.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:s},state:"approval-responded"}}return{...n,parts:r}})}function ah(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.findIndex(h=>h.type==="structured-output"),o=i>=0?r[i]:null,a=(o?.raw??"")+s,u=sh(a),l=u??o?.partial,c={type:"structured-output",status:"streaming",raw:a,...l!==void 0?{partial:l}:{},...o?.reasoning!==void 0?{reasoning:o.reasoning}:{}};return i>=0?r[i]=c:r.push(c),{...n,parts:r}})}function lh(e,t,s,n,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(h=>h.type==="structured-output"),u=a>=0?o[a].raw:"";let l=n||u;if(l===""&&s!==void 0)try{l=JSON.stringify(s)}catch{}const c={type:"structured-output",status:"complete",data:s,partial:s,raw:l,...r!==void 0?{reasoning:r}:{}};return a>=0?o[a]=c:o.push(c),{...i,parts:o}})}function ti(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.findIndex(a=>a.type==="structured-output");if(i<0)return r.push({type:"structured-output",status:"error",raw:"",errorMessage:s}),{...n,parts:r};const o=r[i];return o.status==="complete"?n:(r[i]={...o,status:"error",errorMessage:s},{...n,parts:r})})}function js(e,t,s,n,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(l=>l.type==="thinking"&&l.stepId===s),u={type:"thinking",content:n,stepId:s,...r&&{signature:r}};return a>=0?o[a]=u:o.push(u),{...i,parts:o}})}var uh=12;function ch(e){return e.some(t=>{const s=t.metadata;if(!s||typeof s!="object"||Array.isArray(s))return!1;const n=s[ps];return n!==null&&typeof n=="object"&&!Array.isArray(n)&&n.kind==="generic"})}var dh=class sa{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 nh,this.events=t.events||{},this.jsonParser=t.jsonParser||ta,this.recordingEnabled=t.recording??!1,t.initialMessages&&(this.messages=[...t.initialMessages])}setMessages(t){this.messages=[...t],this.emitMessagesChange()}prependMessages(t){const s=new Set(this.messages.map(r=>r.id)),n=[];for(const r of t)s.has(r.id)||(s.add(r.id),n.push(r));this.messages=[...n,...this.messages],this.emitMessagesChange()}addUserMessage(t,s,n){const r=typeof t=="string"?[{type:"text",content:t}]:t.map(o=>o),i={id:s??Ne(),role:"user",parts:r,createdAt:new Date,...n!=null?{metadata:n}:{}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(t){this.prepareAssistantMessage();const{messageId:s}=this.ensureAssistantMessage(t);return this.pendingManualMessageId=s,s}getCurrentAssistantMessageId(){let t=null;for(const[s,n]of this.messageStates)n.role==="assistant"&&(t=s);return t}addToolResult(t,s,n){const r=this.messages.find(u=>u.parts.some(l=>l.type==="tool-call"&&l.id===t));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${t}`);return}let i=ei(this.messages,t,s,n?"error":void 0,n);const o=zn(s),a=n?"error":"complete";i=Yr(i,r.id,t,o,a,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(t,s){this.messages=oh(this.messages,t,s),this.emitMessagesChange()}toModelMessages(){const t=[];for(const s of this.messages)t.push(...Ld(s));return t}getMessages(){return this.messages}areAllToolsComplete(){const t=this.messages.findLast(r=>r.role==="assistant");if(!t)return!0;const s=t.parts.filter(r=>r.type==="tool-call");if(s.length===0)return!0;const n=new Set(t.parts.filter(r=>r.type==="tool-result").map(r=>r.toolCallId));return s.every(r=>r.state==="complete"||r.state==="approval-responded"||r.output!==void 0&&!r.approval||n.has(r.id)||Vo(r))}removeMessagesAfter(t){const s=new Set(this.messages.slice(0,t+1).map(n=>n.id));for(const n of this.structuredMessageIds)s.has(n)||this.structuredMessageIds.delete(n);for(const n of this.structuredOutputUpdateBatches.keys())s.has(n)||this.structuredOutputUpdateBatches.delete(n);for(const n of this.messageStates.keys())s.has(n)||this.messageStates.delete(n);for(const[n,r]of this.toolCallToMessage)s.has(r)||this.toolCallToMessage.delete(n);for(const n of this.activeMessageIds)s.has(n)||this.activeMessageIds.delete(n);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 s of t)this.processChunk(s);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,s){const n={id:t,role:s,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,n),n}getMessageState(t){return this.messageStates.get(t)}consumePendingThinkingStep(t){if(!this.pendingThinkingStepId)return;const s=this.pendingThinkingStepId;t.currentThinkingStepId=s,t.thinkingSteps.has(s)||(t.thinkingSteps.set(s,""),t.thinkingStepOrder.push(s)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){const t=Array.from(this.activeMessageIds).reverse();for(const s of t){const n=this.messageStates.get(s);if(n&&n.role==="assistant")return s}for(const[s,n]of[...this.messageStates].reverse())if(n.role==="assistant")return s;return null}resumeAssistantState(t,s){this.activeMessageIds.add(t),(s.isComplete||this.isDone)&&(s.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 s=this.getActiveAssistantMessageId();if(s){const o=this.getMessageState(s);if(o)return this.resumeAssistantState(s,o),{messageId:s,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 u=o.parts.length>0?o.parts[o.parts.length-1]:null;return u&&u.type==="text"&&(a.currentSegmentText=u.content,a.lastEmittedText=u.content,a.totalTextContent=u.content),{messageId:t,state:a}}}const n=t||Ne(),r={id:n,role:"assistant",parts:[],createdAt:new Date};this.messages=[...this.messages,r];const i=this.createMessageState(n,"assistant");return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}mergeMessageMetadata(t,s){if(s==null||typeof s!="object"||Array.isArray(s))return;const n=this.messages.find(c=>c.id===t);if(!n)return;const r=s,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=jo(n.metadata,o),u=ie(B(r)?.createdAt),l=u!==void 0;this.messages=this.messages.map(c=>c.id===t?{...c,...a!==void 0?{metadata:a}:{},...l?{createdAt:u}:{}}:c),this.emitMessagesChange()}handleTextMessageStartEvent(t){const{messageId:s,role:n}=t,r=n==="user"||n==="system"?n:"assistant";if(this.pendingManualMessageId){const o=this.pendingManualMessageId;if(this.pendingManualMessageId=null,o!==s){this.messages=this.messages.map(l=>l.id===o?{...l,id:s}:l);const u=this.messageStates.get(o);u&&(u.id=s,this.messageStates.delete(o),this.messageStates.set(s,u)),this.activeMessageIds.delete(o),this.activeMessageIds.add(s);for(const[l,c]of this.toolCallToMessage)c===o&&this.toolCallToMessage.set(l,s)}let a=this.messageStates.get(s);a?a.hasToolCallsSinceTextStart&&(a.currentSegmentText!==a.lastEmittedText&&this.emitTextUpdateForMessage(s),a.currentSegmentText="",a.lastEmittedText="",a.hasToolCallsSinceTextStart=!1):(a=this.createMessageState(s,r),this.activeMessageIds.add(s)),this.mergeMessageMetadata(s,t.metadata),this.emitMessagesChange();return}if(this.messages.find(o=>o.id===s)){this.activeMessageIds.add(s);const o=this.messageStates.get(s);o?o.hasToolCallsSinceTextStart&&(o.currentSegmentText!==o.lastEmittedText&&this.emitTextUpdateForMessage(s),o.currentSegmentText="",o.lastEmittedText="",o.hasToolCallsSinceTextStart=!1):this.createMessageState(s,r),this.mergeMessageMetadata(s,t.metadata);return}const i={id:s,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(s,r),this.activeMessageIds.add(s),this.mergeMessageMetadata(s,t.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(t){const{messageId:s}=t;this.mergeMessageMetadata(s,t.metadata);const n=this.getMessageState(s);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s))}handleMessagesSnapshotEvent(t){this.resetStreamState();const s=this.messages,n=new Map(s.map(i=>[i.id,i])),r=this.mergeReasoningFanOut(t.messages.map(Gd));this.messages=this.reconcileSnapshotToolCalls(r,s).map(i=>{if(i.metadata!=null)return i;const o=n.get(i.id);return o?.metadata==null?i:{...i,metadata:o.metadata}}),this.emitMessagesChange()}mergeReasoningFanOut(t){const s=[];let n=[];const r=u=>u.parts.filter(l=>l.type==="thinking"),i=u=>u.role==="assistant"&&u.parts.length>0&&u.parts.every(l=>l.type==="thinking"),o=u=>u.role==="assistant"&&u.parts.some(l=>l.type==="tool-result")&&u.parts.every(l=>l.type==="tool-result"||l.type==="ui-resource"),a=()=>{s.push(...n),n=[]};for(const u of t){if(i(u)){n.push(u);continue}if(u.role==="assistant"&&n.length>0&&!o(u)){s.push({...u,parts:[...n.flatMap(r),...u.parts]}),n=[];continue}a(),s.push(u)}return a(),s}reconcileSnapshotToolCalls(t,s){const n=new Map;for(const o of s)for(const a of o.parts)a.type==="tool-call"&&n.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"),u=o.role==="assistant"&&a.length===1&&o.parts.every(h=>h.type==="tool-result"||h.type==="ui-resource")?a[0]:void 0;if(!u){i.push(o);continue}const l=i.findLast(h=>h.parts.some(d=>d.type==="tool-call"&&d.id===u.toolCallId))??i.findLast(h=>h.role==="assistant"&&!(h.parts.length===1&&h.parts[0]?.type==="tool-result"));if(!l){r.has(u.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${u.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${u.toolCallId}") will not be able to locate this call`),i.push(o);continue}const c=[...l.parts];if(!r.has(u.toolCallId)&&!c.some(h=>h.type==="tool-call"&&h.id===u.toolCallId)){const h=n.get(u.toolCallId);h?(c.push({...h}),r.add(h.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${u.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${u.toolCallId}") will not be able to locate this call`)}c.push(...o.parts),l.parts=c}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(t,s){const n=new Map;for(const r of t)for(const i of r.parts)i.type==="tool-result"&&n.set(i.toolCallId,i);return t.map(r=>{const i=r.parts.map(o=>{if(o.type!=="tool-call")return o;const a=s.get(o.id),u=n.get(o.id);let l=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")&&(l={...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}:{}}),u&&l.output===void 0){let c;if(Array.isArray(u.content))c=u.content;else try{c=JSON.parse(u.content)}catch{c=u.content}const h=u.state==="error"?this.extractToolResultError(c):void 0;l={...l,output:h?{error:h}:c,state:u.state==="error"?"error":"complete"}}return l});return i.some((o,a)=>o!==r.parts[a])?{...r,parts:i}:r})}handleTextMessageContentEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(t.messageId);if(this.mergeMessageMetadata(s,t.metadata),this.structuredMessageIds.has(s)){const c=t.delta||"";c!==""&&(this.messages=ah(this.messages,s,c),n.totalTextContent+=c,this.queueStructuredOutputUpdate(s,c),this.emitMessagesChange());return}const r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(t,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),n.currentSegmentText="",n.lastEmittedText="",n.hasToolCallsSinceTextStart=!1),n.hasToolCallsSinceTextStart=!1;const i=n.currentSegmentText,o=t.delta||"",a=o!==""?i+o:i,u=a.slice(i.length);n.currentSegmentText=a,n.totalTextContent+=u;const l=t.delta||"";this.chunkStrategy.shouldEmit(l,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s)}handleToolCallStartEvent(t){const s=t.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(s??void 0);r.hasToolCallsSinceTextStart=!0;const i=t.toolCallId;if(!r.toolCalls.get(i)){const o="awaiting-input",a=t.toolCallName,u=t.metadata,l={id:t.toolCallId,name:a,arguments:"",state:o,parsedArguments:void 0,index:r.toolCalls.size,...u!==void 0&&{metadata:u}};r.toolCalls.set(i,l),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=Ht(this.messages,n,{id:t.toolCallId,name:a,arguments:"",state:o,...u!==void 0&&{metadata:u}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,t.toolCallId,o,"")}}handleToolCallArgsEvent(t){const s=t.toolCallId,n=this.toolCallToMessage.get(s);if(!n)return;const r=this.getMessageState(n);if(!r)return;const i=r.toolCalls.get(s);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,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(t){const s=this.toolCallToMessage.get(t.toolCallId);if(!s)return;const n=this.getMessageState(s);if(!n)return;const r=t.input!==void 0?t.input:B(t)?.input,i=n.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=n.toolCallOrder.indexOf(t.toolCallId);this.completeToolCall(s,o,i),r!==void 0&&(i.parsedArguments=r,this.messages=Ht(this.messages,s,{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 s=this.toolCallToMessage.get(t.toolCallId)??this.messages.find(o=>o.parts.some(a=>a.type==="tool-call"&&a.id===t.toolCallId))?.id;if(!s)return;const n=t.state==="output-error"||B(t)?.state==="output-error";let r;try{r=JSON.parse(t.content)}catch{r=t.content}this.messages=ei(this.messages,t.toolCallId,r,n?"error":void 0);const i=n?"error":"complete";this.messages=Yr(this.messages,s,t.toolCallId,t.content,i,i==="error"?this.extractToolResultError(r):void 0),this.emitMessagesChange()}handleRunStartedEvent(t){this.activeRuns.add(t.runId)}handleRunFinishedEvent(t){const s=t;if(this.finishReason=s.finishReason!==void 0?s.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 s=ch(t);for(const n of t){const r=n.metadata&&typeof n.metadata=="object"?n.metadata:{},i=typeof r.kind=="string"?r.kind:void 0,o=n.toolCallId;if(!o)continue;const a=typeof r.toolName=="string"?r.toolName:this.findToolCallName(o),u=Object.hasOwn(r,"input")?r.input:{};if(i==="approval"||n.reason==="approval_required"){const l=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;l&&(this.messages=Zr(this.messages,l,o,n.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:o,toolName:a,input:u,approvalId:n.id});continue}if(i==="client_tool"||n.reason==="client_tool_input"){if(s)continue;this.events.onToolCall?.({toolCallId:o,toolName:a,input:u})}}}findToolCallName(t){for(const s of this.messageStates.values()){const n=s.toolCalls.get(t);if(n)return n.name}return""}handleRunErrorEvent(t){this.hasError=!0;const s=ea(t);s?this.activeRuns.delete(s):this.activeRuns.clear();const{messageId:n}=this.ensureAssistantMessage(),r=t.message||"An error occurred";t.message||console.error("[StreamProcessor] RUN_ERROR with no message; original chunk:",t),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=ti(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,"error"),this.emitMessagesChange()),this.events.onError?.(rh(t))}handleStepStartedEvent(t){const s=t.stepName||Ne(),n=this.getActiveAssistantMessageId();if(n){const r=this.getMessageState(n);if(r){r.currentThinkingStepId=s,r.thinkingSteps.has(s)||(r.thinkingSteps.set(s,""),r.thinkingStepOrder.push(s)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=s}handleStepFinishedEvent(t){const s=t,n=s.signature;if(!n)return;const{messageId:r,state:i}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),o=i.currentThinkingStepId??s.stepId;if(!o)return;const a=i.thinkingSteps.get(o);a!==void 0&&(i.thinkingStepSignatures.set(o,n),this.messages=js(this.messages,r,o,a,n),this.emitMessagesChange())}handleReasoningMessageContentEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;const r=t.delta||"";this.consumePendingThinkingStep(n);const i=n.currentThinkingStepId??t.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,""),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);const o=(n.thinkingSteps.get(i)??"")+r;n.thinkingSteps.set(i,o),this.messages=js(this.messages,s,i,o,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(s,i,o)}handleReasoningEncryptedValueEvent(t){const s=t.encryptedValue;if(typeof s!="string"||s==="")return;if(t.subtype==="tool-call"){this.attachToolCallSignature(t.entityId,s);return}const{messageId:n,state:r}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),i=r.currentThinkingStepId??t.entityId;r.thinkingStepSignatures.set(i,s);const o=r.thinkingSteps.get(i)??"";r.thinkingSteps.has(i)||(r.thinkingSteps.set(i,o),r.thinkingStepOrder.push(i)),this.messages=js(this.messages,n,i,o,s),this.emitMessagesChange()}attachToolCallSignature(t,s){this.messages=this.messages.map(n=>{let r=!1;const i=n.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:s}}));return r?{...n,parts:i}:n});for(const n of this.messageStates.values()){const r=n.toolCalls.get(t);r&&(r.metadata={...r.metadata??{},thoughtSignature:s})}this.emitMessagesChange()}handleCustomEvent(t){const s=this.getActiveAssistantMessageId();if(t.name==="structured-output.start"&&t.value){const n=t.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??s??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 n=t.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??s??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=lh(this.messages,r,n.object,n.raw??"",n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,"complete"),this.emitMessagesChange())}if(t.name==="tool-input-available"&&t.value){const{toolCallId:n,toolName:r,input:i}=t.value;this.events.onToolCall?.({toolCallId:n,toolName:r,input:i});return}if(t.name==="approval-requested"&&t.value){const{toolCallId:n,toolName:r,input:i,approval:o}=t.value,a=s??this.toolCallToMessage.get(n);a&&(this.messages=Zr(this.messages,a,n,o.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:o.id});return}if(t.name==="ui-resource"&&t.value){const n=t.value,r=this.toolCallToMessage.get(n.toolCallId)??s;if(r){const i={type:"ui-resource",resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.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 "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){const n=t.value&&typeof t.value=="object"?t.value.toolCallId:void 0;this.events.onCustomEvent(t.name,t.value,{toolCallId:n})}}isNewTextSegment(t,s){return!0}completeAllToolCalls(){for(const t of this.activeMessageIds)this.completeAllToolCallsForMessage(t)}completeAllToolCallsForMessage(t){const s=this.getMessageState(t);s&&s.toolCalls.forEach((n,r)=>{if(n.state!=="input-complete"){const i=s.toolCallOrder.indexOf(r);this.completeToolCall(t,i,n)}})}completeToolCall(t,s,n){n.state="input-complete";let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartErrored(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=Ht(this.messages,t,{id:n.id,name:n.name,arguments:n.arguments,state:"input-complete",...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(t,n.id,"input-complete",n.arguments))}isToolCallPartAwaitingUserAction(t){return this.messages.some(s=>s.parts?.some(n=>n.type==="tool-call"&&n.id===t&&(n.state==="approval-requested"||n.state==="approval-responded")))}isToolCallPartErrored(t){return this.messages.some(s=>s.parts?.some(n=>n.type==="tool-call"&&n.id===t&&n.state==="error"))}emitTextUpdateForMessage(t){const s=this.getMessageState(t);s&&(s.lastEmittedText=s.currentSegmentText,this.messages=ih(this.messages,t,s.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(t,s.currentSegmentText))}queueStructuredOutputUpdate(t,s){const n=this.structuredOutputUpdateBatches.get(t),r={delta:`${n?.delta??""}${s}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(t,r),r.chunkCount>=uh&&this.flushStructuredOutputUpdate(t)}flushStructuredOutputUpdate(t){const s=this.structuredOutputUpdateBatches.get(t);!s||s.chunkCount===0||(this.structuredOutputUpdateBatches.delete(t),this.emitStructuredOutputChange(t,"update",s.delta))}emitStructuredOutputChange(t,s,n){const r=this.messages.find(i=>i.id===t)?.parts.find(i=>i.type==="structured-output");r&&this.events.onStructuredOutputChange?.({phase:s,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}:{},...n!==void 0?{delta:n}:{}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;let t;for(const s of this.activeMessageIds){const n=this.getMessageState(s);if(!n)continue;this.completeAllToolCallsForMessage(s),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),n.isComplete=!0;const r=this.messages.find(i=>i.id===s);r&&r.role==="assistant"&&(t=r)}for(const s of this.structuredMessageIds)this.flushStructuredOutputUpdate(s),this.messages=ti(this.messages,s,"Stream ended without structured-output.complete"),this.emitStructuredOutputChange(s,"error");if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),t&&!this.hasError&&this.isWhitespaceOnlyMessage(t)){this.messages=this.messages.filter(s=>s.id!==t.id),this.emitMessagesChange();return}t&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(t))}getCompletedToolCalls(){const t=[];for(const s of this.messageStates.values())for(const n of s.toolCalls.values())n.state==="input-complete"&&t.push({id:n.id,type:"function",function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return t}getResult(){const t=this.getCompletedToolCalls();let s="",n="";for(const r of this.messageStates.values()){s+=r.totalTextContent;for(const i of r.thinkingStepOrder)n+=r.thinkingSteps.get(i)??""}return{content:s,thinking:n||void 0,toolCalls:t.length>0?t:void 0,finishReason:this.finishReason}}getState(){let t="",s="";const n=new Map,r=[];for(const i of this.messageStates.values()){t+=i.totalTextContent;for(const o of i.thinkingStepOrder)s+=i.thinkingSteps.get(o)??"";for(const[o,a]of i.toolCalls)n.set(o,a);r.push(...i.toolCallOrder)}return{content:t,thinking:s,toolCalls:n,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(s=>s.type==="text"&&s.content.trim()==="")}static async replay(t,s){return new sa(s).process(hh(t))}};function hh(e){return{async*[Symbol.asyncIterator](){for(const{chunk:t}of e.chunks)yield t}}}var yn=(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})({}),na=new WeakMap;function ne(e){return na.get(e)??ea(e)}var ra=class extends Error{constructor(){super("Stream ended with unterminated trailing data — connection was likely cut short."),this.name="StreamTruncatedError"}},Vn=class extends Error{constructor(e){super("Stream response body read failed",{cause:e}),this.name="StreamReadError"}},fh=class extends Error{constructor(){super("Durable run ended without a terminal event and could not resume — the run did not complete."),this.name="DurableStreamIncompleteError"}},ph=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name="StreamReconnectLimitError"}};function gh(e){const t=e?.maxAttempts??5,s=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(s)||s<0)throw new Error(`Invalid reconnect.delayMs: ${s}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:s}}function mh(e){const t=gh(e),s=new Set;let n,r=0;return{get lastEventId(){return n},note(i){return i===void 0?"new":i===""?(n=void 0,s.clear(),"reset"):s.has(i)?"duplicate":(s.add(i),n=i,"new")},async waitBeforeReconnect(i,o){if(i)r=0;else if(r+=1,r>t.maxAttempts)throw new ph(t.maxAttempts);await vh(t.delayMs,o)}}}function vh(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(s=>{const n=()=>{clearTimeout(r),s()},r=setTimeout(()=>{t?.removeEventListener("abort",n),s()},e);t?.addEventListener("abort",n,{once:!0})})}function si(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((s,n)=>{t[n]=s}),t}return e}var Sh="X-Run-Id";function yh(e){return e===void 0?{}:{[Sh]:e}}function qn(e,t){const s=e.indexOf("#"),n=s===-1?"":e.slice(s),r=s===-1?e:e.slice(0,s),i=r.indexOf("?"),o=i===-1?r:r.slice(0,i),a=new URLSearchParams(i===-1?"":r.slice(i+1));for(const[l,c]of Object.entries(t))a.set(l,c);const u=a.toString();return`${o}${u.length===0?"":`?${u}`}${n}`}async function*Ih(e,t){try{const s=ed();let n="";for(;!t?.aborted;){let r;try{r=await e.read()}catch(u){if(t?.aborted)return;throw new Vn(u)}const{done:i,value:o}=r;if(i)break;n+=s.decode(o,{stream:!0});const a=n.split(`
10
+ `);n=a.pop()||"";for(const u of a){const l=u.endsWith("\r")?u.slice(0,-1):u;l.trim()&&(yield l)}}if(n+=s.decode(),n.trim()&&!t?.aborted)throw new ra}finally{e.releaseLock()}}function Rh(e){return Zo(e)}function Ch(e){const t=B(e)?.model;if(typeof t=="string")return t;const s="usage"in e?e.usage:void 0;if(Array.isArray(s)){const n=s[0]?.model;if(typeof n=="string")return n}}async function*bh(e,t){let s,n,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=td(o);if(a==="[DONE]"){yield{chunk:Go({type:yn.RUN_FINISHED,threadId:s??t?.threadId??"",runId:n??t?.runId??"",timestamp:Date.now()},{finishReason:"stop",...r!==void 0?{model:r}:{}})};return}const u=Rh(JSON.parse(a));"threadId"in u&&typeof u.threadId=="string"&&(s=u.threadId),"runId"in u&&typeof u.runId=="string"&&(n=u.runId);const l=Ch(u);l!==void 0&&(r=l);const c=i;i=void 0,yield{chunk:u,...c!==void 0?{id:c}:{}}}}async function Kn(e){if(!e.ok){if(e.status===401){const t=await e.clone().json().catch(()=>null);if(Kc(t))throw new cn(t.error.provider)}throw new Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}function wh(e,t){const s={threadId:e};return t?.limit!==void 0&&(s.limit=String(t.limit)),t?.before!==void 0&&(s.before=t.before),s}function Eh(e){return e===null||typeof e!="object"?{truncated:!1}:!("truncated"in e)||e.truncated!==!0?{truncated:!1}:!("cursor"in e)||typeof e.cursor!="string"||e.cursor===""?{truncated:!1}:{truncated:!0,cursor:e.cursor}}async function _h(e,t,s,n,r,i){const o=await e(qn(t,wh(r,i)),{method:"GET",headers:{Accept:"application/json",...s},credentials:n});await Kn(o);const a=await o.json(),u=a.activeRun&&typeof a.activeRun.runId=="string"?{runId:a.activeRun.runId}:null,l=a.interrupts&&typeof a.interrupts.runId=="string"&&Array.isArray(a.interrupts.pending)&&a.interrupts.pending.length>0?{runId:a.interrupts.runId,pending:a.interrupts.pending}:null;return{messages:Array.isArray(a.messages)?hn(a.messages):[],activeRun:u,interrupts:l,page:Eh(a.page)}}async function Th(e,t,s,n,r){const i=await e(qn(t,{threadId:r}),{method:"GET",headers:{Accept:"application/json",...s},credentials:n});await Kn(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,u=a.activeRun&&typeof a.activeRun.runId=="string"?{runId:a.activeRun.runId}:null;return{resumeSnapshot:a.resumeSnapshot??null,activeRun:u}}async function*In(e,t,s){await Kn(e),yield*bh(Ih(Zc(e),t),s)}async function*Mh(e,t){for await(const{chunk:s}of In(e,t))yield s}function ni(e,t,s,n){return async function*(r,i){let o;try{o=await e(t,{...s,headers:{...s.headers,...r},...i?{signal:i}:{}})}catch(a){throw new Vn(a)}yield*n(o,i)}}async function*ri(e,t,s){const n=mh(s);for(;;){if(t?.aborted)return;const r=n.lastEventId!==void 0?{"Last-Event-ID":n.lastEventId}:{};let i=!1,o=!1;try{for await(const{chunk:a,id:u}of e(r,t))n.note(u)!=="duplicate"&&(o=!0,(a.type==="RUN_FINISHED"||a.type==="RUN_ERROR")&&(i=!0),yield a)}catch(a){if(t?.aborted)return;if((a instanceof ra||a instanceof Vn)&&n.lastEventId!==void 0){await n.waitBeforeReconnect(o,t);continue}throw a}if(t?.aborted||i)return;if(n.lastEventId!==void 0){if(o){await n.waitBeforeReconnect(!0,t);continue}throw new fh}return}}function ii(e){if(!e)throw new Error("Connection adapter is required");const t="connect"in e,s="subscribe"in e,n="send"in e;if(t&&(s||n))throw new Error("Connection adapter must provide either connect or both subscribe and send, not both modes");if(s&&n){const l=e.joinRun?.bind(e),c=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...l?{joinRun:l}:{},...c?{hydrate:c}:{}}}if(!t)throw new Error("Connection adapter must provide either connect or both subscribe and send");let r=[],i=[],o;function a(l,c){c&&na.set(l,c);const h=i.shift();h?h(l):r.push(l)}async function u(l){const c=()=>o!==i||r.length===0&&(i.length>0||l?.aborted);for(let h=0;h<16&&!l?.aborted;h++){if(c())return;await Promise.resolve()}for(;!l?.aborted;){if(c())return;await new Promise(h=>setTimeout(h,0))}}return{subscribe(l){const c=r.splice(0),h=[];return r=c,i=h,(async function*(){o=h;try{for(;!l?.aborted;){let d;const f=c.shift();f!==void 0?d=f:d=await new Promise(p=>{const g=()=>p(null);h.push(v=>{l?.removeEventListener("abort",g),p(v)}),l?.addEventListener("abort",g,{once:!0})}),d!==null&&(yield d)}}finally{o===h&&(o=void 0)}})()},async send(l,c,h,d){let f=!1,p,g;try{const v=e.connect(l,c,h,d);for await(const m of v)"threadId"in m&&typeof m.threadId=="string"&&(p=m.threadId),"runId"in m&&typeof m.runId=="string"&&(g=m.runId),(m.type==="RUN_FINISHED"||m.type==="RUN_ERROR")&&(f=!0),a(m,d?.runId);!h?.aborted&&!f&&a(Go({type:yn.RUN_FINISHED,threadId:zt(p??d?.threadId,"threadId"),runId:zt(g??d?.runId,"runId"),timestamp:Date.now()},{finishReason:"stop",model:"connect-wrapper"}),d?.runId)}catch(v){if(!h?.aborted&&!f)try{const m=v instanceof Error?v.message:"Unknown error in connect()";a({type:yn.RUN_ERROR,threadId:zt(p??d?.threadId,"threadId"),runId:zt(g??d?.runId,"runId"),timestamp:Date.now(),message:m},d?.runId)}catch{}throw v}await u(h)},...typeof e.joinRun=="function"?{joinRun:(l,c)=>e.joinRun(l,c)}:{},...(()=>{const l=e.hydrate;return typeof l=="function"?{hydrate:(c,h)=>l(c,h)}:{}})()}}function Ah(e,t,s,n){const r=Ud(e),i={...n.body,...s?.forwardedProps??{},...t};return{threadId:s?.threadId??si("thread"),runId:s?.runId??si("run"),...s?.parentRunId!==void 0&&{parentRunId:s.parentRunId},...s?.resume!==void 0&&{resume:s.resume},state:{},messages:r,tools:s?.clientTools??[],context:[],forwardedProps:i,data:{...i}}}function Zf(e,t={}){return{async*connect(s,n,r,i){const o=typeof e=="function"?e():e,a=typeof t=="function"?await t():t,u={"Content-Type":"application/json",...ct(a.headers),...ct(i?.headers),...yh(i?.runId)},l=Ah(s,n,i,a),c=a.fetchClient??fetch,h=r||a.signal;yield*ri(ni(c,o,{method:"POST",headers:u,body:JSON.stringify(l),credentials:a.credentials||"same-origin"},(d,f)=>In(d,f,{...i?.threadId!==void 0?{threadId:i.threadId}:{},...i?.runId!==void 0?{runId:i.runId}:{}})),h,a.reconnect)},async*joinRun(s,n){const r=typeof e=="function"?e():e,i=typeof t=="function"?await t():t,o=qn(r,{offset:"-1",runId:s}),a={...ct(i.headers)},u=i.fetchClient??fetch,l=n||i.signal;yield*ri(ni(u,o,{method:"GET",headers:a,credentials:i.credentials||"same-origin"},(c,h)=>In(c,h,{runId:s})),l,i.reconnect)},async hydrate(s,n){const r=typeof e=="function"?e():e,i=typeof t=="function"?await t():t;return _h(i.fetchClient??fetch,r,ct(i.headers),i.credentials||"same-origin",s,n)},async hydrateGeneration(s){const n=typeof e=="function"?e():e,r=typeof t=="function"?await t():t;return Th(r.fetchClient??fetch,n,ct(r.headers),r.credentials||"same-origin",s)}}}function Oh(e){return{async*connect(t,s,n,r){if(!n)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:s,threadId:r.threadId,runId:r.runId,...r.parentRunId!==void 0?{parentRunId:r.parentRunId}:{},...r.resume!==void 0?{resume:r.resume}:{}},{signal:n,headers:r.headers});i instanceof Response?yield*Mh(i,n):yield*xh(i,n)}}}async function*xh(e,t){if(t.aborted)return;const s=e[Symbol.asyncIterator](),n=new Promise(r=>{t.addEventListener("abort",()=>r({done:!0,value:void 0}),{once:!0})});try{for(;;){const r=await Promise.race([s.next(),n]);if(r.done)return;yield r.value}}finally{await s.return?.()}}function pe(e){return e.resumable}function Gs(e,t){const s=Ed(e.descriptor);return s?{...t,metadata:wd(s)}:t}function Ph(e){return"cancel"in e&&"clearResolution"in e}var kh=new Set(["invalid-payload","invalid-edited-args","invalid-tool-output","invalid-response-schema","unknown-interrupt","expired","stale","conflict","legacy-unsupported"]),Fh=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 ia(e){return ae(e)&&e.kind==="approval"&&typeof e.toolName=="string"&&"input"in e}function oa(e){return ae(e)&&e.kind==="client_tool"&&typeof e.toolName=="string"&&"input"in e}function Lh(e){return ia(e.metadata)||oa(e.metadata)}function oi(e){return Sd(e)}function Nh(e){if(!ae(e.metadata))return!1;const t=e.metadata[ps];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 Dh(e){if(!ae(e.metadata))return!1;const t=e.metadata[ps];return!ae(t)||t.kind!=="generic"?!1:"definitionId"in t||"key"in t||"batchIndex"in t||"payloadSchemaHash"in t}function jh(e){return e.metadata?.["tanstack:interruptPayload"]}function Gh(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 ai(e){if(e!==void 0)try{return Rd(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,s){if(e===void 0)return{valid:!0,payload:t};if(Ae(e)){const n=e["~standard"].validate(t),r=i=>i.issues?{code:s,message:i.issues[0]?.message??"Schema validation failed."}:{valid:!0,payload:i.value};return Pe(n)?Promise.resolve(n).then(r):r(n)}return{valid:!0,payload:t}}function $h(e){for(const t of kh)if(t===e)return!0;return!1}function Bh(e){for(const t of Fh)if(t===e)return!0;return!1}function li(e){if(!ae(e))return!1;const t=e.scope,s=e.code;return typeof s=="string"&&typeof e.message=="string"&&typeof e.retryable=="boolean"&&typeof e.threadId=="string"&&typeof e.interruptedRunId=="string"&&typeof e.generation=="number"?t==="item"?$h(s)&&typeof e.interruptId=="string"&&(e.source==="client"||e.source==="server"):t==="batch"&&Bh(s)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(n=>typeof n=="string")&&(e.source==="client"||e.source==="server"||e.source==="transport"):!1}function Uh(e){return li(e)?[e]:!ae(e)||!Array.isArray(e.errors)?[]:e.errors.every(li)?e.errors:[]}function aa(e,t){if(e.length!==t.length)return!1;const s=[...e].sort(),n=[...t].sort();return s.every((r,i)=>r===n[i])}function ui(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&aa(e.interruptIds,t.interruptIds)}function Hh(e,t,s){const n=s.filter(a=>a.source!=="transport"),r=a=>t.includes(a)&&n.some(u=>ui(a,u)),i=e.filter(a=>!r(a)),o=t.filter(a=>!n.some(u=>ui(a,u)));return Object.freeze({rootErrors:Object.freeze([...i,...s]),submissionRootErrors:Object.freeze([...o,...n])})}function zh(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;const s=t.resolutions.map(n=>n.interruptId);return e.scope==="item"?s.includes(e.interruptId):aa(e.interruptIds,s)}function $s(e,t,s){const n=ht(e)??s?.responseSchemaHash;return U({v:1,kind:"generic",interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...n!==void 0?{responseSchemaHash:n}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}})}function Vh(e,t){const s=U(e.descriptor),n=e.error===void 0?Object.freeze([]):Object.freeze([U(e.error)]),r=n[0];return{id:s.id,interruptId:s.id,reason:s.reason,...s.message!==void 0?{message:s.message}:{},...s.responseSchema!==void 0?{responseSchema:s.responseSchema}:{},...s.expiresAt!==void 0?{expiresAt:s.expiresAt}:{},...s.metadata!==void 0?{metadata:s.metadata}:{},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:n,...r!==void 0?{error:r}:{},canResolve:e.canResolve}}var qh=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 s of e.interrupts??[]){if(t.has(s.id))throw new Error(`Duplicate interrupt definition id: ${s.id}`);t.set(s.id,s)}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 s=new Map;for(const n of e.interrupts){const r=oi(n);r?.kind==="generic"&&r.definitionId!==void 0&&r.key!==void 0&&r.batchIndex!==void 0&&s.set(r.batchIndex,(s.get(r.batchIndex)??0)+1)}this.items=e.interrupts.map(n=>this.hydrateInterrupt(n,e,s)),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(Gs(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 s=this.items.find(n=>n.kind==="client-tool-execution"&&n.binding?.kind==="client-tool-execution"&&n.binding.toolCallId===e||n.kind==="generic"&&Gh(n.descriptor.reason)&&n.descriptor.toolCallId===e&&oa(n.descriptor.metadata));return s?(this.resolveItem(s.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){const s=this.items.find(n=>n.descriptor.id===e&&(n.kind==="tool-approval"||n.kind==="generic"&&n.descriptor.reason==="approval_required"&&ia(n.descriptor.metadata)));return s?(this.resolveItem(s.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,s){const n=U(e),r=oi(n),i=r===void 0&&Lh(n);if(r===void 0&&!i)return Nh(n)?{descriptor:n,binding:$s(n,t,void 0),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(n.id,"stale","The interrupt binding is invalid or incomplete."),validationGeneration:0}:{descriptor:n,binding:void 0,kind:"unbound",status:"pending",canResolve:!1,resumable:!1,validationGeneration:0};const o=r!==void 0&&r.interruptId===n.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&ht(n)===r.responseSchemaHash,a=r!==void 0&&r.interruptId===n.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&r.responseSchemaHash===(ht(n)??r.responseSchemaHash);if(r!==void 0&&Dh(n)&&(!a||r.kind!=="generic"||r.definitionId===void 0||r.key===void 0||r.batchIndex===void 0))return{descriptor:n,binding:$s(n,t,r),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(n.id,"stale","The interrupt binding does not match this interrupted run."),validationGeneration:0};if(a&&r.kind==="tool-approval"){const l=this.tools?.find(c=>c.name===r.toolName);if(l?.needsApproval===!0&&n.toolCallId===r.toolCallId)try{const c=md(l.approvalSchema,l.inputSchema);if(Vr(l.inputSchema)===r.inputSchemaHash&&c.approvalSchemaHash===r.approvalSchemaHash&&c.responseSchemaHash===r.responseSchemaHash)return{descriptor:n,binding:U(r),kind:"tool-approval",status:"pending",canResolve:!0,resumable:!0,tool:l,validationGeneration:0}}catch{}}if(a&&r.kind==="client-tool-execution"){const l=this.tools?.find(c=>c.name===r.toolName);if(l!==void 0&&n.toolCallId===r.toolCallId&&Vr(l.outputSchema)===r.outputSchemaHash)return{descriptor:n,binding:U(r),kind:"client-tool-execution",status:"pending",canResolve:!0,resumable:!0,tool:l,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&&s.get(r.batchIndex)!==1)return{descriptor:n,binding:U(r),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(n.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&&s.get(r.batchIndex)===1){const l=this.interruptDefinitions.get(r.definitionId);if(l!==void 0&&ai(l.responseSchema)===r.responseSchemaHash&&(l.payloadSchema===void 0?r.payloadSchemaHash===void 0:r.payloadSchemaHash===ai(l.payloadSchema))){const c=jh(n);return{descriptor:n,binding:U(r),definition:l,kind:"generic",status:"pending",canResolve:!0,resumable:!0,...c===void 0?{}:{payload:U(c)},validationGeneration:0}}}const u=i||r!==void 0&&r.interruptId===n.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&(r.kind!=="generic"||ht(n)===void 0||r.responseSchemaHash===ht(n));return{descriptor:n,binding:$s(n,t,r),kind:"generic",status:"pending",canResolve:u,resumable:u,validationGeneration:0}}buildSnapshot(e){const t=this.requireHydration(),s=this.items.filter(n=>n.kind!=="client-tool-execution"&&n.status!=="submitting").map(n=>{const r=Vh(n,t);if(n.kind==="unbound"||n.binding===void 0){const a={...r,kind:"unbound",canResolve:!1};return Object.freeze(a)}if(n.kind==="tool-approval"&&n.binding.kind==="tool-approval"){const a=U(n.binding),u={...r,kind:"tool-approval",binding:a,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:U(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(l,c)=>{const h=ae(c)?c:void 0;this.resolveItem(n.descriptor.id,{approved:l,...l&&h?.editedArgs!==void 0?{editedArgs:h.editedArgs}:{},...h?.payload!==void 0?{payload:h.payload}:{}},e)}};return Object.freeze(u)}const i=n.binding.kind==="generic"?U(n.binding):U({v:1,kind:"generic",interruptId:n.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof n.binding.responseSchemaHash=="string"?{responseSchemaHash:n.binding.responseSchemaHash}:{}});if(n.definition!==void 0&&n.binding.kind==="generic"){const a={...r,kind:"generic",definitionId:n.definition.id,key:n.binding.key??"",payload:n.payload,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:u=>this.resolveItem(n.descriptor.id,u,e)};return Object.freeze(a)}const o={...r,kind:"generic",binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:a=>this.resolveItem(n.descriptor.id,a,e)};return Object.freeze(o)});return Object.freeze(s)}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,s){this.assertItemMutable(s);const n=this.findItem(e);if(this.invalidateRetry(),!n.canResolve){n.status="error",n.error=this.itemError(e,"invalid-response-schema","The interrupt response schema is invalid and cannot be resolved."),s||this.publish();return}const r=++n.validationGeneration,i=this.validateCandidate(n,t);if(Pe(i)){n.status="validating",n.error=void 0,s||this.publish(),Promise.resolve(i).then(o=>{r===n.validationGeneration&&this.applyValidation(n,o,s)}).catch(o=>{r===n.validationGeneration&&this.applyValidation(n,{code:this.validationCode(n),message:o instanceof Error?o.message:String(o)},s)});return}this.applyValidation(n,i,s)}cancelItem(e,t){this.assertItemMutable(t);const s=this.findItem(e);this.invalidateRetry(),s.validationGeneration++,s.resolution=Object.freeze(Gs(s,{interruptId:e,status:"cancelled"})),s.status="staged",s.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);const s=this.findItem(e);this.invalidateRetry(),s.validationGeneration++,s.resolution=void 0,s.error=void 0,s.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 s=this.requireHydration(),n=ad(t.map(i=>i.resolution).filter(i=>i!==void 0)),r=Object.freeze({threadId:s.threadId,interruptedRunId:s.interruptedRunId,generation:s.generation,resolutions:n.resolutions,canonicalResolutions:n.canonicalResolutions,fingerprint:n.fingerprint});this.submitBatch(r)}applyValidation(e,t,s){if(!("valid"in t)){e.status="error";const n=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=n,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:n.message,source:"client",retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation})])),s||this.publish();return}e.resolution=U(Gs(e,{interruptId:e.descriptor.id,status:"resolved",payload:t.payload})),e.status="staged",e.error=void 0,s||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind==="generic"){const s=Vt(e.definition?.responseSchema??e.descriptor.responseSchema,t,"invalid-payload");if(e.definition===void 0)return s;const n=r=>"valid"in r?{valid:!0,payload:t}:r;return Pe(s)?Promise.resolve(s).then(n):n(s)}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 s=t.approved,n=t.editedArgs;if(!s&&n!==void 0)return{code:"invalid-edited-args",message:"Rejected tool approvals cannot edit tool arguments."};if(s&&n!==void 0){const r=Vt(e.tool?.inputSchema,n,"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,s){const n=t.approved===!0,r=this.approvalBranchSchema(e.tool,n),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=u=>"valid"in u?{valid:!0,payload:{approved:n,...s!==void 0?{editedArgs:s}:{},...r!==void 0?{payload:u.payload}:{}}}:u;return Pe(o)?Promise.resolve(o).then(a):a(o)}approvalBranchSchema(e,t){const s=e?.approvalSchema;return!ae(s)||!("approve"in s||"reject"in s)?s:t?s.approve:s.reject}validationCode(e){return e.kind==="client-tool-execution"?"invalid-tool-output":"invalid-payload"}resolveBooleanBulk(e){const t=this.items.filter(s=>pe(s)&&s.kind!=="client-tool-execution");if(!t.every(s=>s.kind==="tool-approval"&&this.approvalBranchSchema(s.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 s of t)s.validationGeneration++,s.resolution=U({interruptId:s.descriptor.id,status:"resolved",payload:{approved:e}}),s.status="staged",s.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})),s={active:!0};this.activeTransaction=s;const n=this.buildSnapshot(s).filter(Ph);let r;try{for(const i of n){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{s.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,s)=>{const n=e[s];n&&(t.status=n.status,t.resolution=n.resolution,t.error=n.error,t.validationGeneration=n.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 s of this.items)pe(s)&&(s.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 s=Uh(e);if(s.length===0){const u=e instanceof Error?e.message:String(e);this.addRootError("transport",u,!0,"transport"),this.retrySubmission=t;for(const l of this.items)pe(l)&&(l.status="error");return}const n=s.filter(u=>zh(u,t));n.length!==s.length&&this.addRootError("protocol","Interrupt submission errors did not match the active batch.",!1);let r=!1,i=!1;const o=[];for(const u of n)if((u.code==="stale"||u.code==="expired"||u.code==="conflict")&&(r=!0),i||=u.retryable,u.scope==="item"){const l=this.items.find(c=>pe(c)&&c.descriptor.id===u.interruptId);l&&(l.status="error",l.error=U(u))}else o.push(U(u));const a=Hh(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=a.rootErrors,this.submissionRootErrors=a.submissionRootErrors;for(const u of this.items)pe(u)&&u.status==="submitting"&&(u.status="error");this.retrySubmission=i&&!r?t:void 0}addRootError(e,t,s,n="client"){const r=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:"batch",code:e,message:t,source:n,retryable:s,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(s=>s.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,s,n){const r=this.requireHydration();return Object.freeze({scope:"item",interruptId:e,code:t,message:s,...n!==void 0?{path:Object.freeze([...n])}:{},source:"client",retryable:!1,threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})}};function Kh(e,...t){const s=e?.();if(re(s))return s;for(const n of t)if(re(n))return n}async function Qh(e,t){if(!t)throw new Lo;return await e.prepare(t),e.headers(t)}function Wh(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():Math.random().toString(36).slice(2)}var qt;function ci(){return qt!==void 0||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__=Wh()),qt=globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__),qt}var Jh=0;function ue(e){return e==null||e===""?"missing":`value-${encodeURIComponent(String(e))}`}function Rn(e){const t=e.runtimeId??ci(),s=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,ci(),Jh++].join(":");return{...e,runtimeId:t,eventId:s}}var Xh=class{#t=!0;#e;#s;#n;#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.#s().removeEventListener("tanstack-connect-success",this.#p)};#g=()=>{if(this.#h<this.#o){this.#h++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#s().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.#s().addEventListener("tanstack-connect-success",this.#p),this.#g())};constructor({pluginId:e,debug:t=!1,enabled:s=!0,reconnectEveryMs:n=300}){this.#e=e,this.#t=s,this.#s=this.getGlobalTarget,this.#n=t,this.debugLog(" Initializing event subscription for plugin",this.#e),this.#i=[],this.#r=!1,this.#f=!1,this.#a=null,this.#l=n}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.#n&&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 s=new Event(e,{detail:t});this.#s().dispatchEvent(s)}catch{this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(e,t){try{this.#s().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,s){const n=s?.withEventTarget??!1,r=`${this.#e}:${e}`;if(n&&(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.#s().addEventListener(r,i),this.debugLog("Registered event to bus",r),()=>{n&&this.#d?.removeEventListener(r,i),this.#s().removeEventListener(r,i)}}onAll(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=s=>{const n=s.detail;e(n)};return this.#s().addEventListener("tanstack-devtools-global",t),()=>this.#s().removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=s=>{const n=s.detail;this.#e&&n.pluginId!==this.#e||e(n)};return this.#s().addEventListener("tanstack-devtools-global",t),()=>this.#s().removeEventListener("tanstack-devtools-global",t)}},Yh=class extends Xh{constructor(){super({pluginId:"tanstack-ai-devtools"})}},di=Symbol.for("tanstack.ai.devtools.eventClient");function Zh(){const e=globalThis,t=e[di];if(t)return t;const s=new Yh;return e[di]=s,s}var wt=Zh();function X(e,t){wt.emit(e,t)}var la=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,s,n){this.emitEvent("text:chunk:content",{streamId:e,messageId:t,content:s,...n})}toolCallStateChanged(e,t,s,n,r,i,o){this.emitEvent("tools:call:updated",{streamId:e,messageId:t,toolCallId:s,toolName:n,state:r,arguments:i,...o})}thinkingUpdated(e,t,s,n,r){this.emitEvent("text:chunk:thinking",{streamId:e,messageId:t,content:s,delta:n,...r})}structuredOutputChanged(e,t,s,n,r){this.emitEvent(e,{streamId:t,messageId:s,...n,...r})}approvalRequested(e,t,s,n,r,i,o){this.emitEvent("tools:approval:requested",{streamId:e,messageId:t,toolCallId:s,toolName:n,input:r,approvalId:i,...o})}messageAppended(e,t,s){const n=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:n,parts:e.parts,...s})}messageSent(e,t){const s=typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.content).join("");this.emitEvent("text:message:created",{messageId:e,role:"user",content:s,...Array.isArray(t)&&{parts:t}}),this.emitEvent("text:message:user",{messageId:e,role:"user",content:s,...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,s,n,r){this.emitEvent("tools:result:added",{toolCallId:e,toolName:t,output:s,state:n,...r})}toolApprovalResponded(e,t,s,n){this.emitEvent("tools:approval:responded",{approvalId:e,toolCallId:t,approved:s,...n})}toolFixtureApplied(e){this.emitEvent("devtools:tool-fixture:applied",{...e})}},ef=class extends la{emitEvent(e,t){const s=Date.now(),n=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=n?"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=Rn({eventType:e,clientId:this.clientId,...o,source:"client",visibility:i,timestamp:s});wt.emit(e,{...t,...a})}else{const a=Rn({eventType:e,source:"client",visibility:"client-state",timestamp:s});wt.emit(e,{...t,...a})}}},tf=class extends la{emitEvent(){}},sf=class{events;constructor(e){this.events=new tf(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,s,n){}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){}},nf=e=>new sf(e);function hi(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function fi(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function pi(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function rf(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var of=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,s,n){this.adapter=e,this.id=t,this.applyMessages=s,this.applyResume=n}writeState(){const e=[...this.lastMessages];if(e.length===0&&!this.lastResume){const n=this.generation;this.runOperation(()=>{if(n===this.generation)return this.adapter.removeItem(this.id)});return}const t=this.generation,s={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,s)})}readInitial(){try{const e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(hi).catch(()=>{});const t=hi(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(s=>{!s||this.messagesGeneration!==t||(this.lastResume=s.resume??null,this.lastMessages=s.messages,this.applyMessages(s.messages),s.resume&&this.applyResume&&this.applyResume(s.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 s=t.catch(()=>{});this.queue=s,s.finally(()=>{this.queue===s&&(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=ne(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 s=fi(e);if(s&&this.clearedToolCallIds.has(s))return!0;const n=rf(e);if(n&&this.clearedMessageIds.has(n))return s&&this.clearedToolCallIds.add(s),!0;const r=pi(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=pi(e);t&&this.clearedMessageIds.add(t);const s=fi(e);s&&this.clearedToolCallIds.add(s)}isRunlessChunkFromIgnoredRun(e){return ne(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 gi(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function mi(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function af(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var lf=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=ne(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 s=gi(e);if(s&&this.clearedToolCallIds.has(s))return!0;const n=af(e);if(n&&this.clearedMessageIds.has(n))return s&&this.clearedToolCallIds.add(s),!0;const r=mi(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=mi(e);t&&this.clearedMessageIds.add(t);const s=gi(e);s&&this.clearedToolCallIds.add(s)}isRunlessChunkFromIgnoredRun(e){return ne(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 uf(e){const t=new Set;for(const s of e??[]){if(t.has(s.id))throw new Error(`Duplicate interrupt definition id: ${s.id}`);t.add(s.id)}}function vi(e){const{connection:t,fetcher:s}=e;if(t&&s)throw new Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(s)return Oh(s);throw new Error("ChatClient: either `connection` or `fetcher` is required.")}function Si(e){return"connect"in e}function yi(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 Ii(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 s=e.maxSize;if(s!==void 0&&(!Number.isInteger(s)||s<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",...s!==void 0?{maxSize:s}:{}}}function cf(e){const t=e.at(-1)?.body,s=[];for(const i of e){if(typeof i.content!="string")break;s.push(i.content)}if(s.length===e.length)return{content:s.join(`
11
+ `),...t!==void 0?{body:t}:{}};const n=[];let r;for(const i of e){if(typeof i.content=="string"){n.push({type:"text",content:i.content});continue}typeof i.content.content=="string"?n.push({type:"text",content:i.content.content}):n.push(...i.content.content),r=jo(r,i.content.metadata)}return{content:{content:n,...r!==void 0?{metadata:r}:{}},...t!==void 0?{body:t}:{}}}function df(e){if(!(e===null||typeof e!="object"||Array.isArray(e))&&!(!("approved"in e)||typeof e.approved!="boolean"))return e.approved}function hf(e){const t=e;if(t===null||typeof t!="object"||!("resumeState"in t))return;const s=t.resumeState;if(!(s===null||typeof s!="object"||!("threadId"in s)||typeof s.threadId!="string"||s.threadId.length===0||!("runId"in s)||typeof s.runId!="string"||s.runId.length===0))return{threadId:s.threadId,runId:s.runId}}var ff=2e3,pf=new Set(["TEXT_MESSAGE_START","TEXT_MESSAGE_CONTENT","TOOL_CALL_START","MESSAGES_SNAPSHOT"]),gf=64,mf=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new lf;currentRunId=null;lastResume=null;runParents=new Map;supersededInterruptRunIds=new Set;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;historyPageSize;hasOlderMessages=!1;olderMessagesCursor;knownServerMessageIds=new Set;loadOlderMessagesInFlight=!1;historyGeneration=0;devtoolsMounted=!1;callbacksRef;constructor(e){uf(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,this.historyPageSize=e.history?.pageSize}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 of(e.persistence,e.threadId,a=>this.processor.setMessages(a),a=>this.applyPersistedResume(a)),this.historyPageSize=void 0}else this.historyPageSize=void 0;this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=Ii(e.queue);const s=vi(e);if(this.connectionDrainsOnSend=Si(s),this.connection=ii(s),this.clientToolsRef={current:new Map},e.tools)for(const a of e.tools)this.clientToolsRef.current.set(a.name,a);this.devtoolsBridge=(e.devtoolsBridgeFactory??nf)(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 qh({...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 n=this.persistor?.readInitial(),r=n instanceof Promise?void 0:n,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 dh({...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 u=this.processor.getMessages().find(l=>l.id===a);u&&(this.currentMessageId=u.id,this.events.messageAppended(u,this.currentStreamId||void 0))},onStreamEnd:a=>{this.callbacksRef.current.onFinish(a),this.setStatus("ready"),this.resolveProcessing()},onError:a=>{this.reportStreamError(a)},onTextUpdate:(a,u)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,a,u)},onThinkingUpdate:(a,u)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,a,u,void 0)},onStructuredOutputChange:a=>{const u=this.devtoolsBridge.resolveStreamId(),l=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(l,u,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,u,l,c)=>{const h=this.processor.getMessages().find(d=>d.id===a)?.parts.find(d=>d.type==="tool-call"&&d.id===u)?.name||"unknown";this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,a,u,h,l,c)},onToolCall:a=>{const u=(this.activeClientTools??this.clientToolsRef.current).get(a.toolName),l=u?.execute;if(l){const c=this.continuationGeneration,h=this.devtoolsBridge.getCurrentRunEventContext(),d=(async()=>{try{const f=this.activeClientTools===null?this.context:this.activeContext,p=await l(a.input,{toolCallId:a.toolCallId,context:f,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:a.toolCallId,tool:a.toolName,output:p,state:"output-available"},u,c,h)}catch(f){await this.addToolResultForClientTool({toolCallId:a.toolCallId,tool:a.toolName,output:null,state:"output-error",errorText:f.message},u,c,h)}finally{this.pendingToolExecutions.delete(a.toolCallId)}})();this.pendingToolExecutions.set(a.toolCallId,d)}},onApprovalRequest:a=>{const u=this.devtoolsBridge.resolveStreamId(),l=this.findMessageIdForToolCall(a.toolCallId)??this.currentMessageId??"";this.events.approvalRequested(u,l,a.toolCallId,a.toolName,a.input,a.approvalId)},onCustomEvent:(a,u,l)=>{a==="memory:state"&&this.devtoolsBridge.recordMemoryState(u),(a==="compaction:started"||a==="compaction:state"||a==="compaction:ended")&&this.devtoolsBridge.recordCompactionEvent(a,u),a==="skills:state"&&this.devtoolsBridge.recordSkillsState(u),this.callbacksRef.current.onCustomEvent(a,u,l)}}}),this.persistor?.hydrateAsync(n),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=hf(e);if(t===void 0){this.interruptManager.reset({source:"hydrate"});return}this.lastResume=t;const s=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(s.length===0){this.interruptManager.reset({source:"hydrate"});return}const n=this.interruptGeneration(s);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:n,interrupts:s},"hydrate")}applyPersistedResume(e){this.applyResumeSnapshot(e);const t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,s=e.resumeState?.runId;!t&&s&&this.maybeRejoinInFlight(s)}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;if(!e||this.isLoading||this.abortController||this.disposed)return;const t=this.historyPageSize,s=t===void 0?void 0:{limit:t};(async()=>{let n;const r=this.historyGeneration;try{n=await e(this.threadId,s)}catch{return}if(r===this.historyGeneration&&!(this.disposed||!this.tailing)&&!(this.isLoading||this.abortController)){if(this.applyHydrationPage(n.page),n.messages.length>0){const i=hn(n.messages);this.processor.setMessages(i),this.rememberServerMessageIds(i)}n.interrupts&&n.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:n.interrupts.runId},pendingInterrupts:n.interrupts.pending}):n.activeRun?.runId&&this.maybeRejoinInFlight(n.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=ne(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),ne(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type==="RUN_STARTED"){const r=ne(e)??e.runId,i="parentRunId"in e&&typeof e.parentRunId=="string"?e.parentRunId:void 0;i&&(this.runParents.set(r,i),this.supersededInterruptRunIds.has(r)&&this.markLineageAnswered(i)),this.activeResumeThreadId="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=r;const o=this.supersededInterruptRunIds.has(r)&&!this.isLoading;o||(this.activeRunIds.add(r),this.clearedStreamTracker.onRunStarted(r),this.setSessionGenerating(!0)),this.persistor&&this.connection.joinRun&&!this.lastResume&&!o&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:r}),this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId)&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset());return}if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const s=ne(e);s?(this.activeRunIds.delete(s),this.clearedStreamTracker.onRunSettled(s)):e.type==="RUN_ERROR"&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);const n=e.type==="RUN_FINISHED"&&yi(e);t?.resolveProcessing!==!1&&!n&&this.resolveProcessing()}observeInterruptState(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR"||this.activeInterruptSubmission&&e.type==="RUN_ERROR")return;const t=ne(e),s="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId;if(t&&!yi(e)&&(e.type==="RUN_ERROR"||e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt")&&this.markLineageAnswered(t),e.type==="RUN_FINISHED"&&e.outcome?.type==="interrupt"){const c=this.currentRunId??t??this.activeResumeRunId??"";if(c&&this.supersededInterruptRunIds.has(c))return;this.lastResume={threadId:s??this.threadId,runId:c},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:c,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},"live");return}const n=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,u=!!(this.activeInterruptSubmission&&this.isLoading&&e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt"),l=!!(this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId));if(n||r||i||o||a||u||l){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange("live")}markLineageAnswered(e){let t=e,s=0;for(;t!==void 0&&s<gf;){if(this.supersededInterruptRunIds.has(t))return;this.supersededInterruptRunIds.add(t),t=this.runParents.get(t),s++}}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 s=t??this.lastResume;return s?this.resumeInterruptsUnsafeForGeneration(e,s,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,s){return s!==this.continuationGeneration?Promise.resolve(!1):this.isLoading?new Promise((n,r)=>{this.queuePostStreamAction(async()=>{try{n(await this.resumeInterruptsUnsafeForGeneration(e,t,s))}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=df(r.payload);if(i===void 0)continue;const o=r.interruptId;this.processor.addToolApprovalResponse(o,i)}const s=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 n=this.takeInterruptSubmissionFailure();if(n!==void 0)throw{errors:n.errors};if(!s)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 s of e){const n=s.metadata?.["tanstack:interruptBinding"];if(n===null||typeof n!="object"||!("generation"in n)||typeof n.generation!="number"||!Number.isInteger(n.generation)||n.generation<0||t!==void 0&&t!==n.generation)return 0;t=n.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(),s=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,s.interrupts),this.callbacksRef.current.onInterruptStateChange(s,{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:s=>{this.processor.setMessages(s)},addToolResult:(s,n,r)=>{this.processor.addToolResult(s,n,r)},generateId:s=>this.generateUniqueId(s)}}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 s of t)if(s.parts.find(n=>n.type==="tool-call"&&n.id===e))return s.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 s of t){if(e.aborted)break;await this.processIncomingChunk(s)}}resumeInFlightRun(e){const t=this.connection.joinRun;if(!t)return;const s=new AbortController;this.abortController=s,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus("streaming"),(async()=>{let n=!1,r=!1,i=!1;const o=setTimeout(()=>{r||s.abort()},ff);try{for await(const a of t(e,s.signal)){if(s.signal.aborted)break;r||(r=!0,clearTimeout(o)),!n&&pf.has(a.type)&&(n=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(a){const u=a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError");!r&&!u&&(i=!0),r&&!u&&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===s&&(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=Zo(e),e.type==="RUN_ERROR"&&this.isActiveInterruptSubmissionFailure(e)){const s=B(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(s)?s:[]}}if(this.connectionStatus==="connecting"&&this.setConnectionStatus("connected"),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR")&&(ne(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(s=>setTimeout(s,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){const t=this.activeInterruptSubmission,s=B(e)?.interruptErrors;if(!t||!Array.isArray(s)||s.length===0)return!1;const n=ne(e);return n!==void 0&&n!==this.currentRunId||typeof e.threadId=="string"&&e.threadId!==t.threadId?!1:s.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=ne(e);if(t===void 0)return;const s=this.joinedRunWaiters.get(t);s!==void 0&&(this.joinedRunWaiters.delete(t),s())}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,s){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 n={...t,...s?.body};if(this.isSendBusy()){const{action:r,id:i}=this.decideWhenBusy(e,s);if(r==="drop")return;if(r==="queue"){this.enqueueMessage(e,n,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,n)}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 s=this.normalizeMessageInput(e);this.pendingMessageBody=t;const n=this.processor.addUserMessage(s.content,s.id,s.metadata);return this.events.messageSent(n.id,s.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){const s=this.generateUniqueId("queued");if(t?.whenBusy)return{action:t.whenBusy,id:s};const{strategy:n,whenBusy:r}=this.queueConfig;if(n){const{action:i}=n({pending:{id:s,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:i,id:s}}return{action:r,id:s}}enqueueMessage(e,t,s){const{maxSize:n,onOverflow:r}=this.queueConfig;if(n!==void 0&&this.messageQueue.length>=n){if(r==="reject"||n===0)return;this.messageQueue.shift()}this.messageQueue.push({id:s??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=Bd(e,Ne);if(t.role==="system")return;const s=t;this.events.messageAppended(s);const n=this.processor.getMessages();if(this.processor.setMessages([...n,s]),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,s=this.pendingResumeParentRunId,n=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,u=!1;try{const l=this.messagesForSend(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 v=Kh(this.byokProvider,d.provider,Wc(this.byok));p=await Qh(this.byok,v)}const g={threadId:t??this.threadId,runId:r,...s!==null?{parentRunId:s}:{},clientTools:Array.from(c.values()).map(v=>({name:v.name,description:v.description,parameters:v.inputSchema?pn(v.inputSchema):{type:"object"}})),forwardedProps:{...d},...n?{resume:n}:{},...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(l,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}:{}),u=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),o=!0}catch(l){const c=l instanceof Error?l:new Error(String(l));if(c.name==="AbortError")return a&&(this.devtoolsBridge.emitRunLifecycle("run:cancelled",a,"cancelled"),u=!0),!1;if(c instanceof cn&&this.byok?.request(c.provider,"missing"),c instanceof is&&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}),u=!0)),e===this.streamGeneration&&(c instanceof cn||c instanceof is||c instanceof Lo))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&&!u&&(o?this.devtoolsBridge.emitRunLifecycle("run:completed",a,"completed"):i.aborted&&this.devtoolsBridge.emitRunLifecycle("run:cancelled",a,"cancelled")),await this.drainPostStreamActions(),o?(this.rememberProcessorMessageIds(),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(s=>s.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.resetHistoryPaging(),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,s,n){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",n),s===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(()=>s===this.continuationGeneration?this.checkForContinuation():Promise.resolve());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&Ae(e.outputSchema)?dd(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 s;for(const n of t){const r=n.parts.find(i=>i.type==="tool-call"&&i.approval?.id===e.id);if(r){s=r.id;break}}if(s&&this.events.toolApprovalResponded(e.id,s,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()}getHasOlderMessages(){return this.hasOlderMessages}async loadOlderMessages(){const e=this.connection.hydrate;if(e===void 0||this.disposed||!this.hasOlderMessages)return;const t=this.olderMessagesCursor;if(t===void 0||this.loadOlderMessagesInFlight)return;const s={before:t};this.historyPageSize!==void 0&&(s.limit=this.historyPageSize),this.loadOlderMessagesInFlight=!0;const n=this.historyGeneration;try{const r=await e(this.threadId,s);if(this.disposed||n!==this.historyGeneration)return;const i=hn(r.messages);if(i.length===0)throw new Error("Older page was empty");this.applyHydrationPage(r.page),this.processor.prependMessages(i),this.rememberServerMessageIds(i)}finally{this.loadOlderMessagesInFlight=!1}}resetHistoryPaging(){this.hasOlderMessages=!1,this.olderMessagesCursor=void 0,this.knownServerMessageIds.clear(),this.historyGeneration++}applyHydrationPage(e){if(e?.truncated===!0){this.hasOlderMessages=!0,this.olderMessagesCursor=e.cursor;return}this.hasOlderMessages=!1,this.olderMessagesCursor=void 0}rememberServerMessageIds(e){const t=e.map(s=>s.id);for(const s of t)this.knownServerMessageIds.add(s)}rememberProcessorMessageIds(){this.historyPageSize!==void 0&&this.rememberServerMessageIds(this.processor.getMessages())}messagesForSend(e){if(this.historyPageSize===void 0)return e;const t=[];for(const n of e)this.knownServerMessageIds.has(n.id)||t.push(n);if(t.length>0)return t;const s=e.findLastIndex(n=>n.role==="user");return s===-1?[]:e.slice(s)}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=cf(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:s})=>({id:e,content:t,createdAt:s}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){const t=this.messageQueue.findIndex(s=>s.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 s=vi({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=Si(s),this.connection=ii(s),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=Ii(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 Ri(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 Ci(e){if(!Array.isArray(e))return;const t=[];for(const s of e)!s||typeof s!="object"||!("role"in s)||!("tokens"in s)||!("text"in s)||typeof s.role!="string"||typeof s.tokens!="number"||typeof s.text!="string"||t.push({role:s.role,tokens:s.tokens,text:s.text});return t}function vf(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,s="maxTokens"in e&&typeof e.maxTokens=="number"?e.maxTokens:void 0,n="strategyKey"in e&&typeof e.strategyKey=="string"?e.strategyKey:void 0,r="dropped"in e?Ci(e.dropped):void 0,i="result"in e?Ci(e.result):void 0;return{before:e.before,after:e.after,messagesBefore:e.messagesBefore,messagesAfter:e.messagesAfter,reusedCheckpoint:t,...s!==void 0?{maxTokens:s}:{},...n?{strategyKey:n}:{},...r?{dropped:r}:{},...i?{result:i}:{}}}var bi=Symbol.for("tanstack.ai.devtools.activeBridgeByHookId");function Bs(){const e=globalThis,t=e[bi];if(t)return t;const s=new Map;return e[bi]=s,s}function Sf(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 yf=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?pn(t.inputSchema):{type:"object"},outputSchema:t.outputSchema?pn(t.outputSchema):void 0,needsApproval:t.needsApproval,metadata:t.metadata})):[];X("tools:registered",{...this.createEnvelope("tools:registered"),...this.createMetadataPayload(),tools:e})}emitRunLifecycle(e,t,s,n={}){this.prepareForEmit()&&X(e,{...this.createEnvelope(e,"client-state",{runId:t}),runId:t,status:s,...n.error?{error:n.error}:{}})}deactivate(){const e=Bs();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(Bs().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=Bs(),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",s=>{this.handleRequestState(s)})),this.options.applyToolFixture&&this.unsubscribers.push(wt.on("devtools:tool-fixture:apply",s=>{this.handleToolFixtureApply(s)})))}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",s={}){return Rn({eventType:e,source:"client",visibility:t,clientId:this.options.clientId,hookId:this.options.hookId,...this.options.threadId?{threadId:this.options.threadId}:{},...s.runId?{runId:s.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}:{}}}},If=class extends yf{events;chatOptions;currentRunId=null;currentRunThreadId=null;currentStreamId=null;lastStreamId=null;lastRunEventContext;lastMemoryStateValue=null;lastCompactionEvents=[];lastSkillsStateValue=null;constructor(e){super(Sf(e,{getSnapshot:e.getSnapshot,applyToolFixture:t=>this.applyFixture(t)})),this.chatOptions=e,this.events=new _f(()=>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 s=this.getCurrentRunEventContext();s&&(this.lastRunEventContext=s),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,s=t.scope,n=t.adapter;if(!s||typeof n!="string")return;const r=this.currentRunId?{runId:this.currentRunId}:{};X("memory:retrieve:started",{...this.createEnvelope("memory:retrieve:started","client-state",r),scope:s,adapter:n,query:t.query??""}),t.recall&&X("memory:retrieve:completed",{...this.createEnvelope("memory:retrieve:completed","client-state",r),scope:s,adapter:n,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:s,adapter:n,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 s=this.currentRunId?{runId:this.currentRunId}:{};if(e==="compaction:started"){const n=Ri(t);X("compaction:started",{...this.createEnvelope("compaction:started","client-state",s),...n});return}if(e==="compaction:ended"){const n=Ri(t);X("compaction:ended",{...this.createEnvelope("compaction:ended","client-state",s),...n});return}if(e==="compaction:state"){const n=vf(t);if(!n)return;X("compaction:state",{...this.createEnvelope("compaction:state","client-state",s),...n})}}emitSkillsState(e){if(!e||typeof e!="object")return;const t=e,s=Array.isArray(t.catalog)?t.catalog:[],n=Array.isArray(t.activated)?t.activated:[],r=this.currentRunId?{runId:this.currentRunId}:{};X("skills:snapshot",{...this.createEnvelope("skills:snapshot","client-state",r),catalog:s,activated:n})}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},s=this.getCurrentRunEventContext();return s?{threadId:s.threadId,runId:s.runId,toolCallId:e}:this.chatOptions.threadId?{threadId:this.chatOptions.threadId,toolCallId:e}:t}async applyFixture(e){const t=this.chatOptions.getMessages(),s=e.threadId??this.chatOptions.threadId??"";if(e.execute){await this.executeFixture(e,t,s);return}const{message:n,toolCallId:r}=this.createReplayMessageFromFixture(e,t),i=n.id;this.events.messageAppended(n,void 0,{threadId:s,toolCallId:r,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,n]),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:s,...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,s){const n=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i={id:r,role:"assistant",parts:[{type:"tool-call",id:n,name:e.toolName,arguments:Us(e.input),input:e.input,state:"input-complete"}],createdAt:new Date};this.events.messageAppended(i,void 0,{threadId:s,toolCallId:n,...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:n,threadId:s,output:e.output,errorText:e.errorText});return}let a;try{a=await o(e.input)}catch(u){console.error(`[ai-devtools] tool fixture "${e.toolName}" execute threw`,u),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:null,errorText:u instanceof Error?`${u.name}: ${u.message}`:`Tool execution failed: ${String(u)}`});return}this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,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 s=this.cloneFixtureSourceMessage(e,t);if(s)return s;const n=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i=e.errorText?"error":"complete";return{toolCallId:n,message:{id:r,role:"assistant",parts:[{type:"tool-call",id:n,name:e.toolName,arguments:Us(e.input),input:e.input,state:"input-complete",output:e.output},{type:"tool-result",toolCallId:n,content:Us(e.output),state:i,...e.errorText?{error:e.errorText}:{}}],createdAt:new Date}}}cloneFixtureSourceMessage(e,t){const s=e.message;if(!s||!Array.isArray(s.parts))return;const n=this.createFixtureToolCallIdMap(s.parts,t),r=s.parts.map(a=>Cf(a,n)).filter(a=>!!a),i=e.toolCallId?n.get(e.toolCallId):void 0;if(wf(r,{...i?{mappedToolCallId:i}:{},output:e.output}),r.length===0)return;const o=(e.toolCallId?n.get(e.toolCallId):void 0)??bf(r);if(o)return{toolCallId:o,message:{id:this.resolveFixtureMessageId(s.id,t),role:s.role,parts:r,createdAt:new Date}}}createFixtureToolCallIdMap(e,t){const s=new Map;for(const n of e)!ua(n)||n.type!=="tool-call"||typeof n.id=="string"&&s.set(n.id,this.resolveFixtureToolCallId(n.id,t));return s}resolveFixtureMessageId(e,t){return e&&!t.some(s=>s.id===e)?e:this.chatOptions.generateId("fixture-msg")}resolveFixtureToolCallId(e,t){return e&&!Ef(t,e)?e:this.chatOptions.generateId("fixture-tool-call")}findClientTool(e){const t=this.chatOptions.getTools?.();if(t){for(const s of t)if(s.name===e)return s}}};function ua(e){return typeof e=="object"&&e!==null}function Us(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 Rf(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 Cf(e,t){if(!ua(e)||typeof e.type!="string")return;const s={...e};return e.type==="tool-call"&&typeof e.id=="string"&&(s.id=t.get(e.id)??e.id),e.type==="tool-result"&&typeof e.toolCallId=="string"&&(s.toolCallId=t.get(e.toolCallId)??e.toolCallId),s}function bf(e){const t=e.find(s=>s.type==="tool-call");return t?.type==="tool-call"?t.id:void 0}function wf(e,t){for(const s of e){if(s.type!=="tool-result")continue;const n=e.find(r=>r.type==="tool-call"&&r.id===s.toolCallId&&r.output===void 0);n&&(n.output=Array.isArray(s.content)?s.content:Rf(s.content))}if(t.mappedToolCallId&&t.output!==void 0){const s=e.find(n=>n.type==="tool-call"&&n.id===t.mappedToolCallId&&n.output===void 0);s&&(s.output=t.output)}}function Ef(e,t){return e.some(s=>s.parts.some(n=>n.type==="tool-call"?n.id===t:n.type==="tool-result"?n.toolCallId===t:!1))}var _f=class extends ef{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,s,n){super.textUpdated(e,t,s,n??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}thinkingUpdated(e,t,s,n,r){super.thinkingUpdated(e,t,s,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}messageAppended(e,t,s){super.messageAppended(e,t,s??this.helper.getCurrentRunEventContext()),this.afterEmit(t)}toolCallStateChanged(e,t,s,n,r,i,o){super.toolCallStateChanged(e,t,s,n,r,i,o??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}structuredOutputChanged(e,t,s,n,r){super.structuredOutputChanged(e,t,s,n,r??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(t)}approvalRequested(e,t,s,n,r,i,o){super.approvalRequested(e,t,s,n,r,i,o??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(e)}toolResultAdded(e,t,s,n,r){super.toolResultAdded(e,t,s,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit()}toolApprovalResponded(e,t,s,n){super.toolApprovalResponded(e,t,s,n??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 Tf(e){return new If(e)}var wi=Object.freeze([]),Mf=Object.freeze([]);function ep(e){const t=(0,I.useId)(),s=e.threadId??t,[n,r]=(0,I.useState)(e.initialMessages||[]),[i,o]=(0,I.useState)(!1),[a,u]=(0,I.useState)(void 0),[l,c]=(0,I.useState)("ready"),[h,d]=(0,I.useState)(!1),[f,p]=(0,I.useState)("disconnected"),[g,v]=(0,I.useState)(!1),[m,S]=(0,I.useState)([]),[C,b]=(0,I.useState)(null),[w,R]=(0,I.useState)(()=>({interrupts:wi,pendingInterrupts:wi,interruptErrors:Mf,resuming:!1})),y=(0,I.useRef)(e.initialMessages||[]),_=(0,I.useRef)(!0),O=(0,I.useRef)(!1),T=(0,I.useRef)(null),A=(0,I.useRef)(null),M=(0,I.useRef)(null);y.current=n;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},At=()=>{const D=qe.current;if(!(!D||T.current!==D))return D},ys={ready:!1,callbacks:[]},V=D=>{if(!ys.ready){ys.callbacks.push(D);return}const se=qe.current;!se||T.current!==se||D()},Qn=new mf({devtoolsBridgeFactory:Tf,...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(At())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,se,Is)=>{V(()=>{x.current.onCustomEvent?.(D,se,Is)})},...e.streamProcessor!==void 0&&{streamProcessor:e.streamProcessor},onMessagesChange:D=>{V(()=>{r(D)})},onLoadingChange:D=>{V(()=>{const se=At();se&&(o(D),P(se))})},onErrorChange:D=>{V(()=>{u(D)})},onStatusChange:D=>{V(()=>{c(D)})},onSubscriptionChange:D=>{V(()=>{d(D)})},onConnectionStatusChange:D=>{V(()=>{p(D)})},onSessionGeneratingChange:D=>{V(()=>{v(D)})},...x.current.queue!==void 0&&{queue:x.current.queue},onQueueChange:D=>{V(()=>{S(D)})},onRunIdChange:D=>{V(()=>{b(D)})},onResumeStateChange:(D,se)=>{V(()=>{R(Is=>({...Is,interrupts:se,pendingInterrupts:se}))})},onInterruptStateChange:(D,se)=>{V(()=>{R(D),x.current.onInterruptStateChange?.(D,se)})}});return qe.current=Qn,{client:Qn,initialization:ys}},[s,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)(()=>(M.current?.client===E&&(clearTimeout(M.current.timeout),M.current=null),A.current&&(clearTimeout(A.current),A.current=null),E.mountDevtools(),P(E),()=>{A.current=setTimeout(()=>{T.current===E&&(T.current=null),A.current=null},0);const j={client:E,timeout:setTimeout(()=>{x.current.live?E.unsubscribe():E.stop(),E.dispose(),M.current===j&&(M.current=null)},0)};M.current=j}),[E,P]);const nt=(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]),vs=(0,I.useCallback)(async j=>{await E.addToolResult(j)},[E]),Ss=(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]),Mt=(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(At=>At.type==="structured-output");if(qe)return qe}return null},[ze]),ca=(0,I.useMemo)(()=>Ie?Ie.partial??Ie.data??{}:{},[Ie]),da=(0,I.useMemo)(()=>!Ie||Ie.status!=="complete"?null:Ie.data,[Ie]);return{messages:ze,sendMessage:nt,append:_t,reload:fe,stop:it,isLoading:i,error:a,status:l,isSubscribed:h,connectionStatus:f,sessionGenerating:g,setMessages:ee,clear:He,addToolResult:vs,addToolApprovalResponse:Ss,queue:m,cancelQueued:rt,runId:C,interrupts:w.interrupts,pendingInterrupts:w.pendingInterrupts,interruptErrors:w.interruptErrors,resuming:w.resuming,resolveInterrupts:$,cancelInterrupts:te,retryInterrupts:Mt,resumeInterruptsUnsafe:ot,resumeInterrupts:Tt,partial:ca,final:da}}function tp(e){return(0,I.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>Qc)}var sp=new Uint8Array(128).fill(128);export{jf as C,Di as D,Ff as E,kf as O,mo as S,Nf as T,Bf as _,zc as a,Gf as b,Jf as c,qf as d,Vf as f,Uf as g,Lu as h,Yf as i,Pf as k,Kf as l,Hf as m,ep as n,Xf as o,zf as p,Zf as r,Wf as s,tp as t,Qf as u,$f as v,Df as w,Gn as x,Io as y};