db-studio 1.11.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +29 -27
- package/dist/index.js.map +1 -1
- package/dist/web-dist/assets/_pathlessLayout-C6coCMpi.js +1 -0
- package/dist/web-dist/assets/{_pathlessLayout-ciCuJ1PR.js.map → _pathlessLayout-C6coCMpi.js.map} +1 -1
- package/dist/web-dist/assets/_pathlessLayout-DoBLI2ja.js +132 -0
- package/dist/web-dist/assets/_pathlessLayout-DoBLI2ja.js.map +1 -0
- package/dist/web-dist/assets/_queryId-Chj34V6b.js +1 -0
- package/dist/web-dist/assets/{_queryId-6swfGplM.js.map → _queryId-Chj34V6b.js.map} +1 -1
- package/dist/web-dist/assets/{_table-DHk3bHnN.js → _table-Bg4NvAi4.js} +1 -1
- package/dist/web-dist/assets/{_table-DHk3bHnN.js.map → _table-Bg4NvAi4.js.map} +1 -1
- package/dist/web-dist/assets/_table-CHFe8v3q.js +1 -0
- package/dist/web-dist/assets/{_table-dUsH_2LP.js.map → _table-CHFe8v3q.js.map} +1 -1
- package/dist/web-dist/assets/ai-assistant-D2oc4TtC.js +1 -0
- package/dist/web-dist/assets/ai-assistant-D2oc4TtC.js.map +1 -0
- package/dist/web-dist/assets/browser-B3ZulIJb.js +1 -0
- package/dist/web-dist/assets/{browser-CKmBpcoz.js.map → browser-B3ZulIJb.js.map} +1 -1
- package/dist/web-dist/assets/code-editor-q3FlZk-L.js +9 -0
- package/dist/web-dist/assets/code-editor-q3FlZk-L.js.map +1 -0
- package/dist/web-dist/assets/{database.store-BvoUSH8Y.js → database.store-O79u8Fhj.js} +1 -1
- package/dist/web-dist/assets/{database.store-BvoUSH8Y.js.map → database.store-O79u8Fhj.js.map} +1 -1
- package/dist/web-dist/assets/{dist-C-7rnx4R.js → dist-DBHqGKiG.js} +1 -1
- package/dist/web-dist/assets/{dist-C-7rnx4R.js.map → dist-DBHqGKiG.js.map} +1 -1
- package/dist/web-dist/assets/highlighted-body-OFNGDK62-CFFJC4SW.js +1 -0
- package/dist/web-dist/assets/{highlighted-body-OFNGDK62-qZDgwznf.js.map → highlighted-body-OFNGDK62-CFFJC4SW.js.map} +1 -1
- package/dist/web-dist/assets/{icons-0UA1AvNu.js → icons-CtpwLWUI.js} +1 -1
- package/dist/web-dist/assets/icons-CtpwLWUI.js.map +1 -0
- package/dist/web-dist/assets/index-Cyl_0l9I.css +2 -0
- package/dist/web-dist/assets/index-XoXxezo4.js +35 -0
- package/dist/web-dist/assets/index-XoXxezo4.js.map +1 -0
- package/dist/web-dist/assets/{indexes-D-oUHra7.js → indexes-C9QqJKhp.js} +1 -1
- package/dist/web-dist/assets/{indexes-D-oUHra7.js.map → indexes-C9QqJKhp.js.map} +1 -1
- package/dist/web-dist/assets/{logs-wkipM6zd.js → logs-B8ah8F7D.js} +1 -1
- package/dist/web-dist/assets/{logs-wkipM6zd.js.map → logs-B8ah8F7D.js.map} +1 -1
- package/dist/web-dist/assets/mermaid-GHXKKRXX-TpVEoP0K.js +1 -0
- package/dist/web-dist/assets/popover-wbdw6Hmx.js +1 -0
- package/dist/web-dist/assets/popover-wbdw6Hmx.js.map +1 -0
- package/dist/web-dist/assets/queries.store-CoJVGJKk.js +1 -0
- package/dist/web-dist/assets/queries.store-CoJVGJKk.js.map +1 -0
- package/dist/web-dist/assets/query-runner-Bgs0j50a.js +17 -0
- package/dist/web-dist/assets/query-runner-Bgs0j50a.js.map +1 -0
- package/dist/web-dist/assets/radix-ui-CgJOuzDv.js +51 -0
- package/dist/web-dist/assets/radix-ui-CgJOuzDv.js.map +1 -0
- package/dist/web-dist/assets/react-Cxb6eTZp.js +1 -0
- package/dist/web-dist/assets/{react-B_x-GW6a.js.map → react-Cxb6eTZp.js.map} +1 -1
- package/dist/web-dist/assets/{react-dom-CsRkF-uK.js → react-dom-yg5bT29P.js} +1 -1
- package/dist/web-dist/assets/{react-dom-CsRkF-uK.js.map → react-dom-yg5bT29P.js.map} +1 -1
- package/dist/web-dist/assets/redis-value-COa6YzFD.js +1 -0
- package/dist/web-dist/assets/{redis-value-Dq29EMpv.js.map → redis-value-COa6YzFD.js.map} +1 -1
- package/dist/web-dist/assets/runner-DW5iXMmq.js +1 -0
- package/dist/web-dist/assets/{runner-CL63BPMX.js.map → runner-DW5iXMmq.js.map} +1 -1
- package/dist/web-dist/assets/schema-CtOicTEt.js +64 -0
- package/dist/web-dist/assets/schema-CtOicTEt.js.map +1 -0
- package/dist/web-dist/assets/{schema-CIr5j9z3.js → schema-oy5o_4bt.js} +1 -1
- package/dist/web-dist/assets/{schema-CIr5j9z3.js.map → schema-oy5o_4bt.js.map} +1 -1
- package/dist/web-dist/assets/{table-BoQghHv7.js → table-CN9ZTCOi.js} +1 -1
- package/dist/web-dist/assets/{table-BoQghHv7.js.map → table-CN9ZTCOi.js.map} +1 -1
- package/dist/web-dist/assets/{tanstack-C-qfmRNM.js → tanstack-g1w0v_rJ.js} +6 -6
- package/dist/web-dist/assets/tanstack-g1w0v_rJ.js.map +1 -0
- package/dist/web-dist/assets/tooltip-B7gM8xl3.js +9 -0
- package/dist/web-dist/assets/tooltip-B7gM8xl3.js.map +1 -0
- package/dist/web-dist/assets/{visualizer-qFaRAy7F.js → visualizer-DcEwqmuY.js} +1 -1
- package/dist/web-dist/assets/{visualizer-qFaRAy7F.js.map → visualizer-DcEwqmuY.js.map} +1 -1
- package/dist/web-dist/index.html +12 -12
- package/package.json +1 -1
- package/dist/web-dist/assets/_pathlessLayout-CJRtdlfu.js +0 -132
- package/dist/web-dist/assets/_pathlessLayout-CJRtdlfu.js.map +0 -1
- package/dist/web-dist/assets/_pathlessLayout-ciCuJ1PR.js +0 -1
- package/dist/web-dist/assets/_queryId-6swfGplM.js +0 -1
- package/dist/web-dist/assets/_table-dUsH_2LP.js +0 -1
- package/dist/web-dist/assets/browser-CKmBpcoz.js +0 -1
- package/dist/web-dist/assets/code-editor-C9H5SO98.js +0 -9
- package/dist/web-dist/assets/code-editor-C9H5SO98.js.map +0 -1
- package/dist/web-dist/assets/highlighted-body-OFNGDK62-qZDgwznf.js +0 -1
- package/dist/web-dist/assets/icons-0UA1AvNu.js.map +0 -1
- package/dist/web-dist/assets/index-BSNZ1oRs.js +0 -35
- package/dist/web-dist/assets/index-BSNZ1oRs.js.map +0 -1
- package/dist/web-dist/assets/index-BWKgNfEb.css +0 -2
- package/dist/web-dist/assets/mermaid-GHXKKRXX-BZ1Tdv8E.js +0 -1
- package/dist/web-dist/assets/popover-WwEzK7ho.js +0 -1
- package/dist/web-dist/assets/popover-WwEzK7ho.js.map +0 -1
- package/dist/web-dist/assets/query-runner-B-lngX3P.js +0 -9
- package/dist/web-dist/assets/query-runner-B-lngX3P.js.map +0 -1
- package/dist/web-dist/assets/radix-ui-6dcJ5m4U.js +0 -51
- package/dist/web-dist/assets/radix-ui-6dcJ5m4U.js.map +0 -1
- package/dist/web-dist/assets/react-B_x-GW6a.js +0 -1
- package/dist/web-dist/assets/redis-value-Dq29EMpv.js +0 -1
- package/dist/web-dist/assets/runner-CL63BPMX.js +0 -1
- package/dist/web-dist/assets/schema-BNzZaUjg.js +0 -64
- package/dist/web-dist/assets/schema-BNzZaUjg.js.map +0 -1
- package/dist/web-dist/assets/tanstack-C-qfmRNM.js.map +0 -1
- package/dist/web-dist/assets/toggle-group-CxRlYNqR.js +0 -1
- package/dist/web-dist/assets/toggle-group-CxRlYNqR.js.map +0 -1
- package/dist/web-dist/assets/tooltip-1-bWFncb.js +0 -9
- package/dist/web-dist/assets/tooltip-1-bWFncb.js.map +0 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{r as Ti,t as Xe}from"./rolldown-runtime-CXHxssQy.js";import{lt as Ss}from"./icons-0UA1AvNu.js";import{Ot as aa,kt as la}from"./radix-ui-6dcJ5m4U.js";var Ye=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(){}},ua=class extends Ye{#t;#e;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},ys=new ua,ca={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},da=class{#t=ca;#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)}},Le=new da;function ha(e){setTimeout(e,0)}var fa=typeof window>"u"||"Deno"in globalThis;function q(){}function pa(e,t){return typeof e=="function"?e(t):e}function Un(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 X(e,t){return typeof e=="function"?e(t):e}function Js(e,t){const{type:n="all",exact:s,fetchStatus:r,predicate:i,queryKey:o,stale:a}=e;if(o){if(s){if(t.queryHash!==Is(o,t.options))return!1}else if(!ft(t.queryKey,o))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||r&&r!==t.state.fetchStatus||i&&!i(t))}function Xs(e,t){const{exact:n,status:s,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(De(t.options.mutationKey)!==De(i))return!1}else if(!ft(t.options.mutationKey,i))return!1}return!(s&&t.state.status!==s||r&&!r(t))}function Is(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>$n(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function ft(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ft(e[n],t[n])):!1}var ga=Object.prototype.hasOwnProperty;function Ai(e,t,n=0){if(e===t)return e;if(n>500)return t;const s=Ys(e)&&Ys(t);if(!s&&!($n(e)&&$n(t)))return t;const r=(s?e:Object.keys(e)).length,i=s?t:Object.keys(t),o=i.length,a=s?new Array(o):{};let u=0;for(let l=0;l<o;l++){const c=s?l:i[l],h=e[c],d=t[c];if(h===d){a[c]=h,(s?l<r:ga.call(e,c))&&u++;continue}if(h===null||d===null||typeof h!="object"||typeof d!="object"){a[c]=d;continue}const f=Ai(h,d,n+1);a[c]=f,f===h&&u++}return r===o&&u===r?e:a}function Vt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Ys(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function $n(e){if(!Zs(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Zs(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Zs(e){return Object.prototype.toString.call(e)==="[object Object]"}function ma(e){return new Promise(t=>{Le.setTimeout(t,e)})}function Bn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Ai(e,t):t}function va(e,t,n=0){const s=[...e,t];return n&&s.length>n?s.slice(1):s}function Sa(e,t,n=0){const s=[t,...e];return n&&s.length>n?s.slice(0,-1):s}var Rs=Symbol();function Mi(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Rs?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Cs(e,t){return typeof e=="function"?e(...t):!!e}function ya(e,t,n){let s=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),s||(s=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),e}var pt=(()=>{let e=()=>fa;return{isServer(){return e()},setIsServer(t){e=t}}})();function Hn(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),e(r)},n.reject=r=>{s({status:"rejected",reason:r}),t(r)},n}function Cf(e){return e.state.status==="success"}var Ia=ha;function Ra(){let e=[],t=0,n=a=>{a()},s=a=>{a()},r=Ia;const i=a=>{t?e.push(a):r(()=>{n(a)})},o=()=>{const a=e;e=[],a.length&&r(()=>{s(()=>{a.forEach(u=>{n(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=>{n=a},setBatchNotifyFunction:a=>{s=a},setScheduler:a=>{r=a}}}var H=Ra(),Ca=class extends Ye{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#t}},qt=new Ca;function ba(e){return Math.min(1e3*2**e,3e4)}function xi(e){return(e??"online")==="online"?qt.isOnline():!0}var zn=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Oi(e){let t=!1,n=0,s;const r=Hn(),i=()=>r.status!=="pending",o=g=>{if(!i()){const m=new zn(g);d(m),e.onCancel?.(m)}},a=()=>{t=!0},u=()=>{t=!1},l=()=>ys.isFocused()&&(e.networkMode==="always"||qt.isOnline())&&e.canRun(),c=()=>xi(e.networkMode)&&e.canRun(),h=g=>{i()||(s?.(),r.resolve(g))},d=g=>{i()||(s?.(),r.reject(g))},f=()=>new Promise(g=>{s=m=>{(i()||l())&&g(m)},e.onPause?.()}).then(()=>{s=void 0,i()||e.onContinue?.()}),p=()=>{if(i())return;let g;const m=n===0?e.initialPromise:void 0;try{g=m??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(h).catch(v=>{if(i())return;const S=e.retry??(pt.isServer()?0:3),C=e.retryDelay??ba,w=typeof C=="function"?C(n,v):C,b=S===!0||typeof S=="number"&&n<S||typeof S=="function"&&S(n,v);if(t||!b){d(v);return}n++,e.onFail?.(n,v),ma(w).then(()=>l()?void 0:f()).then(()=>{t?d(v):p()})})};return{promise:r,status:()=>r.status,cancel:o,continue:()=>(s?.(),r),cancelRetry:a,continueRetry:u,canStart:c,start:()=>(c()?p():f().then(p),r)}}var Pi=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Un(this.gcTime)&&(this.#t=Le.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(pt.isServer()?1/0:3e5))}clearGcTimeout(){this.#t!==void 0&&(Le.clearTimeout(this.#t),this.#t=void 0)}};function wa(e){return{onFetch:(t,n)=>{const s=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},u=0;const l=async()=>{let c=!1;const h=p=>{ya(p,()=>t.signal,()=>c=!0)},d=Mi(t.options,t.fetchOptions),f=async(p,g,m)=>{if(c)return Promise.reject(t.signal.reason);if(g==null&&p.pages.length)return Promise.resolve(p);const S=(()=>{const R={client:t.client,queryKey:t.queryKey,pageParam:g,direction:m?"backward":"forward",meta:t.options.meta};return h(R),R})(),C=await d(S),{maxPages:w}=t.options,b=m?Sa:va;return{pages:b(p.pages,C,w),pageParams:b(p.pageParams,g,w)}};if(r&&i.length){const p=r==="backward",g=p?Li:Vn,m={pages:i,pageParams:o};a=await f(m,g(s,m),p)}else{const p=e??i.length;do{const g=u===0?o[0]??s.initialPageParam:Vn(s,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},n):t.fetchFn=l}}}function Vn(e,{pages:t,pageParams:n}){const s=t.length-1;return t.length>0?e.getNextPageParam(t[s],t,n[s],n):void 0}function Li(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Ea(e,t){return t?Vn(e,t)!=null:!1}function Ta(e,t){return!t||!e.getPreviousPageParam?!1:Li(e,t)!=null}var _a=class extends Pi{#t;#e;#n;#s;#i;#r;#o;#a;constructor(e){super(),this.#a=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#s=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=tr(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.#o,...e},e?._type&&(this.#t=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=tr(this.options);t.data!==void 0&&(this.setState(er(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Bn(this.state.data,e,this.options);return this.#l({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({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=>X(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Rs||!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.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#a||this.#f()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#f(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#l({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 n=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(this.#a=!0,n.signal)})},r=()=>{const a=Mi(this.options,t),l=(()=>{const c={client:this.#i,queryKey:this.queryKey,meta:this.meta};return s(c),c})();return this.#a=!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 s(a),a})();(this.#t==="infinite"?wa(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#l({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=Oi({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:a=>{a instanceof zn&&a.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(a,u)=>{this.#l({type:"failed",failureCount:a,error:u})},onPause:()=>{this.#l({type:"pause"})},onContinue:()=>{this.#l({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0});try{const a=await this.#r.start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),this.#s.config.onSuccess?.(a,this),this.#s.config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof zn){if(a.silent)return this.#r.promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw this.#l({type:"error",error:a}),this.#s.config.onError?.(a,this),this.#s.config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}#l(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Fi(n.data,this.options),fetchMeta:e.meta??null};case"success":const s={...n,...er(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?s:void 0,s;case"error":const r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),H.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function Fi(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:xi(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function er(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function tr(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,s=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var ki=class extends Ye{constructor(e,t){super(),this.options=t,this.#t=e,this.#a=null,this.#o=Hn(),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#s=void 0;#i;#r;#o;#a;#f;#l;#c;#d;#u;#h;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),nr(this.#e,this.options)?this.#g():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return qn(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return qn(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#I(),this.#R(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(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&&!Vt(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const s=this.hasListeners();s&&sr(this.#e,n,this.options,t)&&this.#g(),this.updateResult(),s&&(this.#e!==n||X(this.options.enabled,this.#e)!==X(t.enabled,this.#e)||be(this.options.staleTime,this.#e)!==be(t.staleTime,this.#e))&&this.#m();const r=this.#v();s&&(this.#e!==n||X(this.options.enabled,this.#e)!==X(t.enabled,this.#e)||r!==this.#h)&&this.#S(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return Ma(this,n)&&(this.#s=n,this.#r=this.options,this.#i=this.#e.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,s)=>(this.trackProp(s),t?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,s))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#g({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#g(e){this.#C();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(q)),t}#m(){this.#I();const e=be(this.options.staleTime,this.#e);if(pt.isServer()||this.#s.isStale||!Un(e))return;const t=_i(this.#s.dataUpdatedAt,e)+1;this.#d=Le.setTimeout(()=>{this.#s.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#S(e){this.#R(),this.#h=e,!(pt.isServer()||X(this.options.enabled,this.#e)===!1||!Un(this.#h)||this.#h===0)&&(this.#u=Le.setInterval(()=>{(this.options.refetchIntervalInBackground||ys.isFocused())&&this.#g()},this.#h))}#y(){this.#m(),this.#S(this.#v())}#I(){this.#d!==void 0&&(Le.clearTimeout(this.#d),this.#d=void 0)}#R(){this.#u!==void 0&&(Le.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#e,s=this.options,r=this.#s,i=this.#i,o=this.#r,a=e!==n?e.state:this.#n,{state:u}=e;let l={...u},c=!1,h;if(t._optimisticResults){const R=this.hasListeners(),y=!R&&nr(e,t),T=R&&sr(e,n,t,s);(y||T)&&(l={...l,...Fi(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.#c?.state.data,this.#c):t.placeholderData,R!==void 0&&(p="success",h=Bn(r?.data,R,t),c=!0)}if(t.select&&h!==void 0&&!g)if(r&&h===i?.data&&t.select===this.#f)h=this.#l;else try{this.#f=t.select,h=t.select(h),h=Bn(r?.data,h,t),this.#l=h,this.#a=null}catch(R){this.#a=R}this.#a&&(d=this.#a,h=this.#l,f=Date.now(),p="error");const m=l.fetchStatus==="fetching",v=p==="pending",S=p==="error",C=v&&m,w=h!==void 0,b={status:p,fetchStatus:l.fetchStatus,isPending:v,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:m,isRefetching:m&&!v,isLoadingError:S&&!w,isPaused:l.fetchStatus==="paused",isPlaceholderData:c,isRefetchError:S&&w,isStale:bs(e,t),refetch:this.refetch,promise:this.#o,isEnabled:X(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const R=b.data!==void 0,y=b.status==="error"&&!R,T=x=>{y?x.reject(b.error):R&&x.resolve(b.data)},_=()=>{const x=this.#o=b.promise=Hn();T(x)},E=this.#o;switch(E.status){case"pending":e.queryHash===n.queryHash&&T(E);break;case"fulfilled":(y||b.data!==E.value)&&_();break;case"rejected":(!y||b.error!==E.reason)&&_()}}return b}updateResult(){const e=this.#s,t=this.createResult(this.#e,this.options);if(this.#i=this.#e.state,this.#r=this.options,this.#i.data!==void 0&&(this.#c=this.#e),Vt(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,r=typeof s=="function"?s():s;if(r==="all"||!r&&!this.#p.size)return!0;const i=new Set(r??this.#p);return this.options.throwOnError&&i.add("error"),Object.keys(this.#s).some(o=>{const a=o;return this.#s[a]!==e[a]&&i.has(a)})};this.#b({listeners:n()})}#C(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#b(e){H.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Aa(e,t){return X(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&X(t.retryOnMount,e)===!1)}function nr(e,t){return Aa(e,t)||e.state.data!==void 0&&qn(e,t,t.refetchOnMount)}function qn(e,t,n){if(X(t.enabled,e)!==!1&&be(t.staleTime,e)!=="static"){const s=typeof n=="function"?n(e):n;return s==="always"||s!==!1&&bs(e,t)}return!1}function sr(e,t,n,s){return(e!==t||X(s.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&bs(e,n)}function bs(e,t){return X(t.enabled,e)!==!1&&e.isStaleByTime(be(t.staleTime,e))}function Ma(e,t){return!Vt(e.getCurrentResult(),t)}var xa=class extends ki{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,s=super.createResult(e,t),{isFetching:r,isRefetching:i,isError:o,isRefetchError:a}=s,u=n.fetchMeta?.fetchMore?.direction,l=o&&u==="forward",c=r&&u==="forward",h=o&&u==="backward",d=r&&u==="backward";return{...s,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Ea(t,n.data),hasPreviousPage:Ta(t,n.data),isFetchNextPageError:l,isFetchingNextPage:c,isFetchPreviousPageError:h,isFetchingPreviousPage:d,isRefetchError:a&&!l&&!h,isRefetching:i&&!c&&!d}}},Oa=class extends Pi{#t;#e;#n;#s;constructor(e){super(),this.#t=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#e=[],this.state=e.state||Ni(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#e.includes(e)||(this.#e.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#i({type:"continue"})},n={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=Oi({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(i,o)=>{this.#i({type:"failed",failureCount:i,error:o})},onPause:()=>{this.#i({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const s=this.state.status==="pending",r=!this.#s.canStart();try{if(s)t();else{this.#i({type:"pending",variables:e,isPaused:r}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const o=await this.options.onMutate?.(e,n);o!==this.state.context&&this.#i({type:"pending",context:o,variables:e,isPaused:r})}const i=await this.#s.start();return await this.#n.config.onSuccess?.(i,e,this.state.context,this,n),await this.options.onSuccess?.(i,e,this.state.context,n),await this.#n.config.onSettled?.(i,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(i,null,e,this.state.context,n),this.#i({type:"success",data:i}),i}catch(i){try{await this.#n.config.onError?.(i,e,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onError?.(i,e,this.state.context,n)}catch(o){Promise.reject(o)}try{await this.#n.config.onSettled?.(void 0,i,this.state.variables,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,i,e,this.state.context,n)}catch(o){Promise.reject(o)}throw this.#i({type:"error",error:i}),i}finally{this.#n.runNext(this)}}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),H.batch(()=>{this.#e.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function Ni(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Pa=class extends Ye{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const s=new Oa({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(s),s}add(e){this.#t.add(e);const t=Tt(e);if(typeof t=="string"){const n=this.#e.get(t);n?n.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=Tt(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const s=n.indexOf(e);s!==-1&&n.splice(s,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Tt(e);if(typeof t=="string"){const n=this.#e.get(t)?.find(s=>s.state.status==="pending");return!n||n===e}else return!0}runNext(e){const t=Tt(e);return typeof t=="string"?this.#e.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){H.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Xs(t,n))}findAll(e={}){return this.getAll().filter(t=>Xs(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 Tt(e){return e.options.scope?.id}var La=class extends Ye{#t;#e=void 0;#n;#s;constructor(e,t){super(),this.#t=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#t.defaultMutationOptions(e),Vt(this.options,t)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&De(t.mutationKey)!==De(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#r(e)}getCurrentResult(){return this.#e}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#r()}mutate(e,t){return this.#s=t,this.#n?.removeObserver(this),this.#n=this.#t.getMutationCache().build(this.#t,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){const e=this.#n?.state??Ni();this.#e={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#r(e){H.batch(()=>{if(this.#s&&this.hasListeners()){const t=this.#e.variables,n=this.#e.context,s={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#s.onSuccess?.(e.data,t,n,s)}catch(r){Promise.reject(r)}try{this.#s.onSettled?.(e.data,null,t,n,s)}catch(r){Promise.reject(r)}}else if(e?.type==="error"){try{this.#s.onError?.(e.error,t,n,s)}catch(r){Promise.reject(r)}try{this.#s.onSettled?.(void 0,e.error,t,n,s)}catch(r){Promise.reject(r)}}}this.listeners.forEach(t=>{t(this.#e)})})}},Fa=class extends Ye{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const s=t.queryKey,r=t.queryHash??Is(s,t);let i=this.get(r);return i||(i=new _a({client:e,queryKey:s,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(s)}),this.add(i)),i}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){H.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Js(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Js(e,n)):t}notify(e){H.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){H.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){H.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},bf=class{#t;#e;#n;#s;#i;#r;#o;#a;constructor(e={}){this.#t=e.queryCache||new Fa,this.#e=e.mutationCache||new Pa,this.#n=e.defaultOptions||{},this.#s=new Map,this.#i=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=ys.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#a=qt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),s=n.state.data;return s===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(be(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(s))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(e,t,n){const s=this.defaultQueryOptions({queryKey:e}),r=this.#t.get(s.queryHash)?.state.data,i=pa(t,r);if(i!==void 0)return this.#t.build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return H.batch(()=>this.#t.findAll(e).map(({queryKey:s})=>[s,this.setQueryData(s,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;H.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return H.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},s=H.batch(()=>this.#t.findAll(e).map(r=>r.cancel(n)));return Promise.all(s).then(q).catch(q)}invalidateQueries(e,t={}){return H.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},s=H.batch(()=>this.#t.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(q)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(be(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(q).catch(q)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return qt.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(s=>{ft(e,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#i.values()],n={};return t.forEach(s=>{ft(e,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Is(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===Rs&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},I=Ti(Ss(),1),F=la(),Di=I.createContext(void 0),ji=e=>{const t=I.useContext(Di);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wf=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,F.jsx)(Di.Provider,{value:e,children:t})),Gi=I.createContext(!1),ka=()=>I.useContext(Gi),Ef=Gi.Provider;function Na(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Da=I.createContext(Na()),ja=()=>I.useContext(Da),Ga=(e,t,n)=>{const s=n?.state.error&&typeof e.throwOnError=="function"?Cs(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||s)&&(t.isReset()||(e.retryOnMount=!1))},Ua=e=>{I.useEffect(()=>{e.clearReset()},[e])},$a=({result:e,errorResetBoundary:t,throwOnError:n,query:s,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&s&&(r&&e.data===void 0||Cs(n,[e.error,s])),Ba=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),s=e.staleTime;e.staleTime=typeof s=="function"?(...r)=>n(s(...r)):n(s),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Ha=(e,t)=>e.isLoading&&e.isFetching&&!t,za=(e,t)=>e?.suspense&&t.isPending,rr=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ui(e,t,n){const s=ka(),r=ja(),i=ji(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const a=i.getQueryCache().get(o.queryHash);o._optimisticResults=s?"isRestoring":"optimistic",Ba(o),Ga(o,r,a),Ua(r);const u=!i.getQueryCache().get(o.queryHash),[l]=I.useState(()=>new t(i,o)),c=l.getOptimisticResult(o),h=!s&&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]),za(o,c))throw rr(o,l,r);if($a({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&&!pt.isServer()&&Ha(c,s)&&(u?rr(o,l,r):a?.promise)?.catch(q).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?c:l.trackResult(c)}function Tf(e,t){return Ui(e,ki,t)}function _f(e,t){const n=ji(t),[s]=I.useState(()=>new La(n,e));I.useEffect(()=>{s.setOptions(e)},[s,e]);const r=I.useSyncExternalStore(I.useCallback(o=>s.subscribe(H.batchCalls(o)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),i=I.useCallback((o,a)=>{s.mutate(o,a).catch(q)},[s]);if(r.error&&Cs(s.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:i,mutateAsync:r.mutate}}function Af(e,t){return Ui(e,xa,t)}var ir=I.use,ws=I.useLayoutEffect;function Va(e,t,n){I.useEffect(()=>{if(!e.current||n||typeof IntersectionObserver!="function")return()=>t();const s=new IntersectionObserver(r=>{t(r.pop())},{rootMargin:"100px"});return s.observe(e.current),()=>{s.disconnect(),t()}},[t,n,e])}function qa(e){const t=I.useRef(null);return I.useImperativeHandle(e,()=>t.current,[]),t}function gt(e){return e[e.length-1]}function We(e,t){return typeof e=="function"?e(t):e}var $i=Object.prototype.hasOwnProperty,Ka=Object.prototype.propertyIsEnumerable;function Bi(e){for(const t in e)if($i.call(e,t))return!0;return!1}var Qa=()=>Object.create(null),xe=(e,t)=>Fe(e,t,Qa);function Fe(e,t,n=()=>({}),s=0){if(e===t)return e;if(s>500)return t;const r=t,i=lr(e)&&lr(r);if(!i&&!(Kt(e)&&Kt(r)))return r;const o=i?e:or(e);if(!o)return r;const a=i?r:or(r);if(!a)return r;const u=o.length,l=a.length,c=i?new Array(l):n();let h=0;for(let d=0;d<l;d++){const f=i?d:a[d],p=e[f],g=r[f];if(p===g){c[f]=p,(i?d<u:$i.call(e,f))&&h++;continue}if(p===null||g===null||typeof p!="object"||typeof g!="object"){c[f]=g;continue}const m=Fe(p,g,n,s+1);c[f]=m,m===p&&h++}return u===l&&h===u?e:c}function or(e){const t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;const n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(const s of n){if(!Ka.call(e,s))return!1;t.push(s)}return t}function Kt(e){if(!ar(e))return!1;const t=e.constructor;if(typeof t>"u")return!0;const n=t.prototype;return!(!ar(n)||!n.hasOwnProperty("isPrototypeOf"))}function ar(e){return Object.prototype.toString.call(e)==="[object Object]"}function lr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function we(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let s=0,r=e.length;s<r;s++)if(!we(e[s],t[s],n))return!1;return!0}if(Kt(e)&&Kt(t)){const s=n?.ignoreUndefined??!0;if(n?.partial){for(const o in t)if((!s||t[o]!==void 0)&&!we(e[o],t[o],n))return!1;return!0}let r=0;if(!s)r=Object.keys(e).length;else for(const o in e)e[o]!==void 0&&r++;let i=0;for(const o in t)if((!s||t[o]!==void 0)&&(i++,i>r||!we(e[o],t[o],n)))return!1;return r===i}return!1}function Wa(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 Ja=/[\x00-\x1f\x7f"<>`{}]/g;function Xa(e){return e.replace(Ja,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function ur(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,n=>{try{return decodeURI(n)}catch{return n}})}return Xa(t)}var Ya=["http:","https:","mailto:","tel:"];function Qt(e,t){if(!e)return!1;try{const n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function st(e){if(!e)return{path:e,handledProtocolRelativeURL:!1};if(!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith("//"))return{path:e,handledProtocolRelativeURL:!1};const t=/%25|%5C/gi;let n=0,s="",r;for(;(r=t.exec(e))!==null;)s+=ur(e.slice(n,r.index))+r[0],n=t.lastIndex;s=s+ur(n?e.slice(n):e);let i=!1;return s.startsWith("//")&&(i=!0,s="/"+s.replace(/^\/+/,"")),{path:s,handledProtocolRelativeURL:i}}function Za(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function el(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Es(){throw new Error("Invariant failed")}function Wt(e){const t=new Map;let n,s;const r=i=>{i.next&&(i.prev?(i.prev.next=i.next,i.next.prev=i.prev,i.next=void 0,s&&(s.next=i,i.prev=s)):(i.next.prev=void 0,n=i.next,i.next=void 0,s&&(i.prev=s,s.next=i)),s=i)};return{get(i){const o=t.get(i);if(o)return r(o),o.value},set(i,o){if(t.size>=e&&n){const u=n;t.delete(u.key),u.next&&(n=u.next,u.next.prev=void 0),u===s&&(s=void 0)}const a=t.get(i);if(a)a.value=o,r(a);else{const u={key:i,value:o,prev:s};s&&(s.next=u),s=u,n||(n=u),t.set(i,u)}},clear(){t.clear(),n=void 0,s=void 0}}}var Re=4,Hi=5;function zi(e,t,n=new Uint16Array(6)){const s=e.indexOf("/",t),r=s===-1?e.length:s,i=e.substring(t,r);if(!i||!i.includes("$"))return n[0]=0,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n;if(i==="$"){const u=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=u,n[4]=u,n[5]=u,n}if(i.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=r,n[4]=r,n[5]=r,n;const o=i.indexOf("{");let a;if(o!==-1&&o+1<i.length&&(a=i.indexOf("}",o))!==-1){const u=i.charCodeAt(o+1);if(u===45){if(o+2<i.length&&i.charCodeAt(o+2)===36){const l=o+3,c=a;if(l<c)return n[0]=3,n[1]=t+o,n[2]=t+l,n[3]=t+c,n[4]=t+a+1,n[5]=r,n}}else if(u===36){const l=o+1,c=o+2;return c===a?(n[0]=2,n[1]=t+o,n[2]=t+l,n[3]=t+c,n[4]=t+a+1,n[5]=e.length,n):(n[0]=1,n[1]=t+o,n[2]=t+c,n[3]=t+a,n[4]=t+a+1,n[5]=r,n)}}return n[0]=0,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}function sn(e,t,n,s,r,i,o,a){a?.(n);let u=s;{const l=n.fullPath??n.from,c=n.options,h=l.length,d=c?.caseSensitive??e,f=c?.params?.parse??c?.parseParams;for(;u<h;){const g=zi(l,u,t);let m;const v=u,S=g[5];u=S+1,i++;const C=g[0];switch(C){case 0:{const w=l.substring(g[2],g[3]);let b=w,R;d?R=r.static??=new Map:(b=w.toLowerCase(),R=r.staticInsensitive??=new Map);const y=R.get(b);if(y)m=y;else{const T=Ke(l);T.parent=r,T.depth=i,m=T,R.set(b,T)}break}case 1:case 3:case 2:{let w=l.substring(v,g[1]),b=l.substring(g[4],S);const R=d&&!!(w||b);d||(w=w.toLowerCase(),b=b.toLowerCase());const y=C===1?r.dynamic:C===3?r.optional:r.wildcard,T=C!==2&&!f&&y?.find(_=>!_.parse&&_.caseSensitive===R&&_.prefix===w&&_.suffix===b);if(T)m=T;else{const _=tl(C,l,R,w,b);m=_,_.parent=r,_.depth=i;let E;C===1?E=r.dynamic??=[]:C===3?E=r.optional??=[]:E=r.wildcard??=[],E.push(_),E.length===2&&o?.push(E)}break}}r=m}if(f&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf("/")+1)===95){const g=Ke(l);g.kind=Hi,g.parent=r,i++,g.depth=i,r.pathless??=[],r.pathless.push(g),r=g}const p=(n.path||!n.children)&&!n.isRoot;if(p&&l.endsWith("/")){const g=Ke(l);g.kind=Re,g.parent=r,i++,g.depth=i,r.index=g,r=g}r.parse=f??null,r.priority=c?.params?.priority??0,p&&!r.route&&(r.route=n,r.fullPath=l)}if(n.children)for(const l of n.children)sn(e,t,l,u,r,i,o,a)}function Vi(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 Ke(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function tl(e,t,n,s,r){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:s,suffix:r}}function nl(e,t){const n=Ke("/"),s=new Uint16Array(6),r=[];for(const i of e)sn(!1,s,i,1,n,0,r);for(const i of r)i.sort(Vi);t.masksTree=n,t.flatCache=Wt(1e3)}function sl(e,t){e||="/";const n=t.flatCache.get(e);if(n!==void 0)return n;const s=Ts(e,t.masksTree);return t.flatCache.set(e,s),s}function rl(e,t,n,s,r){e||="/",s||="/";const i=t?`case\0${e}`:e;let o=r.singleCache.get(i);return o||(o=Ke("/"),sn(t,new Uint16Array(6),{from:e},1,o,0),r.singleCache.set(i,o)),Ts(s,o,n)}function il(e,t,n=!1){const s=n?e:`nofuzz\0${e}`,r=t.matchCache.get(s);if(r!==void 0)return r;e||="/";let i;try{i=Ts(e,t.segmentTree,n)}catch(o){if(o instanceof URIError)i=null;else throw o}return i&&(i.branch=Ki(i.route)),t.matchCache.set(s,i),i}function ol(e){return e==="/"?e:e.replace(/\/{1,}$/,"")}function al(e,t=!1,n){const s=Ke(e.fullPath),r=new Uint16Array(6),i=[],o={},a={};let u=0;sn(t,r,e,1,s,0,i,l=>{if(n?.(l,u),l.id in o&&Es(),o[l.id]=l,u!==0&&l.path){const c=ol(l.fullPath);(!a[c]||l.fullPath.endsWith("/"))&&(a[c]=l)}u++});for(const l of i)l.sort(Vi);return{processedTree:{segmentTree:s,singleCache:Wt(1e3),matchCache:Wt(1e3),flatCache:null,masksTree:null},routesById:o,routesByPath:a}}function Ts(e,t,n=!1){const s=e.split("/"),r=ul(e,s,t,n);if(!r)return null;const[i]=qi(e,s,r);return{route:r.node.route,rawParams:i}}function qi(e,t,n){const s=ll(n.node);let r=null;const i=Object.create(null);let o=n.extract?.part??0,a=n.extract?.node??0,u=n.extract?.path??0,l=n.extract?.segment??0;for(;a<s.length;o++,a++,u++,l++){const c=s[a];if(c.kind===Re)break;if(c.kind===Hi){l--,o--,u--;continue}const h=t[o],d=u;if(h&&(u+=h.length),c.kind===1){r??=n.node.fullPath.split("/");const f=r[l],p=c.prefix.length;if(f.charCodeAt(p)===123){const g=c.suffix.length,m=f.substring(p+2,f.length-g-1),v=h.substring(p,h.length-g);i[m]=decodeURIComponent(v)}else{const g=f.substring(1);i[g]=decodeURIComponent(h)}}else if(c.kind===3){if(n.skipped&1<<a){o--,u=d-1;continue}r??=n.node.fullPath.split("/");const f=r[l],p=c.prefix.length,g=c.suffix.length,m=f.substring(p+3,f.length-g-1),v=c.suffix||c.prefix?h.substring(p,h.length-g):h;v&&(i[m]=decodeURIComponent(v))}else if(c.kind===2){const f=c,p=e.substring(d+f.prefix.length,e.length-f.suffix.length),g=decodeURIComponent(p);i["*"]=g,i._splat=g;break}}return n.rawParams&&Object.assign(i,n.rawParams),[i,{part:o,node:a,path:u,segment:l}]}function Ki(e){const t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function ll(e){const t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function ul(e,t,n,s){if(e==="/"&&n.index)return{node:n.index,skipped:0};const r=!gt(t),i=r&&e!=="/",o=t.length-(r?1:0),a=[{node:n,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:m}=c;let{extract:v,rawParams:S}=c;if(h.kind===2&&h.route&&!At(l,c))continue;if(h.parse){if(!cr(e,t,c))continue;S=c.rawParams,v=c.extract}s&&h.route&&h.kind!==Re&&At(u,c)&&(u=c);const C=d===o;if(C&&(h.route&&(!i||h.kind===Re||h.kind===2)&&At(l,c)&&(l=c),!h.optional&&!h.wildcard&&!h.index&&!h.pathless))continue;const w=C?void 0:t[d];let b;if(C&&h.index){const R={node:h.index,index:d,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S};let y=!0;if(h.index.parse&&(cr(e,t,R)||(y=!1)),y){if(!g&&!m&&!f&&cl(p,o))return R;At(l,R)&&(l=R)}}if(h.wildcard)for(let R=h.wildcard.length-1;R>=0;R--){const y=h.wildcard[R],{prefix:T,suffix:_}=y;if(!(T&&(C||!(y.caseSensitive?w:b??=w.toLowerCase()).startsWith(T)))){if(_){if(C)continue;const E=t.slice(d).join("/"),x=E.slice(-_.length);if((y.caseSensitive?x:x.toLowerCase())!==_||E.length-_.length<T.length)continue}a.push({node:y,index:o,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}}if(h.optional){const R=f|1<<h.depth+1;for(let y=h.optional.length-1;y>=0;y--){const T=h.optional[y];a.push({node:T,index:d,skipped:R,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}if(!C)for(let y=h.optional.length-1;y>=0;y--){const T=h.optional[y],{prefix:_,suffix:E}=T;if(_||E){const x=T.caseSensitive?w:b??=w.toLowerCase();if(_&&!x.startsWith(_)||E&&x.indexOf(E,x.length-E.length)<_.length)continue}a.push({node:T,index:d+1,skipped:f,statics:p,dynamics:g,optionals:m+_t(o,d),extract:v,rawParams:S})}}if(!C&&h.dynamic&&w)for(let R=h.dynamic.length-1;R>=0;R--){const y=h.dynamic[R],{prefix:T,suffix:_}=y;if(T||_){const E=y.caseSensitive?w:b??=w.toLowerCase();if(T&&!E.startsWith(T)||_&&E.indexOf(_,E.length-_.length)<T.length)continue}a.push({node:y,index:d+1,skipped:f,statics:p,dynamics:g+_t(o,d),optionals:m,extract:v,rawParams:S})}if(!C&&h.staticInsensitive){const R=h.staticInsensitive.get(b??=w.toLowerCase());R&&a.push({node:R,index:d+1,skipped:f,statics:p+_t(o,d),dynamics:g,optionals:m,extract:v,rawParams:S})}if(!C&&h.static){const R=h.static.get(w);R&&a.push({node:R,index:d+1,skipped:f,statics:p+_t(o,d),dynamics:g,optionals:m,extract:v,rawParams:S})}if(h.pathless)for(let R=h.pathless.length-1;R>=0;R--){const y=h.pathless[R];a.push({node:y,index:d,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}}if(l)return l;if(s&&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 _t(e,t){return 2**(e-t-1)}function cl(e,t){return e===2**(t-1)-1}function cr(e,t,n){let s,r;try{[s,r]=qi(e,t,n)}catch{return null}if(n.rawParams=s,n.extract=r,!n.node.parse)return!0;try{if(n.node.parse(s)===!1)return null}catch{}return!0}function At(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 Ut(e){return $t(e.filter(t=>t!==void 0).join("/"))}function $t(e){return e.replace(/\/{2,}/g,"/")}function Qi(e){return e==="/"?e:e.replace(/^\/{1,}/,"")}function me(e){const t=e.length;return t>1&&e[t-1]==="/"?e.replace(/\/{1,}$/,""):e}function Wi(e){return me(Qi(e))}function Jt(e,t){return e?.endsWith("/")&&e!=="/"&&e!==`${t}/`?e.slice(0,-1):e}function dl(e,t,n){return Jt(e,n)===Jt(t,n)}function hl({base:e,to:t,trailingSlash:n="never",cache:s}){if(t.includes("//")&&(t=$t(t)),t.startsWith("/"))return t.length===1||n==="preserve"?t:n==="always"?t.endsWith("/")?t:`${t}/`:t.endsWith("/")?t.slice(0,-1):t;const r=t===".";let i;if(s){i=r?e:e+"\0"+t;const l=s.get(i);if(l)return l}let o;if(r)o=e.split("/");else{for(e.includes("//")&&(e=$t(e)),o=e.split("/");o.length>1&>(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&&(gt(o)===""?n==="never"&&o.pop():n==="always"&&o.push(""));const a=o.join("/"),u=(r?$t(a):a)||"/";return i&&s&&s.set(i,u),u}function fl(e){const t=new Map(e.map(r=>[encodeURIComponent(r),r])),n=Array.from(t.keys()).map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),s=new RegExp(n,"g");return r=>r.replace(s,i=>t.get(i)??i)}function yn(e,t,n){const s=t[e];return typeof s!="string"?s:e==="_splat"?/^[a-zA-Z0-9\-._~!/]*$/.test(s)?s:s.split("/").map(r=>hr(r,n)).join("/"):hr(s,n)}function dr({path:e,params:t,decoder:n,...s}){let r=!1;const i=Object.create(null);if(!e||e==="/")return{interpolatedPath:"/",usedParams:i,isMissingParams:r};if(!e.includes("$"))return{interpolatedPath:e,usedParams:i,isMissingParams:r};const o=e.length;let a=0,u,l="";for(;a<o;){const c=a;u=zi(e,c,u);const h=u[5];if(a=h+1,c===h)continue;const d=u[0];if(d===0){l+="/"+e.substring(c,h);continue}if(d===2){const f=t._splat;i._splat=f,i["*"]=f;const p=e.substring(c,u[1]),g=e.substring(u[4],h);if(!f){r=!0,(p||g)&&(l+="/"+p+g);continue}const m=yn("_splat",t,n);l+="/"+p+m+g;continue}if(d===1){const f=e.substring(u[2],u[3]);!r&&!(f in t)&&(r=!0),i[f]=t[f];const p=e.substring(c,u[1]),g=e.substring(u[4],h),m=yn(f,t,n)??"undefined";l+="/"+p+m+g;continue}if(d===3){const f=e.substring(u[2],u[3]),p=t[f];if(p==null)continue;i[f]=p;const g=e.substring(c,u[1]),m=e.substring(u[4],h),v=yn(f,t,n)??"";l+="/"+g+v+m;continue}}return e.endsWith("/")&&(l+="/"),{usedParams:i,interpolatedPath:l||"/",isMissingParams:r}}function hr(e,t){const n=encodeURIComponent(e);return t?.(n)??n}function Je(e){return e?.isNotFound===!0}function pl(){try{return sessionStorage}catch{return}}var gl="tsr-scroll-restoration-v1_3",Ji=pl();function ml(){try{return JSON.parse(Ji?.getItem("tsr-scroll-restoration-v1_3")||"{}")}catch{return{}}}function vl(){try{Ji?.setItem(gl,JSON.stringify(Ve))}catch{}}var Ve=ml(),fr="data-scroll-restoration-id",Sl=e=>e.state.__TSR_key||e.href;function yl(e){const t=e.getAttribute(fr);if(t)return`[${fr}="${t}"]`;let n="",s=e,r;for(;r=s.parentNode;){let i=1,o=s;for(;o=o.previousElementSibling;)i++;const a=`${s.localName}:nth-child(${i})`;n=n?`${a} > ${n}`:a,s=r}return n}var Mt=!1,Bt="window";function Kn(e){try{return typeof e=="function"?e():document.querySelector(e)}catch{}}function pr(e){const t=new Set;for(const n of e){if(n===Bt)continue;const s=Kn(n);s&&t.add(s)}return t}function Il(e,t){const n=t??e.options.scrollRestoration,s=e._scroll;n&&(s.restoring=!0);const r=e.options.getScrollRestorationKey||Sl,i=new Set,o=a=>{const u=Ve[a]||={};for(const l of i)l===document?u[Bt]={scrollX,scrollY}:l.isConnected&&(u[yl(l)]={scrollX:l.scrollLeft,scrollY:l.scrollTop})};n&&!s.restoration&&(s.restoration=!0,Mt=!1,history.scrollRestoration="manual",document.addEventListener("scroll",a=>{Mt||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())),vl()})),!s.reset&&(s.reset=!0,e.subscribe("onRendered",a=>{const u=e.options.scrollRestorationBehavior,l=e.options.scrollToTopSelectors,c=s.next,h=s.hash;let d;if(i.clear(),s.next=!0,s.hash=!1,typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation}))return;const f=r(a.toLocation),p=a.fromLocation&&r(a.fromLocation);if(s.restoring&&p&&p!==f){const g=Ve[p];if(g){let m=Ve[f];for(const v in g){if(v===Bt){if(c)continue}else{const S=Kn(v);if(!S||c&&l&&(d??=pr(l),d.has(S)))continue}m||(m=Ve[f]={}),m[v]??=g[v]}}}Mt=!0;try{const g=a.toLocation.hash,m=a.toLocation.state.__hashScrollIntoViewOptions??!0;let v=!1;if(c){!g&&l&&(d??=pr(l));const S=g&&m&&h,C=s.restoring?Ve[f]:void 0;if(C)for(const w in C){const{scrollX:b,scrollY:R}=C[w];if(w===Bt){if(S)continue;scrollTo({top:R,left:b,behavior:u}),v=!0}else{const y=Kn(w);y&&(y.scrollLeft=b,y.scrollTop=R,d?.delete(y))}}if(!g){const w={top:0,left:0,behavior:u};if(v||scrollTo(w),d)for(const b of d)b.scrollTo(w)}}!v&&g&&m&&document.getElementById(g)?.scrollIntoView(m)}finally{Mt=!1}}))}function Rl(e,t=String){const n=new URLSearchParams;for(const s in e){const r=e[s];r!==void 0&&n.set(s,t(r))}return n.toString()}function In(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function Cl(e){const t=new URLSearchParams(e),n=Object.create(null);for(const[s,r]of t.entries()){const i=n[s];i==null?n[s]=In(r):Array.isArray(i)?i.push(In(r)):n[s]=[i,In(r)]}return n}var bl=/^(?:\s|["[{\d-]|fa|nu|tr)/,wl=Tl(JSON.parse),El=_l(JSON.stringify,JSON.parse);function Tl(e){return t=>{t[0]==="?"&&(t=t.substring(1));const n=Cl(t);for(const s in n){const r=n[s];if(typeof r=="string")try{n[s]=e(r)}catch{}}return n}}function _l(e,t){const n=t===JSON.parse;function s(r){if(r&&typeof r=="object")try{return e(r)}catch{}else if(t&&typeof r=="string"){if(n&&!bl.test(r))return r;try{return t(r),e(r)}catch{}}return r}return r=>{const i=Rl(r,s);return i?`?${i}`:""}}var ut="__root__";function Al(e){if(e.statusCode=e.statusCode||e.code||307,!e.reloadDocument&&typeof e.href=="string")try{new URL(e.href),e.reloadDocument=!0}catch{}const t=new Headers(e.headers);e.href&&t.get("Location")===null&&t.set("Location",e.href);const n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function Xi(e){return e instanceof Response&&!!e.options}function Ml(e){return{input:({url:t})=>{for(const n of e)t=Qn(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=Yi(e[n],t);return t}}}function xl(e){const t=Wi(e.basepath),n=`/${t}`,s=e.caseSensitive?n:n.toLowerCase(),r=`${s}/`;return{input:({url:i})=>{const o=e.caseSensitive?i.pathname:i.pathname.toLowerCase();return o===s?i.pathname="/":o.startsWith(r)&&(i.pathname=i.pathname.slice(n.length)),i},output:({url:i})=>(i.pathname=Ut(["/",t,i.pathname]),i)}}function Qn(e,t){const n=e?.input?.({url:t});if(n){if(typeof n=="string")return new URL(n);if(n instanceof URL)return n}return t}function Yi(e,t){const n=e?.output?.({url:t});if(n){if(typeof n=="string")return new URL(n);if(n instanceof URL)return n}return t}function Ol(e,t){const{createMutableStore:n,createReadonlyStore:s,batch:r}=t,i=new Map,o=n("idle"),a=n(e),u=n(void 0),l=n([]),c=s(()=>l.get().map(g=>i.get(g).get())),h=s(()=>({status:o.get(),isLoading:o.get()==="pending",matches:c.get(),location:a.get(),resolvedLocation:u.get()}));function d(g){let m=i.get(g);return m||(m=n(void 0),i.set(g,m)),m}const f={status:o,location:a,resolvedLocation:u,ids:l,matches:c,byRoute:i,__store:h,getMatchStore:d,setMatches:p};function p(g){const m=l.get(),v=g.map(S=>S.routeId);r(()=>{el(m,v)||l.set(v);for(const S of m)v.includes(S)||i.get(S).set(()=>{});for(const S of g){const C=d(S.routeId);C.get()!==S&&C.set(S)}})}return f}var Ee="__TSR_index",gr="popstate",mr="beforeunload";function Pl(e){let t=e.getLocation();const n=new Set,s=o=>{t=e.getLocation(),n.forEach(a=>a({location:t,action:o}))},r=o=>{e.notifyOnIndexChange??!0?s(o):t=e.getLocation()},i=async({task:o,navigateOpts:a,...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=Xt(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:n,subscribe:o=>(n.add(o),()=>{n.delete(o)}),push:(o,a,u)=>{const l=t.state[Ee];a=vr(l+1,a),i({task:()=>{e.pushState(o,a),s({type:"PUSH"})},navigateOpts:u,type:"PUSH",path:o,state:a})},replace:(o,a,u)=>{const l=t.state[Ee];a=vr(l,a),i({task:()=>{e.replaceState(o,a),s({type:"REPLACE"})},navigateOpts:u,type:"REPLACE",path:o,state:a})},go:(o,a)=>{i({task:()=>{e.go(o),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:s}}function vr(e,t){t||(t={});const n=_s();return{...t,key:n,__TSR_key:n,[Ee]:e}}function Ll(e){const t=e?.window??(typeof document<"u"?window:void 0),n=t.history.pushState,s=t.history.replaceState;let r=[];const i=()=>r,o=y=>r=y,a=e?.createHref??(y=>y),u=e?.parseLocation??(()=>Xt(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){const y=_s();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 m;const v=()=>{m&&(R._ignoreSubscribers=!0,(m[2]?t.history.pushState:t.history.replaceState)(m[1],"",m[0]),R._ignoreSubscribers=!1,m=void 0,c=void 0)},S=(y,T,_)=>{const E=a(T),x=!!m;x||(c=l),l=Xt(T,_),m=[E,_,m?.[2]||y],x||queueMicrotask(()=>v())},C=y=>{l=u(),R.notify({type:y})},w=async()=>{if(d){d=!1;return}const y=u(),T=y.state[Ee]-l.state[Ee],_=T===1,E=T===-1,x=!_&&!E||h;h=!1;const N=x?"GO":E?"BACK":"FORWARD",k=x?{type:"GO",index:T}:{type:E?"BACK":"FORWARD"};if(f)f=!1;else{const j=i();if(typeof document<"u"&&j.length){for(const A of j)if(await A.blockerFn({currentLocation:l,nextLocation:y,action:N})){d=!0,t.history.go(1),R.notify(k);return}}}l=u(),R.notify(k)},b=y=>{if(p){p=!1;return}let T=!1;const _=i();if(typeof document<"u"&&_.length)for(const E of _){const x=E.enableBeforeUnload??!0;if(x===!0){T=!0;break}if(typeof x=="function"&&x()===!0){T=!0;break}}if(T)return y.preventDefault(),y.returnValue=""},R=Pl({getLocation:g,getLength:()=>t.history.length,pushState:(y,T)=>S(!0,y,T),replaceState:(y,T)=>S(!1,y,T),back:y=>(y&&(f=!0),p=!0,t.history.back()),forward:y=>{y&&(f=!0),p=!0,t.history.forward()},go:y=>{h=!0,t.history.go(y)},createHref:y=>a(y),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=s,t.removeEventListener(mr,b,{capture:!0}),t.removeEventListener(gr,w)},onBlocked:()=>{c&&l!==c&&(l=c)},getBlockers:i,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(mr,b,{capture:!0}),t.addEventListener(gr,w),t.history.pushState=function(...y){const T=n.apply(t.history,y);return R._ignoreSubscribers||C("PUSH"),T},t.history.replaceState=function(...y){const T=s.apply(t.history,y);return R._ignoreSubscribers||C("REPLACE"),T},R}function Fl(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"");return t.startsWith("//")&&(t="/"+t.replace(/^\/+/,"")),t}function Xt(e,t){const n=Fl(e),s=n.indexOf("#"),r=n.indexOf("?"),i=_s();return{href:n,pathname:n.substring(0,s>0?r>0?Math.min(s,r):s:r>0?r:n.length),hash:s>-1?n.substring(s):"",search:r>-1?n.slice(r,s===-1?void 0:s):"",state:t||{[Ee]:0,key:i,__TSR_key:i}}}function _s(){return(Math.random()+1).toString(36).substring(7)}function Sr(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function rn(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function yr({key:e,__TSR_key:t,__TSR_index:n,__hashScrollIntoViewOptions:s,...r}){return r}function kl(e,t,n,s){for(const r of t){if(s&&e._tx!==s)return;n.some(i=>i.routeId===r.routeId)||e.routesById[r.routeId].options.onLeave?.(r)}for(const r of n){if(s&&e._tx!==s)return;e.routesById[r.routeId].options[t.some(i=>i.routeId===r.routeId)?"onStay":"onEnter"]?.(r)}}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.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=async n=>(n(),!1),this.update=n=>{const s=this.options,r=this.basepath??s?.basepath??"/",i=this.basepath===void 0,o=s?.rewrite;if(this.options={...s,...n},this.isServer=this.options.isServer??!1??typeof document>"u",this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=fl(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=Ll()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost"),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let l;this.resolvePathCache=Wt(1e3),l=this.buildRouteTree(),this.setRoutes(l)}if(!this.stores&&this.latestLocation){const l=this.getStoreConfig(this);this.batch=l.batch,this.stores=Ol(this.latestLocation,l),Il(this)}const a=this.options.basepath??"/",u=this.options.rewrite;if(i||r!==a||o!==u){this.basepath=a;const l=[],c=Wi(a);c&&c!=="/"&&l.push(xl({basepath:a})),u&&l.push(u),this.rewrite=l.length===0?void 0:l.length===1?l[0]:Ml(l),this.history&&this.updateLatestLocation(),this.stores&&this.stores.location.set(this.latestLocation)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const n=al(this.routeTree,this.options.caseSensitive,(s,r)=>{s.init({originalIndex:r})});return this.options.routeMasks&&nl(this.options.routeMasks,n.processedTree),n},this.subscribe=(n,s)=>{const r={eventType:n,fn:s};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=n=>{for(const s of this.subscribers)if(s.eventType===n.type)try{s.fn(n)}catch(r){console.error(r)}},this.parseLocation=(n,s)=>{const r=({pathname:u,search:l,hash:c,href:h,state:d})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(u)){const v=this.options.parseSearch(l),S=this.options.stringifySearch(v);return{href:u+S+c,publicHref:u+S+c,pathname:st(u).path,external:!1,searchStr:S,search:xe(s?.search,v),hash:st(c.slice(1)).path,state:Fe(s?.state,d)}}const f=new URL(h,this.origin),p=Qn(this.rewrite,f),g=this.options.parseSearch(p.search),m=this.options.stringifySearch(g);return p.search=m,{href:p.href.replace(p.origin,""),publicHref:h,pathname:st(p.pathname).path,external:!!this.rewrite&&p.origin!==this.origin,searchStr:m,search:xe(s?.search,g),hash:st(p.hash.slice(1)).path,state:Fe(s?.state,d)}},i=r(n),{__tempLocation:o,__tempKey:a}=i.state;if(o&&(!a||a===this.tempLocationKey)){const u=r(o);return u.state.key=i.state.key,u.state.__TSR_key=i.state.__TSR_key,delete u.state.__tempLocation,{...u,maskedLocation:i}}return i},this.resolvePathWithBase=(n,s)=>hl({base:n,to:s,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(n,s,r)=>typeof n=="string"?this.matchRoutesInternal({pathname:n,search:s},r):this.matchRoutesInternal(n,s),this.getMatchedRoutes=n=>{const s=Object.create(null),r=il(me(n),this.processedTree,!0);return r&&Object.assign(s,r.rawParams),[r?.branch||[this.routesById.__root__],s,r?.route]},this.buildLocation=n=>{const s=(i={})=>{if(i.href){const _=Xt(i.href,{});i={...i,to:Qn(this.rewrite,new URL(_.pathname,this.origin)).pathname,search:this.options.parseSearch(_.search),hash:_.hash.slice(1)}}const o=i._fromLocation||this._pendingLocation||this.latestLocation,a=this.matchRoutesLightweight(o);i.from;const u=i.unsafeRelative==="path"?o.pathname:i.from??a[1],l=a[2],c=a[3],h=this.resolvePathWithBase(u,i.to?`${i.to}`:".");let d=Ir(i.params,c);const f=this.routesByPath[me(h)];let p;if(f)p=this.getRouteBranch(f);else if(h.includes("$"))p=[];else{const[_,E,x]=this.getMatchedRoutes(h);p=_,this.options.notFoundRoute&&(!x||x.path!=="/"&&E["**"])&&(p=[...p,this.options.notFoundRoute])}if(p.length&&Bi(d))for(const _ of p){const E=_.options.params?.stringify??_.options.stringifyParams;if(E){d===c&&(d=Object.assign(Object.create(null),d));try{Object.assign(d,E(d))}catch{}}}const g=n.leaveParams?h:st(dr({path:h,params:d,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path;let m=l;if(n._includeValidateSearch&&this.options.search?.strict){const _={};p.forEach(E=>{if(E.options.validateSearch)try{Object.assign(_,Ht(E.options.validateSearch,{..._,...m}))}catch{}}),m=_}m=jl(m,i,p,n._includeValidateSearch),m=xe(l,m);const v=this.options.stringifySearch(m),S=i.hash===!0?o.hash:i.hash?We(i.hash,o.hash):void 0,C=S?`#${S}`:"";let w=i.state===!0?o.state:i.state?We(i.state,o.state):{};i.state&&(w=Fe(o.state,w));const b=`${g}${v}${C}`;let R,y,T=!1;if(this.rewrite){const _=new URL(b,this.origin),E=Yi(this.rewrite,_);R=_.href.replace(_.origin,""),E.origin!==this.origin?(y=E.href,T=!0):y=E.pathname+E.search+E.hash}else R=Za(b),y=R;return{publicHref:y,href:R,pathname:g,search:m,searchStr:v,state:w,hash:S??"",external:T,unmaskOnReload:i.unmaskOnReload}},r=s(n);if(n.mask)r.maskedLocation=s({from:n.from,...n.mask});else if(this.options.routeMasks){const i=sl(r.pathname,this.processedTree);if(i){const o=Object.assign(Object.create(null),i.rawParams),{from:a,params:u,...l}=i.route,c=Ir(u,o);r.maskedLocation=s({from:n.from,...l,params:c})}}return r},this.commitLocation=async({viewTransition:n,ignoreBlocker:s,...r})=>{let i;const o=me(this.latestLocation.href)===me(r.href)&&we(yr(r.state),yr(this.latestLocation.state)),a=this._commitPromise;let u;const l=new Promise(c=>{u=c});if(l.resolve=()=>{u(),a?.resolve()},this._commitPromise=l,o)this.load();else{let{maskedLocation:c,hashScrollIntoView:h,...d}=r;c&&(d={...c,state:{...c.state,__tempKey:void 0,__tempLocation:{...d,search:d.searchStr,state:{...d.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(d.unmaskOnReload??this.options.unmaskOnReload??!1)&&(d.state.__tempKey=this.tempLocationKey)),d.state.__hashScrollIntoViewOptions=h??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=n,i=r.replace?"REPLACE":"PUSH",this.history[i==="REPLACE"?"replace":"push"](d.publicHref,d.state,{ignoreBlocker:s}),this.history.subscribers.size||this.load({action:{type:i}})}return this._scroll.next=r.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:n,resetScroll:s,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:n,resetScroll:s,hashScrollIntoView:r,ignoreBlocker:o});return queueMicrotask(()=>{this._pendingLocation===u&&(this._pendingLocation=void 0)}),l},this.navigate=async({to:n,reloadDocument:s,href:r,publicHref:i,...o})=>{let a=!1;if(r)try{new URL(`${r}`),a=!0}catch{}if(a&&!s&&(s=!0),s){if(n!==void 0||!r){const l=this.buildLocation({to:n,...o});r=r??l.publicHref,i=i??l.publicHref}const u=!a&&i?i:r;if(Qt(u,this.protocolAllowlist))return;if(!o.ignoreBlocker){const l=this.history.getBlockers?.()??[];for(const c of l)if(c?.blockerFn&&await c.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:"PUSH"}))return}o.replace?window.location.replace(u):window.location.href=u;return}return this.buildAndCommitLocation({...o,href:r,to:n,_isNavigate:!0})},this.load=async n=>{this.updateLatestLocation(),n?.action&&(this._scroll.hash=n.action.type==="PUSH"||n.action.type==="REPLACE"),await Kl(this,n)},this.startViewTransition=n=>{const s=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,s&&typeof document.startViewTransition=="function"){let r;if(typeof s=="object"&&window.CSS?.supports?.("selector(:active-view-transition-type(a))")){const i=this.latestLocation,o=this.stores.resolvedLocation.get(),a=typeof s.types=="function"?s.types(rn(i,o)):s.types;if(a===!1)return n();r={update:n,types:a}}else r=n;return document.startViewTransition(r).updateCallbackDone}return n()},this.invalidate=n=>{const s=this._committed,r=n?.filter,i=this._preloads,o=new Set([...s,...this._cache.values(),...[...i?.values()??[]].flat(),...this._tx?.[3]??[]].filter(l=>!r||r(l)).map(l=>l.id)),a=[];for(const[l,c]of i??[])c.some(h=>o.has(h.id))&&(i.delete(l),a.push(l));const u=l=>{if(o.has(l.id)){const c=this.routesById[l.routeId],h={...l,invalid:!0,...(n?.forcePending||l.status==="error"||l.status==="notFound")&&Sr(c)?{status:"pending",error:void 0}:void 0};return l._flight=void 0,h}return l};this._committed=s.map(u);for(const[l,c]of this._cache)o.has(l)&&(c.invalid=!0,n?.forcePending&&(c.status="pending"));for(const l of o)this._flights?.delete(l);for(const l of a)l.abort();return this.shouldViewTransition=!1,this.load({sync:n?.sync})},this.resolveRedirect=n=>{const s=n.headers.get("Location");if(n.options.href){if(s)try{const r=new URL(s);if(this.origin&&r.origin===this.origin){const i=r.pathname+r.search+r.hash;n.options.href=i,n.headers.set("Location",i)}}catch{}}else{const r=this.buildLocation(n.options).publicHref||"/";n.options.href=r,n.headers.set("Location",r)}if(n.options.href&&Qt(n.options.href,this.protocolAllowlist))throw new Error("Redirect blocked: unsafe protocol");return n.headers.get("Location")||n.headers.set("Location",n.options.href),n},this.clearCache=n=>{const s=this._cache,r=this._preloads,i=n?.filter,o=[],a=[];for(const[l,c]of s)(!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)s.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=Qe,this.preloadRoute=n=>Ql(this,n),this.matchRoute=(n,s)=>{const r={...n,to:n.to?this.resolvePathWithBase(n.from||"",n.to):void 0,params:n.params||{},leaveParams:!0},i=this.buildLocation(r),o=this.stores.status.get()==="pending";if(s?.pending&&!o)return!1;const a=s?.pending??!o?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),u=rl(i.pathname,s?.caseSensitive??!1,s?.fuzzy??!1,a.pathname,this.processedTree);return!u||n.params&&!we(u.rawParams,n.params,{partial:!0})?!1:s?.includeSearch??!0?we(a.search,i.search,{partial:!0})?u.rawParams:!1:u.rawParams},this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??"fuzzy",stringifySearch:e.stringifySearch??El,parseSearch:e.parseSearch??wl,protocolAllowlist:e.protocolAllowlist??Ya}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;const s=this.options.notFoundRoute;s&&(s.init({originalIndex:99999999999}),this.routesById[s.id]=s)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=Ki(e),this.routeBranchCache.set(e,t)),t}matchRoutesInternal(e,t){const[n,s,r]=this.getMatchedRoutes(e.pathname);let i=n,o=!1;(r?r.path!=="/"&&s["**"]:me(e.pathname))&&(this.options.notFoundRoute?i=[...i,this.options.notFoundRoute]:o=!0);const a=o?Gl(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,m,v;{const k=p?.search??e.search,j=p?._strictSearch??void 0;try{const A=Ht(f.options.validateSearch,{...k})??void 0;g={...k,...A},m={...j,...A}}catch(A){let ae=A;if(A instanceof Yt||(ae=new Yt(A.message,{cause:A})),t?.throwOnError)throw ae;g=k,m={},v=ae}}let S="",C="";try{S=f.options.loaderDeps?.({search:g})??"",C=S&&JSON.stringify(S)||""}catch(k){if(t?.throwOnError)throw k;v??=k}const{interpolatedPath:w,usedParams:b}=dr({path:f.fullPath,params:s,decoder:this.pathParamsDecoder,server:this.isServer}),R=f.id+w+C,y=c(f,d),T=this._cache.get(R)??(y?.id===R?y:void 0);h=T?._strictParams??Object.assign(b,h);let _;if(!T)try{Rr(f,h)}catch(k){if(Je(k)||Xi(k)?_=k:_=new Dl(k.message,{cause:k}),t?.throwOnError)throw _}const E=y?"stay":"enter";let x;if(T)x={...T,cause:E,search:xe(y?y.search:T.search,g),_strictSearch:m,searchError:v};else{const k=Sr(f)?"pending":"success";x={id:R,ssr:f.options.ssr,index:d,routeId:f.id,params:y?.params??h,_strictParams:h,pathname:w,updatedAt:Date.now(),search:y?xe(y.search,g):g,_strictSearch:m,searchError:v,status:k,isFetching:!1,error:void 0,paramsError:_,context:{},abortController:t?._controller??new AbortController,cause:E,loaderDeps:y?Fe(y.loaderDeps,S):S,invalid:!1,preload:!1,staticData:f.options.staticData||{},fullPath:f.fullPath}}const N=a===f.id;x._notFound&&!N&&(x.error=void 0),x._notFound=N,u[d]=x}for(let d=0;d<u.length;d++){const f=u[d];f.params=f.cause==="stay"?xe(f.params,h):h,t?._controller&&(f.context={})}return u}matchRoutesLightweight(e){const t=gt(this.stores.ids.get()),n=t?this.stores.byRoute.get(t).get():void 0,s=n?.id,r=this.lightweightCache.get(e);if(r&&r[0]===s)return r[1];const[i,o]=this.getMatchedRoutes(e.pathname),a=gt(i),u={...e.search};for(const d of i)try{Object.assign(u,Ht(d.options.validateSearch,u))}catch{}const l=n&&n.routeId===a.id&&n.pathname===e.pathname;let c;if(l)c=n.params;else{const d=Object.assign(Object.create(null),o);for(const f of i)try{Rr(f,d)}catch{}c=d}const h=[i,a.fullPath,u,c];return this.lightweightCache.set(e,[s,h]),h}},Yt=class extends Error{},Dl=class extends Error{};function Ht(e,t){if(e==null)return{};if("~standard"in e){const n=e["~standard"].validate(t);if(n instanceof Promise)throw new Yt("Async validation not supported");if(n.issues)throw new Yt(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return"parse"in e?e.parse(t):typeof e=="function"?e(t):{}}function jl(e,t,n,s){const r=[];for(const o of n){const a=o.options;if("search"in a)a.search?.middlewares&&r.push(...a.search.middlewares);else if(a.preSearchFilters||a.postSearchFilters){const l=({search:c,next:h})=>{const d=h(a.preSearchFilters?a.preSearchFilters.reduce((f,p)=>p(f),c):c);return a.postSearchFilters?a.postSearchFilters.reduce((f,p)=>p(f),d):d};r.push(l)}const u=a.validateSearch;if(s&&u){const l=({search:c,next:h,meta:d})=>{const f=h(c);try{const p=Ht(u,f);if(d&&p)for(const g in p)g in f||(d.defaulted||=new Map).set(g,p[g]);return{...f,...p}}catch{}return f};r.push(l)}}const i=(o,a,u)=>{if(o>=r.length){if(!t.search)return{};if(t.search===!0)return a;const c=We(t.search,a);return u&&(u.explicit=c),c}const l=(c,h)=>{if(h){const d=u||{};return{search:i(o+1,c,d),meta:d}}return i(o+1,c,u)};return r[o]({search:a,next:l,meta:u})};return i(0,e)}function Gl(e,t){if(e!=="root"){let n;for(let s=t.length-1;s>=0;s--){const r=t[s];if(r.options.notFoundComponent)return r.id;n||=r.children&&r.id}if(n)return n}return ut}function Ir(e,t){if(e===!1||e===null)return Object.create(null);if((e??!0)===!0)return t;const n=Object.assign(Object.create(null),t);return Object.assign(n,We(e,n))}function Rr(e,t){const n=e.options.params?.parse??e.options.parseParams;n&&Object.assign(t,n(t))}function Wn(e,t){return e.options[t]?.preload?.()}function Ul(e,t){const n=Wn(e,"component");let s=Wn(e,"pendingComponent");return t&&(s?s=s.then(t):t()),n&&s?Promise.all([n,s]).then(()=>{}):n??s}function Qe(e,t,n){const s=()=>t===!1?void 0:t?Wn(e,t):Ul(e,n),r=e._lazy;if(r)return r===!0?s():r.then(s);if(!e.lazyFn)return s();const i=e.lazyFn().then(o=>{{const{id:a,...u}=o.options;Object.assign(e.options,u),e._lazy=!0}},o=>{throw e._lazy=void 0,o});return e._lazy=i,i.then(s)}function As(e){const t=e.findIndex(n=>n.status!=="success"||n._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var fe=0,Se=1,on=2,Z=3,Te=[4];function mt(e){return typeof e[0]=="number"}function Ue(e,t){return t.aborted?Promise.race([Promise.reject(t),e]):new Promise((n,s)=>{const r=()=>s(t);t.addEventListener("abort",r,{once:!0}),Promise.resolve(e).then(n,s).finally(()=>t.removeEventListener("abort",r))})}function $e(e,t){return e.routesById[t.routeId]}function vt(e,t,n){return Xi(e)?[Z,e]:Je(e)?(e.routeId||=n,[on,e]):t?(typeof e?.then=="function"&&(e=new Error("A Promise was thrown",{cause:e})),[Se,e]):[fe,e]}function Ms(e,t){let n=vt(t,!0,e.id);if(n[0]!==Se)return n;try{e.options.onError?.(n[1])}catch(s){n=vt(s,!0,e.id)}return n}function ct(e,t,n,s,r){return r[0].signal.aborted?Te:Ps(e,t,n,Ms(n,s),r)}async function $l(e,t,n,s,r,i){const[o,a]=t,u=n[0].signal,l=!!n[3];for(let c=n[6]??0;c<s;c++){const h=a[c],d=$e(e,h);h.abortController=n[0];const f=a[c-1]?.context??e.options.context??{},p={params:h.params,location:o,navigate:S=>e.navigate({...S,_fromLocation:o}),buildLocation:e.buildLocation,cause:l?"preload":h.cause,abortController:n[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 ve(e,h),[c,ct(e,t,d,S,n)]}if(u.aborted)return[c,Te];const g=h.paramsError??h.searchError;if(g!==void 0)return ve(e,h),[c,ct(e,t,d,g,n)];const m=d.options.beforeLoad;if(!m)continue;const v=h.status;c>=i&&(h.status="pending",n[7]?.());try{St(e,h,"beforeLoad",n[0]);const S=await Ue(m({...p,search:h.search,context:h.context,...e.options.additionalContext}),u);if(u.aborted)return[c,Te];const C=Ps(e,t,d,vt(S,!1,d.id),n);if(C[0]!==fe)return ve(e,h),[c,C];h.context={...h.context,...S}}catch(S){return ve(e,h),[c,ct(e,t,d,S,n)]}finally{h.status=v,St(e,h,!1,n[0])}}r()}function xs(e,t,n){if(!(!n||--n[2])){if(e._flights?.get(t.id)===n){const s=e._tx;if(s&&!s[0].signal.aborted&&!s[3].includes(t)&&s[3].some(r=>r.id===t.id)&&s[3].some(r=>r.isFetching==="beforeLoad"))return;e._flights.delete(t.id)}return n[1]}}function ve(e,t){const n=t._flight;t._flight=void 0,xs(e,t,n)?.abort()}function Q(e,t,n,s){const r=[];for(const i of t)if(!n?.includes(i)){const o=i._flight;if(i._flight=void 0,s&&o?.[2]===1&&e._flights?.get(i.id)===o&&n?.some(a=>a.id===i.id))o[2]=0;else{const a=xs(e,i,o);a&&r.push(a)}}for(const i of r)i.abort()}function Os(e){for(const t of e){const n=t._flight;n&&n[2]++}}function St(e,t,n,s){if(t.isFetching=n,s&&e._tx?.[0]!==s)return;const r=e.stores.byRoute.get(t.routeId),i=r?.get();i?.id===t.id&&r.set({...i,isFetching:n})}function Zi(e,t,n,s,r,i,o){const a=t[0];return{params:n.params,location:a,navigate:u=>e.navigate({...u,_fromLocation:a}),cause:o?"preload":n.cause,abortController:r,preload:o,deps:n.loaderDeps,parentMatchPromise:i,context:n.context,route:s,...e.options.additionalContext}}async function Cr(e,t,n,s,r,i,o){const a=o[0],u=a.signal;if(u.aborted)return Te;if(!r)return[fe,void 0];let l=n._flight;St(e,n,"loader",a);try{if(!l){const c=new AbortController;l=[Promise.resolve().then(()=>r(Zi(e,t,n,s,c,i,!!o[3]))).then(h=>vt(h,!1,s.id),h=>vt(h,!0,s.id)).then(h=>(h[0]!==fe&&e._flights?.get(n.id)===l&&(e._flights.delete(n.id),l[2]||c.abort()),h[0]===Se&&l[2]?Ms(s,h[1]):h)),c,1],(e._flights??=new Map).set(n.id,l)}return n._flight=l,n.abortController=l[1],Ps(e,t,s,await Ue(l[0],u),o)}catch(c){if(c!==u||!u.aborted)throw c;return ve(e,n),Te}finally{St(e,n,!1,a)}}function br(e,t,n){t[0]!==Z&&(e.status="success",e.error=void 0,t[0]===fe?(e.loaderData=t[1],e.invalid=!1,e.updatedAt=Date.now(),e.preload=n):e.invalid=!0)}function Bl(e,t,n){const s=e._cache.get(t.id);if(s!==n||e._committed.some(i=>i.id===t.id&&i._flight===t._flight))return;const r={...t,_notFound:void 0,context:{}};r._flight&&r._flight[2]++,e._cache.set(t.id,r),s&&ve(e,s)}function wr(e,t){return t[0]===Se||t[0]===on?{...e,status:t[0]===Se?"error":"notFound",error:t[1],_flight:void 0}:e}function Hl(e,t,n,s,r,i,o){const a=t[1][n],u=$e(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(Zi(e,t,a,u,i[0],r,l))),i[0].signal.aborted&&(f=Te)),!f)if(a.status!=="success")d=!0;else{const N=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>=N&&(i[5]||a.cause==="enter"||i[2].some(k=>k.routeId===a.routeId&&k.id!==a.id)))}}catch(N){a.invalid=!0,ve(e,a),f=ct(e,t,u,N,i)}const p=u.options.loader,g=typeof p=="function",m=g?p:p?.handler,v=!l||u.options.preload!==!1;let S=v&&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"),w=d&&v,b=w&&!C&&(a.status!=="success"||!!p),R=n>=o?i[7]:void 0,y=u.lazyFn&&u._lazy!==!0?R:void 0;if(w&&!p&&(a.invalid=!1,a.updatedAt=Date.now()),S&&S[2]++,b){const N=a._flight;a._flight=S,xs(e,a,N)?.abort(),n>=o&&(a.status="pending"),R?.()}w||(a.isFetching=!1);const T=(f?Promise.resolve(f):b?Cr(e,t,a,u,m,r,i):Promise.resolve([fe,a.loaderData])).then(N=>(b&&(br(a,N,l),N[0]===fe&&(p&&!i[0].signal.aborted&&Bl(e,a,c),n>=o&&(a.status="pending"))),N)),_=Ue(Promise.resolve().then(()=>Qe(u,void 0,y)),i[0].signal).then(()=>{},N=>t[1].some((k,j)=>j<=n&&(k.status==="error"||k.status==="notFound"||k._notFound))?void 0:[n,ct(e,t,u,N,i)]).then(N=>T.then(k=>(b&&!N&&k[0]===fe&&a.status==="pending"&&!i[0].signal.aborted&&(a.status="success",R?.()),N)));if(s.push([n,T,_]),!C)return T.then(N=>wr(a,N));const E={...a,status:"pending",preload:!1,_flight:S};a.invalid=!1,a.isFetching="loader";const x=Cr(e,t,E,u,m,r,i).then(N=>(a.isFetching=!1,br(E,N,!1),N));return(t[2]??=[]).push([n,x,_,E]),x.then(N=>wr(E,N))}async function Jn(e,t,n,s,r=0){const i=n?.[1][1];let o=i?.routeId?t.findIndex(a=>a.routeId===i.routeId):n?.[0]??t.length-1;o<0&&(o=0);for(let a=o;a>=0;a--){const u=$e(e,t[a]);try{const l=Qe(u,!1);l&&await Ue(l,s)}catch(l){if(l===s&&s.aborted)throw l}if(u.options.notFoundComponent)return a}return i?.routeId?o:r}function ke(e,t){t[2]&&(Q(e,t[2].map(n=>n[3])),t[2]=void 0)}async function Er(e,t,n,s){let r;try{await Promise.all(e.map(i=>i[1].then(async o=>{const a=i[0];if(!(s&&a>=await s)){if(o[0]>=Z)throw[a,o];!r&&o[0]!==fe&&(r=[a,o],await Promise.all((n??[]).map(u=>{if(!(u[0]<=a))return u[1].then(l=>{if(l[0]===Z)throw[u[0],l]})})))}})))}catch(i){return i}return t??r}function Ps(e,t,n,s,r,i){for(;s[0]===Z;){const o=s[1],a=o.options;if(a.reloadDocument?r[3]:r[1]>=20)return s;try{return a.href&&a.reloadDocument?(e.resolveRedirect(o),s):[Z,o,e.buildLocation({...a,_fromLocation:t[0],_includeValidateSearch:!0})]}catch(u){s=i?[Se,u]:Ms(n,u),i=!0}}return s}async function eo(e,t,n,s,r,i){const o=t[1];let a=await r,u=!1;const l=o.findIndex(f=>f._notFound),c=f=>f[1][0]===on?Jn(e,o,f,s.signal):f[0];let h=l<0?o.length:l;if((a?.[1][0]??0)>=Z)h=0;else if(a){h=a[2]??=await c(a);for(const f of n){if(f[0]>=h)break;const p=await f[1];if(p[0]!==fe&&p[0]<Z&&!("loaderData"in o[f[0]])){a=[f[0],p],h=a[2]=await c(a);break}}}for(const f of n){if(f[0]>=h)break;const p=await f[2];if(p){a=p;break}}if((a?.[1][0]??0)>=Z){const f=a[1];if(f[0]!==Z||f[1].options.reloadDocument||f[2])return ke(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],m=f?.[1],v=()=>{f&&(g._notFound=void 0,p===Se?g.status="error":(m.routeId=g.routeId,g.routeId===e.routeTree.id?(g.status="success",g._notFound=!0):g.status="notFound"),g.error=m,g.isFetching=!1)};v(),f||i?.();const S=$e(e,g);try{await Ue(f?Promise.resolve().then(()=>Qe(S,p===Se?"errorComponent":"notFoundComponent")):Promise.all([Qe(S),Qe(S,"notFoundComponent")]),s.signal)}catch(C){if(C===s.signal&&s.signal.aborted)return ke(e,t),Te}f?u&&(s.abort(),await Promise.all([...n.map(C=>C[1]),...n.map(C=>C[2]),...(t[2]??[]).map(C=>C[1])]),ke(e,t),Q(e,o),v()):g.status="success"}return t}async function to(e,t,n,s=0,r=t[1].length){const i=t[1];for(let o=s;o<r;o++){const a=i[o],u=$e(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 Ue(Promise.all([u.head?.(l),u.scripts?.(l)]),n);a.meta=c?.meta,a.links=c?.links,a.headScripts=c?.scripts,a.styles=c?.styles,a.scripts=h}catch(l){if(l===n&&n.aborted)break;console.error(l)}if(a.status!=="success"||a._notFound)break}return t}async function no(e,t,n,s){const r=[t,n],i=s[0].signal;let o;try{const a=e.stores.matches.get();let u=n.findIndex(v=>v._notFound);if(e.options.notFoundMode!=="root"&&u>=0){const v=await Jn(e,n,void 0,i,u);n[u]._notFound=void 0,n[v]._notFound=!0,u=v}let l=u<0?n.length:u+1,c=0;for(;c<l&&c!==u;){const v=n[c],S=s[2][c],C=a[c];if(S?.id!==v.id||S.status!=="success"||S._notFound||v.preload||C?.id!==v.id||C.status!=="success"||C._notFound)break;c++}const h=[],d=s[6]??0;let f=d?Promise.resolve(n[d-1]):void 0;const p=()=>{for(let v=d;v<l&&!i.aborted;v++)f=Hl(e,r,v,h,f,s,c)},g=await $l(e,r,s,l,p,c);if(g){if(s[4]=!0,l=g[0],g[1][0]===on){const v=await Jn(e,n,g,i);g[2]=v,l=Math.min(l,v+1)}else g[1][0]>=Z&&(l=0);p()}if(!i.aborted&&!s[3]){const v=[];for(const[S,C]of e._flights??[])C[2]||(e._flights.delete(S),v.push(C[1]));for(const S of v)S.abort()}const m=eo(e,r,h,s[0],Er(h,g,r[2]),s[7]);r[2]?.length&&(r[3]=Er(r[2],void 0,void 0,m.then(v=>mt(v)?0:As(n).length,()=>0))),o=await m}catch(a){if(ke(e,r),a===i&&i.aborted)return Te;throw a}return mt(o)?o:to(e,o,i,s[6]===n.length?s[6]:0)}function Xn(e,t){if(e._tx!==t)return;const n=t[3],s=e.stores.matches.get();let r=e._pending;for(let i=0;i<n.length;i++){const o=n[i],a=o.status==="success"&&!o._notFound,u=s[i]?.id===o.id&&s[i]?.status==="pending";if(a&&!u)continue;const l=$e(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 m=r[2]-Date.now();if(m>0){r[3]=setTimeout(()=>Xn(e,t),m);return}r[2]=0}const p=n.map(m=>({...m,_flight:void 0}));p[i].status="pending";const g=r[4]=e.startTransition(()=>e.stores.setMatches(p),p).then(m=>(m&&e._pending===r&&r[4]===g&&!r[2]&&(r[2]=Date.now()+d),m));return}}function rt(e,t){const n=e._pending;(e._tx===t||!e._tx?.[3].some(s=>s.id===n?.[1]))&&(clearTimeout(n?.[3]),e._pending=void 0)}async function Tr(e,t){const n=e._pending;if(!n)return;clearTimeout(n[3]);const s=n[2]-Date.now();if(!n[4]||s<=0||!As(t[3]).some(i=>i.id===n[1]))return;let r;try{await Ue(new Promise(i=>{r=setTimeout(i,s)}),t[0].signal)}catch{}clearTimeout(r)}function so(e,t){e._committed=t,e.stores.setMatches(t)}function zl(e,t,n,s){const r=e._committed,i=e._cache;for(const u of n)u.preload=!1,s&&(u._assetEnd=void 0);const o=As(n).length,a=new Map;{const u=Date.now();for(const l of[...r,...i.values()]){if(l.status!=="success"||n.some((h,d)=>h.id===l.id&&(d<o||h.status==="success")))continue;const c=$e(e,l);!c.options.loader||u-l.updatedAt>=(l.preload?c.options.preloadGcTime??e.options.defaultPreloadGcTime??3e5:c.options.gcTime??e.options.defaultGcTime??3e5)||a.set(l.id,i.get(l.id)===l?l:{...l,_flight:void 0,isFetching:!1,context:{}})}}t[3]=[],e._cache=a,so(e,n),Q(e,[...i.values(),...r],[...n,...a.values()]),kl(e,r,n,t)}async function xt(e,t){let n=e._tx;for(;n&&n!==t;){if(await n[5],e._tx===n)return;n=e._tx}}function ro(e,t,n){const s=n[1].options,r=n[2];if(!r)return e.navigate({...s,replace:!0,ignoreBlocker:!0});if(s.reloadDocument)return e.navigate({href:r.publicHref,reloadDocument:!0,replace:!0,ignoreBlocker:!0});r._redirects=t[1]+1,e._pendingLocation=r;const i=e.commitLocation({...r,viewTransition:s.viewTransition,replace:!0,resetScroll:s.resetScroll,hashScrollIntoView:s.hashScrollIntoView,ignoreBlocker:!0});return queueMicrotask(()=>{e._pendingLocation===r&&(e._pendingLocation=void 0)}),i}async function Vl(e,t,n,s,r){const i=n.map(u=>({...u}));Os(i);for(const u of s)ve(e,i[u[0]]),i[u[0]]=u[3];const o=[t[2],i];let a;try{a=await eo(e,o,s,t[0],r)}catch(u){throw Q(e,i),u}if(mt(a)){Q(e,i),a[0]===Z&&e._tx===t&&e._committed===n&&await ro(e,t,a);return}if(await to(e,a,t[0].signal),e._tx!==t||e._committed!==n){Q(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),ve(e,l))}so(e,i),Q(e,n,i)}async function ql(e,t,n,s,r,i){const o=await no(e,t[2],t[3],[t[0],t[1],e._committed,void 0,r,n,i,s]);if(mt(o)){const h=o[0]===Z&&e._tx===t;if((!h||o[1].options.reloadDocument)&&rt(e,t),Q(e,t[3]),t[3]=[],!h)return;if(e._tx!==t){rt(e,t);return}await ro(e,t,o);return}const a=o[1];if(e._tx===t&&await Tr(e,t),e._tx!==t){rt(e,t),Q(e,a),ke(e,o);return}const u=t[2],l=rn(u,e.stores.resolvedLocation.get()),c=o[2];await e.startViewTransition(async()=>{if(e._tx===t&&await Tr(e,t),e._tx!==t){rt(e,t),Q(e,a),ke(e,o);return}const h=()=>{rt(e,t),zl(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){ke(e,o);return}c?.length&&Vl(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 Kl(e,t){const n=e._tx,s=e.stores.resolvedLocation.get(),r=s??e.stores.location.get(),i=e.latestLocation,o=e._pendingLocation,a=o?.href===i.href?o._redirects??0:0,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 w=rn(i,s);e.emit({type:"onBeforeNavigate",...w}),c.signal.aborted||e.emit({type:"onBeforeLoad",...w})}if(c.signal.aborted){await xt(e,n);return}const d=r.href===i.href;let f=c;const p=e.matchRoutes(i,{_controller:c});Os(p);const g=l?u[1](p):void 0;if(g?f=l:l?.abort(),c.signal.aborted){Q(e,p),await xt(e,n);return}e._preflight=void 0;let m;const v=()=>ql(e,C,d,()=>Xn(e,C),t?.sync,g),S=t?.sync?new Promise(w=>m=w):Promise.resolve().then(v).then(),C=[f,a,i,p,Date.now(),S];if(e._tx=C,n){for(const w of e.stores.matches.get()){if(e._tx!==C)break;w.isFetching&&St(e,w,!1)}n[0].abort(),Q(e,n[3],C[3],!0)}if(e._tx!==C){Q(e,C[3]),C[3]=[],m?.(),await xt(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(w=>w._notFound))&&Xn(e,C),m?.(v()),await S,await xt(e,C)}async function Ql(e,t){let n=e.buildLocation(t);for(let s=0;;s++){const r=e._committed,i=new AbortController;let o,a,u;try{try{o=e.matchRoutes(n,{_controller:i}),Os(o),a=(e._preloads??=new Map).set(i,o),u=await no(e,n,o,[i,s,r,!0])}finally{a&&(a=a.delete(i),Q(e,o)),i.abort()}if(!mt(u))return u[1];if(!a||u.length<3)return;n=u[2]}catch(l){Je(l)||console.error(l);return}}}var Wl="Error preloading route! ☝️",io=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=t=>{this.originalIndex=t.originalIndex;const n=this.options,s=!n?.path&&!n?.id;this.parentRoute=this.options.getParentRoute?.(),s?this._path=ut:this.parentRoute||Es();let r=s?ut:n?.path;r&&r!=="/"&&(r=Qi(r));const i=n?.id||r;let o=s?ut:Ut([this.parentRoute.id==="__root__"?"":this.parentRoute.id,i]);r==="__root__"&&(r="/"),o!=="__root__"&&(o=Ut(["/",o]));const a=o==="__root__"?"/":Ut([this.parentRoute.fullPath,r]);this._path=r,this._id=o,this._fullPath=a,this._to=me(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=>Al({from:this.fullPath,...t}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw new Error("Route cannot have both an 'id' and a 'path' option.")}},Jl=class extends io{constructor(e){super(e)}},Ls=class extends I.Component{constructor(...e){super(...e),this.state={error:null},this.reset=()=>{this.setState({error:null})}}static getDerivedStateFromProps(e,t){const n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){const e=this.state.error;return e?I.createElement(this.props.errorComponent??Xl,{error:e,reset:this.reset}):this.props.children}};function Xl({error:e}){const[t,n]=I.useState(!1);return(0,F.jsxs)("div",{style:{padding:".5rem",maxWidth:"100%"},children:[(0,F.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:".5rem"},children:[(0,F.jsx)("strong",{style:{fontSize:"1rem"},children:"Something went wrong!"}),(0,F.jsx)("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:()=>n(s=>!s),children:t?"Hide Error":"Show Error"})]}),(0,F.jsx)("div",{style:{height:".25rem"}}),t?(0,F.jsx)("div",{children:(0,F.jsx)("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"},children:e.message?(0,F.jsx)("code",{children:e.message}):null})}):null]})}function Yl({children:e,fallback:t=null}){return(0,F.jsx)(I.Fragment,{children:oo()?e:t})}function oo(){return I.useSyncExternalStore(Zl,()=>!0,()=>!1)}function Zl(){return()=>{}}var ao=I.createContext(null);function se(e){return I.useContext(ao)}var an=I.createContext(void 0),eu=I.createContext(void 0),G=(e=>(e[e.None=0]="None",e[e.Mutable=1]="Mutable",e[e.Watching=2]="Watching",e[e.RecursedCheck=4]="RecursedCheck",e[e.Recursed=8]="Recursed",e[e.Dirty=16]="Dirty",e[e.Pending=32]="Pending",e))(G||{});function tu({update:e,notify:t,unwatched:n}){return{link:s,unlink:r,propagate:i,checkDirty:o,shallowPropagate:a};function s(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&&n(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 m=p.subs;m.nextSub!==void 0&&a(m),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 m=l.nextDep;if(m!==void 0){l=m;continue}}for(;d--;){const m=c.subs,v=m.nextSub!==void 0;if(v?(l=h.value,h=h.prev):l=m,f){if(e(c)){v&&a(m),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 nu(e,t,n){const s=typeof e=="object",r=s?e:void 0;return{next:(s?e.next:e)?.bind(r),error:(s?e.error:t)?.bind(r),complete:(s?e.complete:n)?.bind(r)}}var Yn=[],zt=0,{link:_r,unlink:su,propagate:ru,checkDirty:lo,shallowPropagate:Ar}=tu({update(e){return e._update()},notify(e){Yn[Zn++]=e,e.flags&=~G.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=G.Mutable|G.Dirty,Zt(e))}}),Ot=0,Zn=0,he,es=0;function iu(e){try{++es,e()}finally{--es||uo()}}function Zt(e){const t=e.depsTail;let n=t!==void 0?t.nextDep:e.deps;for(;n!==void 0;)n=su(n,e)}function uo(){if(!(es>0)){for(;Ot<Zn;){const e=Yn[Ot];Yn[Ot++]=void 0,e.notify()}Ot=0,Zn=0}}function Mr(e,t){const n=typeof e=="function",s=e,r={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?G.None:G.Mutable,get(){return he!==void 0&&_r(r,he,zt),r._snapshot},subscribe(i){const o=nu(i),a={current:!1},u=ou(()=>{r.get(),a.current?o.next?.(r._snapshot):a.current=!0});return{unsubscribe:()=>{u.stop()}}},_update(i){const o=he,a=t?.compare??Object.is;if(n)he=r,++zt,r.depsTail=void 0;else if(i===void 0)return!1;n&&(r.flags=G.Mutable|G.RecursedCheck);try{const u=r._snapshot,l=typeof i=="function"?i(u):i===void 0&&n?s(u):i;return u===void 0||!a(u,l)?(r._snapshot=l,!0):!1}finally{he=o,n&&(r.flags&=~G.RecursedCheck),Zt(r)}}};return n?(r.flags=G.Mutable|G.Dirty,r.get=function(){const i=r.flags;if(i&G.Dirty||i&G.Pending&&lo(r.deps,r)){if(r._update()){const o=r.subs;o!==void 0&&Ar(o)}}else i&G.Pending&&(r.flags=i&~G.Pending);return he!==void 0&&_r(r,he,zt),r._snapshot}):r.set=function(i){if(r._update(i)){const o=r.subs;o!==void 0&&(ru(o),Ar(o),uo())}},r}function ou(e){const t=()=>{const s=he;he=n,++zt,n.depsTail=void 0,n.flags=G.Watching|G.RecursedCheck;try{return e()}finally{he=s,n.flags&=~G.RecursedCheck,Zt(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:G.Watching|G.RecursedCheck,notify(){const s=this.flags;s&G.Dirty||s&G.Pending&&lo(this.deps,this)?t():this.flags=G.Watching},stop(){this.flags=G.None,this.depsTail=void 0,Zt(this)}};return t(),n}var au=Xe((e=>{var t=Ss();function n(d,f){return d===f&&(d!==0||1/d===1/f)||d!==d&&f!==f}var s=typeof Object.is=="function"?Object.is:n,r=t.useState,i=t.useEffect,o=t.useLayoutEffect,a=t.useDebugValue;function u(d,f){var p=f(),g=r({inst:{value:p,getSnapshot:f}}),m=g[0].inst,v=g[1];return o(function(){m.value=p,m.getSnapshot=f,l(m)&&v({inst:m})},[d,p,f]),i(function(){return l(m)&&v({inst:m}),d(function(){l(m)&&v({inst:m})})},[d]),a(p),p}function l(d){var f=d.getSnapshot;d=d.value;try{var p=f();return!s(d,p)}catch{return!0}}function c(d,f){return f()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:u;e.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:h})),lu=Xe(((e,t)=>{t.exports=au()})),uu=Xe((e=>{var t=Ss(),n=lu();function s(c,h){return c===h&&(c!==0||1/c===1/h)||c!==c&&h!==h}var r=typeof Object.is=="function"?Object.is:s,i=n.useSyncExternalStore,o=t.useRef,a=t.useEffect,u=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(c,h,d,f,p){var g=o(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=u(function(){function S(y){if(!C){if(C=!0,w=y,y=f(y),p!==void 0&&m.hasValue){var T=m.value;if(p(T,y))return b=T}return b=y}if(T=b,r(w,y))return T;var _=f(y);return p!==void 0&&p(T,_)?(w=y,T):(w=y,b=_)}var C=!1,w,b,R=d===void 0?null:d;return[function(){return S(h())},R===null?void 0:function(){return S(R())}]},[h,d,f,p]);var v=i(c,g[0],g[1]);return a(function(){m.hasValue=!0,m.value=v},[v]),l(v),v}})),cu=Xe(((e,t)=>{t.exports=uu()})),du=cu();function hu(e,t){return e===t}function ye(e,t,n=hu){const s=(0,I.useCallback)(i=>{if(!e)return()=>{};const{unsubscribe:o}=e.subscribe(i);return o},[e]),r=(0,I.useCallback)(()=>e?.get(),[e]);return(0,du.useSyncExternalStoreWithSelector)(s,r,r,t,n)}var xr={};function co(e,t){const n=I.useRef();return s=>{const r=e?.select?e.select(s):s;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=Fe(n.current,r):r}}function Be(e){const t=se(),n=I.useContext(e.from?eu:an),s=e.from??n,r=t.stores.getMatchStore(s),i=co(e,t),o=ye(r,a=>a?i(a):xr);if(o!==xr)return o;(e.shouldThrow??!0)&&Es()}function ho(e){return Be({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function fo(e){const{select:t,...n}=e;return Be({...n,select:s=>t?t(s.loaderDeps):s.loaderDeps})}function po(e){return Be({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function go(e){return Be({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function Fs(e){const t=se();return I.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function Mf(e){const t=se(),n=Fs(),s=I.useRef(null);return ws(()=>{s.current!==e&&(n(e),s.current=e)},[t,e,n]),null}function mo(e){return Be({...e,select:t=>e.select?e.select(t.context):t.context})}function Rn(e){const t=I.useRef(e);return we(t.current,e,{ignoreUndefined:!1})||(t.current=e),t.current}function fu(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function pu(e,t,n){if(e?.external)return Qt(e.href,n)?void 0:e.href;if(!Ru(t)&&!(typeof t!="string"||t.indexOf(":")===-1))try{return new URL(t),Qt(t,n)?void 0:t}catch{}}function gu(e,t,n,s,r,i){if(i)return!1;if(n?.exact){if(!dl(e.pathname,t.pathname,s))return!1}else{const o=Jt(e.pathname,s),a=Jt(t.pathname,s);if(!(o.startsWith(a)&&(o.length===a.length||o[a.length]==="/")))return!1}return(n?.includeSearch??!0)&&!we(e.search,t.search,{partial:!n?.exact,ignoreUndefined:!n?.explicitUndefined})?!1:n?.includeHash?r&&e.hash===t.hash:!0}function mu(e,t){const n=se(),s=qa(t),{activeProps:r,inactiveProps:i,activeOptions:o,to:a,preload:u,preloadDelay:l,preloadIntentProximity:c,hashScrollIntoView:h,replace:d,startTransition:f,resetScroll:p,viewTransition:g,children:m,target:v,disabled:S,style:C,className:w,onClick:b,onBlur:R,onFocus:y,onMouseEnter:T,onMouseLeave:_,onTouchStart:E,ignoreBlocker:x,params:N,search:k,hash:j,state:A,mask:ae,reloadDocument:Hs,unsafeRelative:zs,from:Vs,_fromLocation:qs,...Rt}=e,Ct=oo(),fn=Rn(e.search),pn=Rn(e.params),bt=Rn(o),Me=I.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,fn,pn,e.state,e.mask,e.unsafeRelative]),gn=I.useCallback(M=>{const U=n.buildLocation({_fromLocation:M,...Me}),ue=Iu(U.maskedLocation?U.maskedLocation.publicHref:U.publicHref,U.maskedLocation?U.maskedLocation.external:U.external,n.history,S),vn=pu(ue,a,n.protocolAllowlist);return[ue?.href,vn,gu(M,U,bt,n.basepath,Ct,vn!==void 0)]},[bt,S,Ct,Me,n,a]),[mn,Ze,et]=ye(n.stores.location,gn,fu),re=et?We(r,{})??vu:Cn,W=et?Cn:We(i,{})??Cn,wt=[w,re.className,W.className].filter(Boolean).join(" "),Et=(C||re.style||W.style)&&{...C,...re.style,...W.style},D=I.useRef(!1),O=e.reloadDocument||Ze||S?!1:u??n.options.defaultPreload,le=l??n.options.defaultPreloadDelay??0,J=I.useCallback(()=>{n.preloadRoute(Me).catch(M=>{console.warn(M),console.warn(Wl)})},[n,Me]),Ie=I.useCallback(M=>{if(!M){bn(s);return}if(!(M.isIntersecting??O==="intent")){M.isIntersecting===!1&&bn(s);return}if(!le){J();return}dt.has(s)||dt.set(s,setTimeout(()=>{dt.delete(s),J()},le))},[J,s,O,le]);Va(s,Ie,O!=="viewport"),I.useEffect(()=>{D.current||O==="render"&&(J(),D.current=!0)},[J,O]);const tt=M=>{const U=M.currentTarget.getAttribute("target"),ue=v!==void 0?v:U;!S&&!(M.metaKey||M.altKey||M.ctrlKey||M.shiftKey)&&!M.defaultPrevented&&(!ue||ue==="_self")&&M.button===0&&(M.preventDefault(),n.navigate({...Me,replace:d,resetScroll:p,hashScrollIntoView:h,startTransition:f,viewTransition:g,ignoreBlocker:x}))};if(Ze)return{...Rt,ref:s,href:Ze,...m&&{children:m},...v&&{target:v},...S&&{disabled:S},...C&&{style:C},...w&&{className:w},...b&&{onClick:b},...R&&{onBlur:R},...y&&{onFocus:y},...T&&{onMouseEnter:T},..._&&{onMouseLeave:_},...E&&{onTouchStart:E}};const z=()=>{O==="intent"&&J()},nt=()=>{O==="intent"&&bn(s)};return{...Rt,...re,...W,href:mn,ref:s,onClick:He([b,tt]),onBlur:He([R,nt]),onFocus:He([y,Ie]),onMouseEnter:He([T,Ie]),onMouseLeave:He([_,nt]),onTouchStart:He([E,z]),disabled:!!S,target:v,...Et&&{style:Et},...wt&&{className:wt},...S&&Su,...et&&yu}}var Cn={},vu={className:"active"},Su={role:"link","aria-disabled":!0},yu={"data-status":"active","aria-current":"page"},dt=new WeakMap,bn=e=>{clearTimeout(dt.get(e)),dt.delete(e)},He=e=>t=>{for(const n of e)if(n){if(t.defaultPrevented)return;n(t)}};function Iu(e,t,n,s){if(!s)return t?{href:e,external:!0}:{href:n.createHref(e)||"/",external:!1}}function Ru(e){if(typeof e!="string")return!1;const t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var vo=I.forwardRef((e,t)=>{const{_asChild:n,...s}=e,{type:r,...i}=mu(s,t),o=typeof s.children=="function"?s.children({isActive:i["data-status"]==="active"}):s.children;if(!n){const{disabled:a,...u}=i;return I.createElement("a",u,o)}return I.createElement(n,i,o)}),Cu=class extends io{constructor(e){super(e),this.useMatch=t=>Be({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>mo({...t,from:this.id}),this.useSearch=t=>go({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>po({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>fo({...t,from:this.id}),this.useLoaderData=t=>ho({...t,from:this.id}),this.useNavigate=()=>Fs({from:this.fullPath}),this.Link=I.forwardRef((t,n)=>(0,F.jsx)(vo,{ref:n,from:this.fullPath,...t}))}};function bu(e){return new Cu(e)}var wu=class extends Jl{constructor(e){super(e),this.useMatch=t=>Be({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>mo({...t,from:this.id}),this.useSearch=t=>go({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>po({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>fo({...t,from:this.id}),this.useLoaderData=t=>ho({...t,from:this.id}),this.useNavigate=()=>Fs({from:this.fullPath}),this.Link=I.forwardRef((t,n)=>(0,F.jsx)(vo,{ref:n,from:this.fullPath,...t}))}};function xf(e){return new wu(e)}function Of(e){return t=>{const n=bu(t);return n.isRoot=!1,n}}function Pf(e,t){let n,s,r;const i=()=>(n||(r=void 0,n=e().then(a=>{n=void 0,o.preload=void 0,s=a[t??"default"]}).catch(a=>{n=void 0,r=a})),n),o=function(u){if(r){if(Wa(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(!s)if(ir)ir(i());else throw i();return I.createElement(s,u)};return o.preload=i,o}function Eu(e){const t=se(),n=`not-found-${ye(t.stores.location,s=>s.pathname)}-${ye(t.stores.status,s=>s)}`;return(0,F.jsx)(Ls,{getResetKey:()=>n,onCatch:(s,r)=>{if(Je(s))e.onCatch?.(s,r);else throw s},errorComponent:({error:s})=>{if(Je(s))return e.fallback?.(s);throw s},children:e.children})}function Tu(){return(0,F.jsx)("p",{children:"Not Found"})}function qe(e){return(0,F.jsx)(F.Fragment,{children:e.children})}function So(e,t,n){return t.options.notFoundComponent?(0,F.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,F.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,F.jsx)(Tu,{})}function ln(e,t){const n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,F.jsx)(n,{}):null}var _u=(e,t)=>e[0]===t[0]&&e[1]===t[1],yo=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n==="data-only"||!e.ssr,Io=I.memo(function({routeId:t}){const n=se();return(0,F.jsx)(Au,{router:n,match:ye(n.stores.getMatchStore(t),s=>s)})});function Au({router:e,match:t}){const n=e.routesById[t.routeId],s=ln(e,n),r=n.options.errorComponent??e.options.defaultErrorComponent,i=n.options.onCatch??e.options.defaultOnCatch,o=n.isRoot?n.options.notFoundComponent??e.options.notFoundRoute?.options.component:n.options.notFoundComponent,a=t.ssr===!1||t.ssr==="data-only",u=yo(e,n,t.ssr)&&(n.options.wrapInSuspense??s??(n.options.errorComponent?.preload||a))?I.Suspense:qe,l=r?Ls:qe,c=o?Eu:qe;return(0,F.jsxs)(n.isRoot?n.options.shellComponent??qe:qe,{children:[(0,F.jsx)(an.Provider,{value:t.routeId,children:(0,F.jsx)(u,{fallback:s,children:(0,F.jsx)(l,{getResetKey:()=>t,errorComponent:r,onCatch:(h,d)=>{if(Je(h))throw h.routeId??=t.routeId,h;i?.(h,d)},children:(0,F.jsx)(c,{fallback:h=>{if(h.routeId??=t.routeId,h.routeId!==t.routeId)throw h;return I.createElement(o,h)},children:a?(0,F.jsx)(Yl,{fallback:s,children:(0,F.jsx)(Or,{match:t})}):(0,F.jsx)(Or,{match:t})})})})}),null]})}var Or=I.memo(function({match:t}){const n=se(),s=t.routeId,r=n.routesById[s],i=I.useMemo(()=>{const a=(r.options.remountDeps??n.options.defaultRemountDeps)?.({routeId:s,loaderDeps:t.loaderDeps,params:t._strictParams,search:t._strictSearch});return a?JSON.stringify(a):void 0},[s,t.loaderDeps,t._strictParams,t._strictSearch,r.options.remountDeps,n.options.defaultRemountDeps]),o=I.useMemo(()=>{const a=r.options.component??n.options.defaultComponent;return a?(0,F.jsx)(a,{},i):(0,F.jsx)(Mu,{})},[i,r.options.component,n.options.defaultComponent]);if(t.status==="pending"){if(n.ssr&&!yo(n,r,t.ssr))return o;if(n._tx)throw n._tx[5];return ln(n,r)}if(t.status==="notFound")return So(n,r,t.error);if(t.status==="error")throw t.error;return o}),Mu=I.memo(function(){const t=se(),n=I.useContext(an);let s,r,i;{const a=t.stores.getMatchStore(n);[s,r]=ye(a,u=>[!!u._notFound,u.error],_u),i=ye(t.stores.ids,u=>u[u.indexOf(n)+1])}if(s)return So(t,t.routesById[n],r);if(!i)return null;const o=(0,F.jsx)(Io,{routeId:i});return n==="__root__"?(0,F.jsx)(I.Suspense,{fallback:ln(t),children:o}):o});function Ro(e,t){const n=e[1];e.length=0,n?.(t)}function xu({t:e}){const t=se(),n=t._rendered??=[];return t.startTransition=(s,r)=>new Promise(i=>{Ro(n,!1),n.push(r,i),e(t),I.startTransition(s)}),ws(()=>{const s=t.history.subscribe(t.load);t.updateLatestLocation();const r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(me(r.publicHref)!==me(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),s;const o=t.stores.resolvedLocation.get();return o?.href===r.href&&o.state.__TSR_key===r.state.__TSR_key?n.push(t.stores.matches.get(),a=>{a&&t.emit({type:"onRendered",...rn(o,o)})}):t._tx||t.load({sync:!0}).catch(console.error),s},[t,t.history]),null}function Ou(){const e=se(),t=e.routesById[ut],n=ln(e,t),s=e.ssr?qe:I.Suspense,r=(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(xu,{t:I.useState()[1]}),(0,F.jsx)(s,{fallback:n,children:(0,F.jsx)(Pu,{})})]});return e.options.InnerWrap?(0,F.jsx)(e.options.InnerWrap,{children:r}):r}function Pu(){const e=se(),t=e._rendered,n=ye(e.stores.matches,o=>t[0]??o),s=n[0],r=s?.routeId;ws(()=>{t[0]===n&&Ro(t,!0)},[t,n]);const i=r?(0,F.jsx)(Io,{routeId:r}):null;return(0,F.jsx)(an.Provider,{value:r,children:e.options.disableGlobalCatchBoundary?i:(0,F.jsx)(Ls,{getResetKey:()=>s,onCatch:void 0,children:i})})}var Lu=e=>({createMutableStore:Mr,createReadonlyStore:Mr,batch:iu}),Lf=e=>new Fu(e),Fu=class extends Nl{constructor(e){super(e,Lu)}};function ku({router:e,children:t,...n}){Bi(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});const s=(0,F.jsx)(ao.Provider,{value:e,children:t});return e.options.Wrap?(0,F.jsx)(e.options.Wrap,{children:s}):s}function Ff({router:e,...t}){return(0,F.jsx)(ku,{router:e,...t,children:(0,F.jsx)(Ou,{})})}function kf(e){const t=se();return ye(t.stores.location,co(e,t))}function Ce(e,t){return typeof e=="function"?e(t):e}function ee(e,t){return n=>{t.setState(s=>({...s,[e]:Ce(n,s[e])}))}}function un(e){return e instanceof Function}function Nu(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Du(e,t){const n=[],s=r=>{r.forEach(i=>{n.push(i);const o=t(i);o!=null&&o.length&&s(o)})};return s(e),n}function P(e,t,n){let s=[],r;return i=>{let o;n.key&&n.debug&&(o=Date.now());const a=e(i);if(!(a.length!==s.length||a.some((l,c)=>s[c]!==l)))return r;s=a;let u;if(n.key&&n.debug&&(u=Date.now()),r=t(...a),n==null||n.onChange==null||n.onChange(r),n.key&&n.debug&&n!=null&&n.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`,`
|
|
1
|
+
import{r as Oi,t as Ze}from"./rolldown-runtime-CXHxssQy.js";import{ut as Cs}from"./icons-CtpwLWUI.js";import{Ot as ha,kt as fa}from"./radix-ui-CgJOuzDv.js";var et=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 et{#t;#e;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},bs=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)}},Fe=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 Vn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Pi(e,t){return Math.max(e+(t||0)-Date.now(),0)}function we(e,t){return typeof e=="function"?e(t):e}function X(e,t){return typeof e=="function"?e(t):e}function er(e,t){const{type:n="all",exact:s,fetchStatus:r,predicate:i,queryKey:o,stale:a}=e;if(o){if(s){if(t.queryHash!==ws(o,t.options))return!1}else if(!gt(t.queryKey,o))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||r&&r!==t.state.fetchStatus||i&&!i(t))}function tr(e,t){const{exact:n,status:s,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ge(t.options.mutationKey)!==Ge(i))return!1}else if(!gt(t.options.mutationKey,i))return!1}return!(s&&t.state.status!==s||r&&!r(t))}function ws(e,t){return(t?.queryKeyHashFn||Ge)(e)}function Ge(e){return JSON.stringify(e,(t,n)=>qn(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function gt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>gt(e[n],t[n])):!1}var Ia=Object.prototype.hasOwnProperty;function ki(e,t,n=0){if(e===t)return e;if(n>500)return t;const s=nr(e)&&nr(t);if(!s&&!(qn(e)&&qn(t)))return t;const r=(s?e:Object.keys(e)).length,i=s?t:Object.keys(t),o=i.length,a=s?new Array(o):{};let u=0;for(let l=0;l<o;l++){const c=s?l:i[l],h=e[c],d=t[c];if(h===d){a[c]=h,(s?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=ki(h,d,n+1);a[c]=f,f===h&&u++}return r===o&&u===r?e:a}function Wt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function nr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function qn(e){if(!sr(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!sr(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function sr(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ra(e){return new Promise(t=>{Fe.setTimeout(t,e)})}function Kn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?ki(e,t):t}function Ca(e,t,n=0){const s=[...e,t];return n&&s.length>n?s.slice(1):s}function ba(e,t,n=0){const s=[t,...e];return n&&s.length>n?s.slice(0,-1):s}var Es=Symbol();function Li(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Es?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Ts(e,t){return typeof e=="function"?e(...t):!!e}function wa(e,t,n){let s=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),s||(s=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),e}var mt=(()=>{let e=()=>Sa;return{isServer(){return e()},setIsServer(t){e=t}}})();function Qn(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),e(r)},n.reject=r=>{s({status:"rejected",reason:r}),t(r)},n}function Pf(e){return e.state.status==="success"}var Ea=va;function Ta(){let e=[],t=0,n=a=>{a()},s=a=>{a()},r=Ea;const i=a=>{t?e.push(a):r(()=>{n(a)})},o=()=>{const a=e;e=[],a.length&&r(()=>{s(()=>{a.forEach(u=>{n(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=>{n=a},setBatchNotifyFunction:a=>{s=a},setScheduler:a=>{r=a}}}var H=Ta(),_a=class extends et{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#t}},Jt=new _a;function Aa(e){return Math.min(1e3*2**e,3e4)}function Fi(e){return(e??"online")==="online"?Jt.isOnline():!0}var Wn=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Ni(e){let t=!1,n=0,s;const r=Qn(),i=()=>r.status!=="pending",o=g=>{if(!i()){const m=new Wn(g);d(m),e.onCancel?.(m)}},a=()=>{t=!0},u=()=>{t=!1},l=()=>bs.isFocused()&&(e.networkMode==="always"||Jt.isOnline())&&e.canRun(),c=()=>Fi(e.networkMode)&&e.canRun(),h=g=>{i()||(s?.(),r.resolve(g))},d=g=>{i()||(s?.(),r.reject(g))},f=()=>new Promise(g=>{s=m=>{(i()||l())&&g(m)},e.onPause?.()}).then(()=>{s=void 0,i()||e.onContinue?.()}),p=()=>{if(i())return;let g;const m=n===0?e.initialPromise:void 0;try{g=m??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(h).catch(v=>{if(i())return;const S=e.retry??(mt.isServer()?0:3),C=e.retryDelay??Aa,w=typeof C=="function"?C(n,v):C,b=S===!0||typeof S=="number"&&n<S||typeof S=="function"&&S(n,v);if(t||!b){d(v);return}n++,e.onFail?.(n,v),Ra(w).then(()=>l()?void 0:f()).then(()=>{t?d(v):p()})})};return{promise:r,status:()=>r.status,cancel:o,continue:()=>(s?.(),r),cancelRetry:a,continueRetry:u,canStart:c,start:()=>(c()?p():f().then(p),r)}}var Di=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Vn(this.gcTime)&&(this.#t=Fe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(mt.isServer()?1/0:3e5))}clearGcTimeout(){this.#t!==void 0&&(Fe.clearTimeout(this.#t),this.#t=void 0)}};function Ma(e){return{onFetch:(t,n)=>{const s=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},u=0;const l=async()=>{let c=!1;const h=p=>{wa(p,()=>t.signal,()=>c=!0)},d=Li(t.options,t.fetchOptions),f=async(p,g,m)=>{if(c)return Promise.reject(t.signal.reason);if(g==null&&p.pages.length)return Promise.resolve(p);const S=(()=>{const R={client:t.client,queryKey:t.queryKey,pageParam:g,direction:m?"backward":"forward",meta:t.options.meta};return h(R),R})(),C=await d(S),{maxPages:w}=t.options,b=m?ba:Ca;return{pages:b(p.pages,C,w),pageParams:b(p.pageParams,g,w)}};if(r&&i.length){const p=r==="backward",g=p?ji:Jn,m={pages:i,pageParams:o};a=await f(m,g(s,m),p)}else{const p=e??i.length;do{const g=u===0?o[0]??s.initialPageParam:Jn(s,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},n):t.fetchFn=l}}}function Jn(e,{pages:t,pageParams:n}){const s=t.length-1;return t.length>0?e.getNextPageParam(t[s],t,n[s],n):void 0}function ji(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function xa(e,t){return t?Jn(e,t)!=null:!1}function Oa(e,t){return!t||!e.getPreviousPageParam?!1:ji(e,t)!=null}var Pa=class extends Di{#t;#e;#n;#s;#i;#r;#a;#l;constructor(e){super(),this.#l=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#s=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=ir(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=ir(this.options);t.data!==void 0&&(this.setState(rr(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const n=Kn(this.state.data,e,this.options);return this.#o({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#o({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#e}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>X(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Es||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>we(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:!Pi(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#l||this.#h()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#o({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const a=this.observers.find(u=>u.options.queryFn);a&&this.setOptions(a.options)}const n=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(this.#l=!0,n.signal)})},r=()=>{const a=Li(this.options,t),l=(()=>{const c={client:this.#i,queryKey:this.queryKey,meta:this.meta};return s(c),c})();return this.#l=!1,this.options.persister?this.options.persister(a,l,this):a(l)},o=(()=>{const a={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:r};return s(a),a})();(this.#t==="infinite"?Ma(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#o({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=Ni({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:a=>{a instanceof Wn&&a.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.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.#s.config.onSuccess?.(a,this),this.#s.config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof Wn){if(a.silent)return this.#r.promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw this.#o({type:"error",error:a}),this.#s.config.onError?.(a,this),this.#s.config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}#o(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Gi(n.data,this.options),fetchMeta:e.meta??null};case"success":const s={...n,...rr(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?s:void 0,s;case"error":const r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),H.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function Gi(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Fi(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function rr(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function ir(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,s=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var $i=class extends et{constructor(e,t){super(),this.options=t,this.#t=e,this.#l=null,this.#a=Qn(),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#s=void 0;#i;#r;#a;#l;#h;#o;#u;#f;#d;#p;#g=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),or(this.#e,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Xn(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Xn(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#I(),this.#R(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(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&&!Wt(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const s=this.hasListeners();s&&ar(this.#e,n,this.options,t)&&this.#m(),this.updateResult(),s&&(this.#e!==n||X(this.options.enabled,this.#e)!==X(t.enabled,this.#e)||we(this.options.staleTime,this.#e)!==we(t.staleTime,this.#e))&&this.#c();const r=this.#v();s&&(this.#e!==n||X(this.options.enabled,this.#e)!==X(t.enabled,this.#e)||r!==this.#p)&&this.#S(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return La(this,n)&&(this.#s=n,this.#r=this.options,this.#i=this.#e.state),n}getCurrentResult(){return this.#s}trackResult(e,t){return new Proxy(e,{get:(n,s)=>(this.trackProp(s),t?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#a.status==="pending"&&this.#a.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,s))})}trackProp(e){this.#g.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#m(e){this.#C();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(q)),t}#c(){this.#I();const e=we(this.options.staleTime,this.#e);if(mt.isServer()||this.#s.isStale||!Vn(e))return;const t=Pi(this.#s.dataUpdatedAt,e)+1;this.#f=Fe.setTimeout(()=>{this.#s.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#S(e){this.#R(),this.#p=e,!(mt.isServer()||X(this.options.enabled,this.#e)===!1||!Vn(this.#p)||this.#p===0)&&(this.#d=Fe.setInterval(()=>{(this.options.refetchIntervalInBackground||bs.isFocused())&&this.#m()},this.#p))}#y(){this.#c(),this.#S(this.#v())}#I(){this.#f!==void 0&&(Fe.clearTimeout(this.#f),this.#f=void 0)}#R(){this.#d!==void 0&&(Fe.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,s=this.options,r=this.#s,i=this.#i,o=this.#r,a=e!==n?e.state:this.#n,{state:u}=e;let l={...u},c=!1,h;if(t._optimisticResults){const R=this.hasListeners(),y=!R&&or(e,t),T=R&&ar(e,n,t,s);(y||T)&&(l={...l,...Gi(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=Kn(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=Kn(r?.data,h,t),this.#o=h,this.#l=null}catch(R){this.#l=R}this.#l&&(d=this.#l,h=this.#o,f=Date.now(),p="error");const m=l.fetchStatus==="fetching",v=p==="pending",S=p==="error",C=v&&m,w=h!==void 0,b={status:p,fetchStatus:l.fetchStatus,isPending:v,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:m,isRefetching:m&&!v,isLoadingError:S&&!w,isPaused:l.fetchStatus==="paused",isPlaceholderData:c,isRefetchError:S&&w,isStale:_s(e,t),refetch:this.refetch,promise:this.#a,isEnabled:X(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const R=b.data!==void 0,y=b.status==="error"&&!R,T=x=>{y?x.reject(b.error):R&&x.resolve(b.data)},_=()=>{const x=this.#a=b.promise=Qn();T(x)},E=this.#a;switch(E.status){case"pending":e.queryHash===n.queryHash&&T(E);break;case"fulfilled":(y||b.data!==E.value)&&_();break;case"rejected":(!y||b.error!==E.reason)&&_()}}return b}updateResult(){const e=this.#s,t=this.createResult(this.#e,this.options);if(this.#i=this.#e.state,this.#r=this.options,this.#i.data!==void 0&&(this.#u=this.#e),Wt(t,e))return;this.#s=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,r=typeof s=="function"?s():s;if(r==="all"||!r&&!this.#g.size)return!0;const i=new Set(r??this.#g);return this.options.throwOnError&&i.add("error"),Object.keys(this.#s).some(o=>{const a=o;return this.#s[a]!==e[a]&&i.has(a)})};this.#b({listeners:n()})}#C(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#b(e){H.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#s)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function ka(e,t){return X(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&X(t.retryOnMount,e)===!1)}function or(e,t){return ka(e,t)||e.state.data!==void 0&&Xn(e,t,t.refetchOnMount)}function Xn(e,t,n){if(X(t.enabled,e)!==!1&&we(t.staleTime,e)!=="static"){const s=typeof n=="function"?n(e):n;return s==="always"||s!==!1&&_s(e,t)}return!1}function ar(e,t,n,s){return(e!==t||X(s.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&_s(e,n)}function _s(e,t){return X(t.enabled,e)!==!1&&e.isStaleByTime(we(t.staleTime,e))}function La(e,t){return!Wt(e.getCurrentResult(),t)}var Fa=class extends $i{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,s=super.createResult(e,t),{isFetching:r,isRefetching:i,isError:o,isRefetchError:a}=s,u=n.fetchMeta?.fetchMore?.direction,l=o&&u==="forward",c=r&&u==="forward",h=o&&u==="backward",d=r&&u==="backward";return{...s,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:xa(t,n.data),hasPreviousPage:Oa(t,n.data),isFetchNextPageError:l,isFetchingNextPage:c,isFetchPreviousPageError:h,isFetchingPreviousPage:d,isRefetchError:a&&!l&&!h,isRefetching:i&&!c&&!d}}},Na=class extends Di{#t;#e;#n;#s;constructor(e){super(),this.#t=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#e=[],this.state=e.state||Ui(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#e.includes(e)||(this.#e.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#i({type:"continue"})},n={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=Ni({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(i,o)=>{this.#i({type:"failed",failureCount:i,error:o})},onPause:()=>{this.#i({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const s=this.state.status==="pending",r=!this.#s.canStart();try{if(s)t();else{this.#i({type:"pending",variables:e,isPaused:r}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const o=await this.options.onMutate?.(e,n);o!==this.state.context&&this.#i({type:"pending",context:o,variables:e,isPaused:r})}const i=await this.#s.start();return await this.#n.config.onSuccess?.(i,e,this.state.context,this,n),await this.options.onSuccess?.(i,e,this.state.context,n),await this.#n.config.onSettled?.(i,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(i,null,e,this.state.context,n),this.#i({type:"success",data:i}),i}catch(i){try{await this.#n.config.onError?.(i,e,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onError?.(i,e,this.state.context,n)}catch(o){Promise.reject(o)}try{await this.#n.config.onSettled?.(void 0,i,this.state.variables,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,i,e,this.state.context,n)}catch(o){Promise.reject(o)}throw this.#i({type:"error",error:i}),i}finally{this.#n.runNext(this)}}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),H.batch(()=>{this.#e.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function Ui(){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 et{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const s=new Na({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(s),s}add(e){this.#t.add(e);const t=At(e);if(typeof t=="string"){const n=this.#e.get(t);n?n.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=At(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const s=n.indexOf(e);s!==-1&&n.splice(s,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=At(e);if(typeof t=="string"){const n=this.#e.get(t)?.find(s=>s.state.status==="pending");return!n||n===e}else return!0}runNext(e){const t=At(e);return typeof t=="string"?this.#e.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){H.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>tr(t,n))}findAll(e={}){return this.getAll().filter(t=>tr(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 At(e){return e.options.scope?.id}var ja=class extends et{#t;#e=void 0;#n;#s;constructor(e,t){super(),this.#t=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#t.defaultMutationOptions(e),Wt(this.options,t)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&Ge(t.mutationKey)!==Ge(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#r(e)}getCurrentResult(){return this.#e}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#r()}mutate(e,t){return this.#s=t,this.#n?.removeObserver(this),this.#n=this.#t.getMutationCache().build(this.#t,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){const e=this.#n?.state??Ui();this.#e={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#r(e){H.batch(()=>{if(this.#s&&this.hasListeners()){const t=this.#e.variables,n=this.#e.context,s={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#s.onSuccess?.(e.data,t,n,s)}catch(r){Promise.reject(r)}try{this.#s.onSettled?.(e.data,null,t,n,s)}catch(r){Promise.reject(r)}}else if(e?.type==="error"){try{this.#s.onError?.(e.error,t,n,s)}catch(r){Promise.reject(r)}try{this.#s.onSettled?.(void 0,e.error,t,n,s)}catch(r){Promise.reject(r)}}}this.listeners.forEach(t=>{t(this.#e)})})}},Ga=class extends et{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const s=t.queryKey,r=t.queryHash??ws(s,t);let i=this.get(r);return i||(i=new Pa({client:e,queryKey:s,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(s)}),this.add(i)),i}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){H.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>er(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>er(e,n)):t}notify(e){H.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){H.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){H.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},kf=class{#t;#e;#n;#s;#i;#r;#a;#l;constructor(e={}){this.#t=e.queryCache||new Ga,this.#e=e.mutationCache||new Da,this.#n=e.defaultOptions||{},this.#s=new Map,this.#i=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#a=bs.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#l=Jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#a?.(),this.#a=void 0,this.#l?.(),this.#l=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),s=n.state.data;return s===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(we(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(s))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(e,t,n){const s=this.defaultQueryOptions({queryKey:e}),r=this.#t.get(s.queryHash)?.state.data,i=ya(t,r);if(i!==void 0)return this.#t.build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return H.batch(()=>this.#t.findAll(e).map(({queryKey:s})=>[s,this.setQueryData(s,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;H.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return H.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},s=H.batch(()=>this.#t.findAll(e).map(r=>r.cancel(n)));return Promise.all(s).then(q).catch(q)}invalidateQueries(e,t={}){return H.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},s=H.batch(()=>this.#t.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(s).then(q)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(we(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(q).catch(q)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Jt.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#s.set(Ge(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(s=>{gt(e,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(Ge(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#i.values()],n={};return t.forEach(s=>{gt(e,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=ws(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===Es&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},I=Oi(Cs(),1),L=fa(),Bi=I.createContext(void 0),Hi=e=>{const t=I.useContext(Bi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Lf=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,L.jsx)(Bi.Provider,{value:e,children:t})),zi=I.createContext(!1),$a=()=>I.useContext(zi),Ff=zi.Provider;function Ua(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ba=I.createContext(Ua()),Ha=()=>I.useContext(Ba),za=(e,t,n)=>{const s=n?.state.error&&typeof e.throwOnError=="function"?Ts(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||s)&&(t.isReset()||(e.retryOnMount=!1))},Va=e=>{I.useEffect(()=>{e.clearReset()},[e])},qa=({result:e,errorResetBoundary:t,throwOnError:n,query:s,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&s&&(r&&e.data===void 0||Ts(n,[e.error,s])),Ka=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),s=e.staleTime;e.staleTime=typeof s=="function"?(...r)=>n(s(...r)):n(s),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Qa=(e,t)=>e.isLoading&&e.isFetching&&!t,Wa=(e,t)=>e?.suspense&&t.isPending,lr=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Vi(e,t,n){const s=$a(),r=Ha(),i=Hi(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const a=i.getQueryCache().get(o.queryHash);o._optimisticResults=s?"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=!s&&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 lr(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&&!mt.isServer()&&Qa(c,s)&&(u?lr(o,l,r):a?.promise)?.catch(q).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?c:l.trackResult(c)}function Nf(e,t){return Vi(e,$i,t)}function Df(e,t){const n=Hi(t),[s]=I.useState(()=>new ja(n,e));I.useEffect(()=>{s.setOptions(e)},[s,e]);const r=I.useSyncExternalStore(I.useCallback(o=>s.subscribe(H.batchCalls(o)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),i=I.useCallback((o,a)=>{s.mutate(o,a).catch(q)},[s]);if(r.error&&Ts(s.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:i,mutateAsync:r.mutate}}function jf(e,t){return Vi(e,Fa,t)}var ur=I.use,As=I.useLayoutEffect;function Ja(e,t,n){I.useEffect(()=>{if(!e.current||n||typeof IntersectionObserver!="function")return()=>t();const s=new IntersectionObserver(r=>{t(r.pop())},{rootMargin:"100px"});return s.observe(e.current),()=>{s.disconnect(),t()}},[t,n,e])}function Xa(e){const t=I.useRef(null);return I.useImperativeHandle(e,()=>t.current,[]),t}function vt(e){return e[e.length-1]}function Xe(e,t){return typeof e=="function"?e(t):e}var qi=Object.prototype.hasOwnProperty,Ya=Object.prototype.propertyIsEnumerable;function Ki(e){for(const t in e)if(qi.call(e,t))return!0;return!1}var Za=()=>Object.create(null),Oe=(e,t)=>Ne(e,t,Za);function Ne(e,t,n=()=>({}),s=0){if(e===t)return e;if(s>500)return t;const r=t,i=hr(e)&&hr(r);if(!i&&!(Xt(e)&&Xt(r)))return r;const o=i?e:cr(e);if(!o)return r;const a=i?r:cr(r);if(!a)return r;const u=o.length,l=a.length,c=i?new Array(l):n();let h=0;for(let d=0;d<l;d++){const f=i?d:a[d],p=e[f],g=r[f];if(p===g){c[f]=p,(i?d<u:qi.call(e,f))&&h++;continue}if(p===null||g===null||typeof p!="object"||typeof g!="object"){c[f]=g;continue}const m=Ne(p,g,n,s+1);c[f]=m,m===p&&h++}return u===l&&h===u?e:c}function cr(e){const t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;const n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(const s of n){if(!Ya.call(e,s))return!1;t.push(s)}return t}function Xt(e){if(!dr(e))return!1;const t=e.constructor;if(typeof t>"u")return!0;const n=t.prototype;return!(!dr(n)||!n.hasOwnProperty("isPrototypeOf"))}function dr(e){return Object.prototype.toString.call(e)==="[object Object]"}function hr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ee(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let s=0,r=e.length;s<r;s++)if(!Ee(e[s],t[s],n))return!1;return!0}if(Xt(e)&&Xt(t)){const s=n?.ignoreUndefined??!0;if(n?.partial){for(const o in t)if((!s||t[o]!==void 0)&&!Ee(e[o],t[o],n))return!1;return!0}let r=0;if(!s)r=Object.keys(e).length;else for(const o in e)e[o]!==void 0&&r++;let i=0;for(const o in t)if((!s||t[o]!==void 0)&&(i++,i>r||!Ee(e[o],t[o],n)))return!1;return r===i}return!1}function el(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 tl=/[\x00-\x1f\x7f"<>`{}]/g;function nl(e){return e.replace(tl,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function fr(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,n=>{try{return decodeURI(n)}catch{return n}})}return nl(t)}var sl=["http:","https:","mailto:","tel:"];function Yt(e,t){if(!e)return!1;try{const n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function it(e){if(!e)return{path:e,handledProtocolRelativeURL:!1};if(!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith("//"))return{path:e,handledProtocolRelativeURL:!1};const t=/%25|%5C/gi;let n=0,s="",r;for(;(r=t.exec(e))!==null;)s+=fr(e.slice(n,r.index))+r[0],n=t.lastIndex;s=s+fr(n?e.slice(n):e);let i=!1;return s.startsWith("//")&&(i=!0,s="/"+s.replace(/^\/+/,"")),{path:s,handledProtocolRelativeURL:i}}function rl(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function il(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Ms(){throw new Error("Invariant failed")}function Zt(e){const t=new Map;let n,s;const r=i=>{i.next&&(i.prev?(i.prev.next=i.next,i.next.prev=i.prev,i.next=void 0,s&&(s.next=i,i.prev=s)):(i.next.prev=void 0,n=i.next,i.next=void 0,s&&(i.prev=s,s.next=i)),s=i)};return{get(i){const o=t.get(i);if(o)return r(o),o.value},set(i,o){if(t.size>=e&&n){const u=n;t.delete(u.key),u.next&&(n=u.next,u.next.prev=void 0),u===s&&(s=void 0)}const a=t.get(i);if(a)a.value=o,r(a);else{const u={key:i,value:o,prev:s};s&&(s.next=u),s=u,n||(n=u),t.set(i,u)}},clear(){t.clear(),n=void 0,s=void 0}}}var Ce=4,Qi=5;function Wi(e,t,n=new Uint16Array(6)){const s=e.indexOf("/",t),r=s===-1?e.length:s,i=e.substring(t,r);if(!i||!i.includes("$"))return n[0]=0,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n;if(i==="$"){const u=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=u,n[4]=u,n[5]=u,n}if(i.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=r,n[4]=r,n[5]=r,n;const o=i.indexOf("{");let a;if(o!==-1&&o+1<i.length&&(a=i.indexOf("}",o))!==-1){const u=i.charCodeAt(o+1);if(u===45){if(o+2<i.length&&i.charCodeAt(o+2)===36){const l=o+3,c=a;if(l<c)return n[0]=3,n[1]=t+o,n[2]=t+l,n[3]=t+c,n[4]=t+a+1,n[5]=r,n}}else if(u===36){const l=o+1,c=o+2;return c===a?(n[0]=2,n[1]=t+o,n[2]=t+l,n[3]=t+c,n[4]=t+a+1,n[5]=e.length,n):(n[0]=1,n[1]=t+o,n[2]=t+c,n[3]=t+a,n[4]=t+a+1,n[5]=r,n)}}return n[0]=0,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}function un(e,t,n,s,r,i,o,a){a?.(n);let u=s;{const l=n.fullPath??n.from,c=n.options,h=l.length,d=c?.caseSensitive??e,f=c?.params?.parse??c?.parseParams;for(;u<h;){const g=Wi(l,u,t);let m;const v=u,S=g[5];u=S+1,i++;const C=g[0];switch(C){case 0:{const w=l.substring(g[2],g[3]);let b=w,R;d?R=r.static??=new Map:(b=w.toLowerCase(),R=r.staticInsensitive??=new Map);const y=R.get(b);if(y)m=y;else{const T=We(l);T.parent=r,T.depth=i,m=T,R.set(b,T)}break}case 1:case 3:case 2:{let w=l.substring(v,g[1]),b=l.substring(g[4],S);const R=d&&!!(w||b);d||(w=w.toLowerCase(),b=b.toLowerCase());const y=C===1?r.dynamic:C===3?r.optional:r.wildcard,T=C!==2&&!f&&y?.find(_=>!_.parse&&_.caseSensitive===R&&_.prefix===w&&_.suffix===b);if(T)m=T;else{const _=ol(C,l,R,w,b);m=_,_.parent=r,_.depth=i;let E;C===1?E=r.dynamic??=[]:C===3?E=r.optional??=[]:E=r.wildcard??=[],E.push(_),E.length===2&&o?.push(E)}break}}r=m}if(f&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf("/")+1)===95){const g=We(l);g.kind=Qi,g.parent=r,i++,g.depth=i,r.pathless??=[],r.pathless.push(g),r=g}const p=(n.path||!n.children)&&!n.isRoot;if(p&&l.endsWith("/")){const g=We(l);g.kind=Ce,g.parent=r,i++,g.depth=i,r.index=g,r=g}r.parse=f??null,r.priority=c?.params?.priority??0,p&&!r.route&&(r.route=n,r.fullPath=l)}if(n.children)for(const l of n.children)un(e,t,l,u,r,i,o,a)}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 We(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function ol(e,t,n,s,r){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:s,suffix:r}}function al(e,t){const n=We("/"),s=new Uint16Array(6),r=[];for(const i of e)un(!1,s,i,1,n,0,r);for(const i of r)i.sort(Ji);t.masksTree=n,t.flatCache=Zt(1e3)}function ll(e,t){e||="/";const n=t.flatCache.get(e);if(n!==void 0)return n;const s=xs(e,t.masksTree);return t.flatCache.set(e,s),s}function ul(e,t,n,s,r){e||="/",s||="/";const i=t?`case\0${e}`:e;let o=r.singleCache.get(i);return o||(o=We("/"),un(t,new Uint16Array(6),{from:e},1,o,0),r.singleCache.set(i,o)),xs(s,o,n)}function cl(e,t,n=!1){const s=n?e:`nofuzz\0${e}`,r=t.matchCache.get(s);if(r!==void 0)return r;e||="/";let i;try{i=xs(e,t.segmentTree,n)}catch(o){if(o instanceof URIError)i=null;else throw o}return i&&(i.branch=Yi(i.route)),t.matchCache.set(s,i),i}function dl(e){return e==="/"?e:e.replace(/\/{1,}$/,"")}function hl(e,t=!1,n){const s=We(e.fullPath),r=new Uint16Array(6),i=[],o={},a={};let u=0;un(t,r,e,1,s,0,i,l=>{if(n?.(l,u),l.id in o&&Ms(),o[l.id]=l,u!==0&&l.path){const c=dl(l.fullPath);(!a[c]||l.fullPath.endsWith("/"))&&(a[c]=l)}u++});for(const l of i)l.sort(Ji);return{processedTree:{segmentTree:s,singleCache:Zt(1e3),matchCache:Zt(1e3),flatCache:null,masksTree:null},routesById:o,routesByPath:a}}function xs(e,t,n=!1){const s=e.split("/"),r=pl(e,s,t,n);if(!r)return null;const[i]=Xi(e,s,r);return{route:r.node.route,rawParams:i}}function Xi(e,t,n){const s=fl(n.node);let r=null;const i=Object.create(null);let o=n.extract?.part??0,a=n.extract?.node??0,u=n.extract?.path??0,l=n.extract?.segment??0;for(;a<s.length;o++,a++,u++,l++){const c=s[a];if(c.kind===Ce)break;if(c.kind===Qi){l--,o--,u--;continue}const h=t[o],d=u;if(h&&(u+=h.length),c.kind===1){r??=n.node.fullPath.split("/");const f=r[l],p=c.prefix.length;if(f.charCodeAt(p)===123){const g=c.suffix.length,m=f.substring(p+2,f.length-g-1),v=h.substring(p,h.length-g);i[m]=decodeURIComponent(v)}else{const g=f.substring(1);i[g]=decodeURIComponent(h)}}else if(c.kind===3){if(n.skipped&1<<a){o--,u=d-1;continue}r??=n.node.fullPath.split("/");const f=r[l],p=c.prefix.length,g=c.suffix.length,m=f.substring(p+3,f.length-g-1),v=c.suffix||c.prefix?h.substring(p,h.length-g):h;v&&(i[m]=decodeURIComponent(v))}else if(c.kind===2){const f=c,p=e.substring(d+f.prefix.length,e.length-f.suffix.length),g=decodeURIComponent(p);i["*"]=g,i._splat=g;break}}return n.rawParams&&Object.assign(i,n.rawParams),[i,{part:o,node:a,path:u,segment:l}]}function Yi(e){const t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function fl(e){const t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function pl(e,t,n,s){if(e==="/"&&n.index)return{node:n.index,skipped:0};const r=!vt(t),i=r&&e!=="/",o=t.length-(r?1:0),a=[{node:n,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:m}=c;let{extract:v,rawParams:S}=c;if(h.kind===2&&h.route&&!xt(l,c))continue;if(h.parse){if(!pr(e,t,c))continue;S=c.rawParams,v=c.extract}s&&h.route&&h.kind!==Ce&&xt(u,c)&&(u=c);const C=d===o;if(C&&(h.route&&(!i||h.kind===Ce||h.kind===2)&&xt(l,c)&&(l=c),!h.optional&&!h.wildcard&&!h.index&&!h.pathless))continue;const w=C?void 0:t[d];let b;if(C&&h.index){const R={node:h.index,index:d,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S};let y=!0;if(h.index.parse&&(pr(e,t,R)||(y=!1)),y){if(!g&&!m&&!f&&gl(p,o))return R;xt(l,R)&&(l=R)}}if(h.wildcard)for(let R=h.wildcard.length-1;R>=0;R--){const y=h.wildcard[R],{prefix:T,suffix:_}=y;if(!(T&&(C||!(y.caseSensitive?w:b??=w.toLowerCase()).startsWith(T)))){if(_){if(C)continue;const E=t.slice(d).join("/"),x=E.slice(-_.length);if((y.caseSensitive?x:x.toLowerCase())!==_||E.length-_.length<T.length)continue}a.push({node:y,index:o,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}}if(h.optional){const R=f|1<<h.depth+1;for(let y=h.optional.length-1;y>=0;y--){const T=h.optional[y];a.push({node:T,index:d,skipped:R,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}if(!C)for(let y=h.optional.length-1;y>=0;y--){const T=h.optional[y],{prefix:_,suffix:E}=T;if(_||E){const x=T.caseSensitive?w:b??=w.toLowerCase();if(_&&!x.startsWith(_)||E&&x.indexOf(E,x.length-E.length)<_.length)continue}a.push({node:T,index:d+1,skipped:f,statics:p,dynamics:g,optionals:m+Mt(o,d),extract:v,rawParams:S})}}if(!C&&h.dynamic&&w)for(let R=h.dynamic.length-1;R>=0;R--){const y=h.dynamic[R],{prefix:T,suffix:_}=y;if(T||_){const E=y.caseSensitive?w:b??=w.toLowerCase();if(T&&!E.startsWith(T)||_&&E.indexOf(_,E.length-_.length)<T.length)continue}a.push({node:y,index:d+1,skipped:f,statics:p,dynamics:g+Mt(o,d),optionals:m,extract:v,rawParams:S})}if(!C&&h.staticInsensitive){const R=h.staticInsensitive.get(b??=w.toLowerCase());R&&a.push({node:R,index:d+1,skipped:f,statics:p+Mt(o,d),dynamics:g,optionals:m,extract:v,rawParams:S})}if(!C&&h.static){const R=h.static.get(w);R&&a.push({node:R,index:d+1,skipped:f,statics:p+Mt(o,d),dynamics:g,optionals:m,extract:v,rawParams:S})}if(h.pathless)for(let R=h.pathless.length-1;R>=0;R--){const y=h.pathless[R];a.push({node:y,index:d,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}}if(l)return l;if(s&&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 Mt(e,t){return 2**(e-t-1)}function gl(e,t){return e===2**(t-1)-1}function pr(e,t,n){let s,r;try{[s,r]=Xi(e,t,n)}catch{return null}if(n.rawParams=s,n.extract=r,!n.node.parse)return!0;try{if(n.node.parse(s)===!1)return null}catch{}return!0}function xt(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===Ce)>(e.node.kind===Ce)||t.node.kind===Ce==(e.node.kind===Ce)&&t.node.depth>e.node.depth))):!0}function zt(e){return Vt(e.filter(t=>t!==void 0).join("/"))}function Vt(e){return e.replace(/\/{2,}/g,"/")}function Zi(e){return e==="/"?e:e.replace(/^\/{1,}/,"")}function ve(e){const t=e.length;return t>1&&e[t-1]==="/"?e.replace(/\/{1,}$/,""):e}function eo(e){return ve(Zi(e))}function en(e,t){return e?.endsWith("/")&&e!=="/"&&e!==`${t}/`?e.slice(0,-1):e}function ml(e,t,n){return en(e,n)===en(t,n)}function vl({base:e,to:t,trailingSlash:n="never",cache:s}){if(t.includes("//")&&(t=Vt(t)),t.startsWith("/"))return t.length===1||n==="preserve"?t:n==="always"?t.endsWith("/")?t:`${t}/`:t.endsWith("/")?t.slice(0,-1):t;const r=t===".";let i;if(s){i=r?e:e+"\0"+t;const l=s.get(i);if(l)return l}let o;if(r)o=e.split("/");else{for(e.includes("//")&&(e=Vt(e)),o=e.split("/");o.length>1&&vt(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&&(vt(o)===""?n==="never"&&o.pop():n==="always"&&o.push(""));const a=o.join("/"),u=(r?Vt(a):a)||"/";return i&&s&&s.set(i,u),u}function Sl(e){const t=new Map(e.map(r=>[encodeURIComponent(r),r])),n=Array.from(t.keys()).map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),s=new RegExp(n,"g");return r=>r.replace(s,i=>t.get(i)??i)}function wn(e,t,n){const s=t[e];return typeof s!="string"?s:e==="_splat"?/^[a-zA-Z0-9\-._~!/]*$/.test(s)?s:s.split("/").map(r=>mr(r,n)).join("/"):mr(s,n)}function gr({path:e,params:t,decoder:n,...s}){let r=!1;const i=Object.create(null);if(!e||e==="/")return{interpolatedPath:"/",usedParams:i,isMissingParams:r};if(!e.includes("$"))return{interpolatedPath:e,usedParams:i,isMissingParams:r};const o=e.length;let a=0,u,l="";for(;a<o;){const c=a;u=Wi(e,c,u);const h=u[5];if(a=h+1,c===h)continue;const d=u[0];if(d===0){l+="/"+e.substring(c,h);continue}if(d===2){const f=t._splat;i._splat=f,i["*"]=f;const p=e.substring(c,u[1]),g=e.substring(u[4],h);if(!f){r=!0,(p||g)&&(l+="/"+p+g);continue}const m=wn("_splat",t,n);l+="/"+p+m+g;continue}if(d===1){const f=e.substring(u[2],u[3]);!r&&!(f in t)&&(r=!0),i[f]=t[f];const p=e.substring(c,u[1]),g=e.substring(u[4],h),m=wn(f,t,n)??"undefined";l+="/"+p+m+g;continue}if(d===3){const f=e.substring(u[2],u[3]),p=t[f];if(p==null)continue;i[f]=p;const g=e.substring(c,u[1]),m=e.substring(u[4],h),v=wn(f,t,n)??"";l+="/"+g+v+m;continue}}return e.endsWith("/")&&(l+="/"),{usedParams:i,interpolatedPath:l||"/",isMissingParams:r}}function mr(e,t){const n=encodeURIComponent(e);return t?.(n)??n}function Ye(e){return e?.isNotFound===!0}function yl(){try{return sessionStorage}catch{return}}var Il="tsr-scroll-restoration-v1_3",to=yl();function Rl(){try{return JSON.parse(to?.getItem("tsr-scroll-restoration-v1_3")||"{}")}catch{return{}}}function Cl(){try{to?.setItem(Il,JSON.stringify(Ke))}catch{}}var Ke=Rl(),vr="data-scroll-restoration-id",bl=e=>e.state.__TSR_key||e.href;function wl(e){const t=e.getAttribute(vr);if(t)return`[${vr}="${t}"]`;let n="",s=e,r;for(;r=s.parentNode;){let i=1,o=s;for(;o=o.previousElementSibling;)i++;const a=`${s.localName}:nth-child(${i})`;n=n?`${a} > ${n}`:a,s=r}return n}var Ot=!1,qt="window";function Yn(e){try{return typeof e=="function"?e():document.querySelector(e)}catch{}}function Sr(e){const t=new Set;for(const n of e){if(n===qt)continue;const s=Yn(n);s&&t.add(s)}return t}function El(e,t){const n=t??e.options.scrollRestoration,s=e._scroll;n&&(s.restoring=!0);const r=e.options.getScrollRestorationKey||bl,i=new Set,o=a=>{const u=Ke[a]||={};for(const l of i)l===document?u[qt]={scrollX,scrollY}:l.isConnected&&(u[wl(l)]={scrollX:l.scrollLeft,scrollY:l.scrollTop})};n&&!s.restoration&&(s.restoration=!0,Ot=!1,history.scrollRestoration="manual",document.addEventListener("scroll",a=>{Ot||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())),Cl()})),!s.reset&&(s.reset=!0,e.subscribe("onRendered",a=>{const u=e.options.scrollRestorationBehavior,l=e.options.scrollToTopSelectors,c=s.next,h=s.hash;let d;if(i.clear(),s.next=!0,s.hash=!1,typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation}))return;const f=r(a.toLocation),p=a.fromLocation&&r(a.fromLocation);if(s.restoring&&p&&p!==f){const g=Ke[p];if(g){let m=Ke[f];for(const v in g){if(v===qt){if(c)continue}else{const S=Yn(v);if(!S||c&&l&&(d??=Sr(l),d.has(S)))continue}m||(m=Ke[f]={}),m[v]??=g[v]}}}Ot=!0;try{const g=a.toLocation.hash,m=a.toLocation.state.__hashScrollIntoViewOptions??!0;let v=!1;if(c){!g&&l&&(d??=Sr(l));const S=g&&m&&h,C=s.restoring?Ke[f]:void 0;if(C)for(const w in C){const{scrollX:b,scrollY:R}=C[w];if(w===qt){if(S)continue;scrollTo({top:R,left:b,behavior:u}),v=!0}else{const y=Yn(w);y&&(y.scrollLeft=b,y.scrollTop=R,d?.delete(y))}}if(!g){const w={top:0,left:0,behavior:u};if(v||scrollTo(w),d)for(const b of d)b.scrollTo(w)}}!v&&g&&m&&document.getElementById(g)?.scrollIntoView(m)}finally{Ot=!1}}))}function Tl(e,t=String){const n=new URLSearchParams;for(const s in e){const r=e[s];r!==void 0&&n.set(s,t(r))}return n.toString()}function En(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function _l(e){const t=new URLSearchParams(e),n=Object.create(null);for(const[s,r]of t.entries()){const i=n[s];i==null?n[s]=En(r):Array.isArray(i)?i.push(En(r)):n[s]=[i,En(r)]}return n}var Al=/^(?:\s|["[{\d-]|fa|nu|tr)/,Ml=Ol(JSON.parse),xl=Pl(JSON.stringify,JSON.parse);function Ol(e){return t=>{t[0]==="?"&&(t=t.substring(1));const n=_l(t);for(const s in n){const r=n[s];if(typeof r=="string")try{n[s]=e(r)}catch{}}return n}}function Pl(e,t){const n=t===JSON.parse;function s(r){if(r&&typeof r=="object")try{return e(r)}catch{}else if(t&&typeof r=="string"){if(n&&!Al.test(r))return r;try{return t(r),e(r)}catch{}}return r}return r=>{const i=Tl(r,s);return i?`?${i}`:""}}var dt="__root__";function kl(e){if(e.statusCode=e.statusCode||e.code||307,!e.reloadDocument&&typeof e.href=="string")try{new URL(e.href),e.reloadDocument=!0}catch{}const t=new Headers(e.headers);e.href&&t.get("Location")===null&&t.set("Location",e.href);const n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function no(e){return e instanceof Response&&!!e.options}function Ll(e){return{input:({url:t})=>{for(const n of e)t=Zn(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=so(e[n],t);return t}}}function Fl(e){const t=eo(e.basepath),n=`/${t}`,s=e.caseSensitive?n:n.toLowerCase(),r=`${s}/`;return{input:({url:i})=>{const o=e.caseSensitive?i.pathname:i.pathname.toLowerCase();return o===s?i.pathname="/":o.startsWith(r)&&(i.pathname=i.pathname.slice(n.length)),i},output:({url:i})=>(i.pathname=zt(["/",t,i.pathname]),i)}}function Zn(e,t){const n=e?.input?.({url:t});if(n){if(typeof n=="string")return new URL(n);if(n instanceof URL)return n}return t}function so(e,t){const n=e?.output?.({url:t});if(n){if(typeof n=="string")return new URL(n);if(n instanceof URL)return n}return t}function Nl(e,t){const{createMutableStore:n,createReadonlyStore:s,batch:r}=t,i=new Map,o=n("idle"),a=n(e),u=n(void 0),l=n([]),c=s(()=>l.get().map(g=>i.get(g).get())),h=s(()=>({status:o.get(),isLoading:o.get()==="pending",matches:c.get(),location:a.get(),resolvedLocation:u.get()}));function d(g){let m=i.get(g);return m||(m=n(void 0),i.set(g,m)),m}const f={status:o,location:a,resolvedLocation:u,ids:l,matches:c,byRoute:i,__store:h,getMatchStore:d,setMatches:p};function p(g){const m=l.get(),v=g.map(S=>S.routeId);r(()=>{il(m,v)||l.set(v);for(const S of m)v.includes(S)||i.get(S).set(()=>{});for(const S of g){const C=d(S.routeId);C.get()!==S&&C.set(S)}})}return f}var Te="__TSR_index",yr="popstate",Ir="beforeunload";function Dl(e){let t=e.getLocation();const n=new Set,s=o=>{t=e.getLocation(),n.forEach(a=>a({location:t,action:o}))},r=o=>{e.notifyOnIndexChange??!0?s(o):t=e.getLocation()},i=async({task:o,navigateOpts:a,...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=tn(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:n,subscribe:o=>(n.add(o),()=>{n.delete(o)}),push:(o,a,u)=>{const l=t.state[Te];a=Rr(l+1,a),i({task:()=>{e.pushState(o,a),s({type:"PUSH"})},navigateOpts:u,type:"PUSH",path:o,state:a})},replace:(o,a,u)=>{const l=t.state[Te];a=Rr(l,a),i({task:()=>{e.replaceState(o,a),s({type:"REPLACE"})},navigateOpts:u,type:"REPLACE",path:o,state:a})},go:(o,a)=>{i({task:()=>{e.go(o),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[Te]!==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:s}}function Rr(e,t){t||(t={});const n=Os();return{...t,key:n,__TSR_key:n,[Te]:e}}function jl(e){const t=e?.window??(typeof document<"u"?window:void 0),n=t.history.pushState,s=t.history.replaceState;let r=[];const i=()=>r,o=y=>r=y,a=e?.createHref??(y=>y),u=e?.parseLocation??(()=>tn(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){const y=Os();t.history.replaceState({[Te]:0,key:y,__TSR_key:y},"")}let l=u(),c,h=!1,d=!1,f=!1,p=!1;const g=()=>l;let m;const v=()=>{m&&(R._ignoreSubscribers=!0,(m[2]?t.history.pushState:t.history.replaceState)(m[1],"",m[0]),R._ignoreSubscribers=!1,m=void 0,c=void 0)},S=(y,T,_)=>{const E=a(T),x=!!m;x||(c=l),l=tn(T,_),m=[E,_,m?.[2]||y],x||queueMicrotask(()=>v())},C=y=>{l=u(),R.notify({type:y})},w=async()=>{if(d){d=!1;return}const y=u(),T=y.state[Te]-l.state[Te],_=T===1,E=T===-1,x=!_&&!E||h;h=!1;const N=x?"GO":E?"BACK":"FORWARD",F=x?{type:"GO",index:T}:{type:E?"BACK":"FORWARD"};if(f)f=!1;else{const j=i();if(typeof document<"u"&&j.length){for(const A of j)if(await A.blockerFn({currentLocation:l,nextLocation:y,action:N})){d=!0,t.history.go(1),R.notify(F);return}}}l=u(),R.notify(F)},b=y=>{if(p){p=!1;return}let T=!1;const _=i();if(typeof document<"u"&&_.length)for(const E of _){const x=E.enableBeforeUnload??!0;if(x===!0){T=!0;break}if(typeof x=="function"&&x()===!0){T=!0;break}}if(T)return y.preventDefault(),y.returnValue=""},R=Dl({getLocation:g,getLength:()=>t.history.length,pushState:(y,T)=>S(!0,y,T),replaceState:(y,T)=>S(!1,y,T),back:y=>(y&&(f=!0),p=!0,t.history.back()),forward:y=>{y&&(f=!0),p=!0,t.history.forward()},go:y=>{h=!0,t.history.go(y)},createHref:y=>a(y),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=s,t.removeEventListener(Ir,b,{capture:!0}),t.removeEventListener(yr,w)},onBlocked:()=>{c&&l!==c&&(l=c)},getBlockers:i,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Ir,b,{capture:!0}),t.addEventListener(yr,w),t.history.pushState=function(...y){const T=n.apply(t.history,y);return R._ignoreSubscribers||C("PUSH"),T},t.history.replaceState=function(...y){const T=s.apply(t.history,y);return R._ignoreSubscribers||C("REPLACE"),T},R}function Gl(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"");return t.startsWith("//")&&(t="/"+t.replace(/^\/+/,"")),t}function tn(e,t){const n=Gl(e),s=n.indexOf("#"),r=n.indexOf("?"),i=Os();return{href:n,pathname:n.substring(0,s>0?r>0?Math.min(s,r):s:r>0?r:n.length),hash:s>-1?n.substring(s):"",search:r>-1?n.slice(r,s===-1?void 0:s):"",state:t||{[Te]:0,key:i,__TSR_key:i}}}function Os(){return(Math.random()+1).toString(36).substring(7)}function Cr(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function cn(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function br({key:e,__TSR_key:t,__TSR_index:n,__hashScrollIntoViewOptions:s,...r}){return r}function $l(e,t,n,s){for(const r of t){if(s&&e._tx!==s)return;n.some(i=>i.routeId===r.routeId)||e.routesById[r.routeId].options.onLeave?.(r)}for(const r of n){if(s&&e._tx!==s)return;e.routesById[r.routeId].options[t.some(i=>i.routeId===r.routeId)?"onStay":"onEnter"]?.(r)}}var Ul=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.subscribers=new Set,this._cache=new Map,this._committed=[],this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=async n=>(n(),!1),this.update=n=>{const s=this.options,r=this.basepath??s?.basepath??"/",i=this.basepath===void 0,o=s?.rewrite;if(this.options={...s,...n},this.isServer=this.options.isServer??!1??typeof document>"u",this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=Sl(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=jl()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost"),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let l;this.resolvePathCache=Zt(1e3),l=this.buildRouteTree(),this.setRoutes(l)}if(!this.stores&&this.latestLocation){const l=this.getStoreConfig(this);this.batch=l.batch,this.stores=Nl(this.latestLocation,l),El(this)}const a=this.options.basepath??"/",u=this.options.rewrite;if(i||r!==a||o!==u){this.basepath=a;const l=[],c=eo(a);c&&c!=="/"&&l.push(Fl({basepath:a})),u&&l.push(u),this.rewrite=l.length===0?void 0:l.length===1?l[0]:Ll(l),this.history&&this.updateLatestLocation(),this.stores&&this.stores.location.set(this.latestLocation)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const n=hl(this.routeTree,this.options.caseSensitive,(s,r)=>{s.init({originalIndex:r})});return this.options.routeMasks&&al(this.options.routeMasks,n.processedTree),n},this.subscribe=(n,s)=>{const r={eventType:n,fn:s};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=n=>{for(const s of this.subscribers)if(s.eventType===n.type)try{s.fn(n)}catch(r){console.error(r)}},this.parseLocation=(n,s)=>{const r=({pathname:u,search:l,hash:c,href:h,state:d})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(u)){const v=this.options.parseSearch(l),S=this.options.stringifySearch(v);return{href:u+S+c,publicHref:u+S+c,pathname:it(u).path,external:!1,searchStr:S,search:Oe(s?.search,v),hash:it(c.slice(1)).path,state:Ne(s?.state,d)}}const f=new URL(h,this.origin),p=Zn(this.rewrite,f),g=this.options.parseSearch(p.search),m=this.options.stringifySearch(g);return p.search=m,{href:p.href.replace(p.origin,""),publicHref:h,pathname:it(p.pathname).path,external:!!this.rewrite&&p.origin!==this.origin,searchStr:m,search:Oe(s?.search,g),hash:it(p.hash.slice(1)).path,state:Ne(s?.state,d)}},i=r(n),{__tempLocation:o,__tempKey:a}=i.state;if(o&&(!a||a===this.tempLocationKey)){const u=r(o);return u.state.key=i.state.key,u.state.__TSR_key=i.state.__TSR_key,delete u.state.__tempLocation,{...u,maskedLocation:i}}return i},this.resolvePathWithBase=(n,s)=>vl({base:n,to:s,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(n,s,r)=>typeof n=="string"?this.matchRoutesInternal({pathname:n,search:s},r):this.matchRoutesInternal(n,s),this.getMatchedRoutes=n=>{const s=Object.create(null),r=cl(ve(n),this.processedTree,!0);return r&&Object.assign(s,r.rawParams),[r?.branch||[this.routesById.__root__],s,r?.route]},this.buildLocation=n=>{const s=(i={})=>{if(i.href){const _=tn(i.href,{});i={...i,to:Zn(this.rewrite,new URL(_.pathname,this.origin)).pathname,search:this.options.parseSearch(_.search),hash:_.hash.slice(1)}}const o=i._fromLocation||this._pendingLocation||this.latestLocation,a=this.matchRoutesLightweight(o);i.from;const u=i.unsafeRelative==="path"?o.pathname:i.from??a[1],l=a[2],c=a[3],h=this.resolvePathWithBase(u,i.to?`${i.to}`:".");let d=wr(i.params,c);const f=this.routesByPath[ve(h)];let p;if(f)p=this.getRouteBranch(f);else if(h.includes("$"))p=[];else{const[_,E,x]=this.getMatchedRoutes(h);p=_,this.options.notFoundRoute&&(!x||x.path!=="/"&&E["**"])&&(p=[...p,this.options.notFoundRoute])}if(p.length&&Ki(d))for(const _ of p){const E=_.options.params?.stringify??_.options.stringifyParams;if(E){d===c&&(d=Object.assign(Object.create(null),d));try{Object.assign(d,E(d))}catch{}}}const g=n.leaveParams?h:it(gr({path:h,params:d,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path;let m=l;if(n._includeValidateSearch&&this.options.search?.strict){const _={};p.forEach(E=>{if(E.options.validateSearch)try{Object.assign(_,Kt(E.options.validateSearch,{..._,...m}))}catch{}}),m=_}m=Hl(m,i,p,n._includeValidateSearch),m=Oe(l,m);const v=this.options.stringifySearch(m),S=i.hash===!0?o.hash:i.hash?Xe(i.hash,o.hash):void 0,C=S?`#${S}`:"";let w=i.state===!0?o.state:i.state?Xe(i.state,o.state):{};i.state&&(w=Ne(o.state,w));const b=`${g}${v}${C}`;let R,y,T=!1;if(this.rewrite){const _=new URL(b,this.origin),E=so(this.rewrite,_);R=_.href.replace(_.origin,""),E.origin!==this.origin?(y=E.href,T=!0):y=E.pathname+E.search+E.hash}else R=rl(b),y=R;return{publicHref:y,href:R,pathname:g,search:m,searchStr:v,state:w,hash:S??"",external:T,unmaskOnReload:i.unmaskOnReload}},r=s(n);if(n.mask)r.maskedLocation=s({from:n.from,...n.mask});else if(this.options.routeMasks){const i=ll(r.pathname,this.processedTree);if(i){const o=Object.assign(Object.create(null),i.rawParams),{from:a,params:u,...l}=i.route,c=wr(u,o);r.maskedLocation=s({from:n.from,...l,params:c})}}return r},this.commitLocation=async({viewTransition:n,ignoreBlocker:s,...r})=>{let i;const o=ve(this.latestLocation.href)===ve(r.href)&&Ee(br(r.state),br(this.latestLocation.state)),a=this._commitPromise;let u;const l=new Promise(c=>{u=c});if(l.resolve=()=>{u(),a?.resolve()},this._commitPromise=l,o)this.load();else{let{maskedLocation:c,hashScrollIntoView:h,...d}=r;c&&(d={...c,state:{...c.state,__tempKey:void 0,__tempLocation:{...d,search:d.searchStr,state:{...d.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(d.unmaskOnReload??this.options.unmaskOnReload??!1)&&(d.state.__tempKey=this.tempLocationKey)),d.state.__hashScrollIntoViewOptions=h??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=n,i=r.replace?"REPLACE":"PUSH",this.history[i==="REPLACE"?"replace":"push"](d.publicHref,d.state,{ignoreBlocker:s}),this.history.subscribers.size||this.load({action:{type:i}})}return this._scroll.next=r.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:n,resetScroll:s,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:n,resetScroll:s,hashScrollIntoView:r,ignoreBlocker:o});return queueMicrotask(()=>{this._pendingLocation===u&&(this._pendingLocation=void 0)}),l},this.navigate=async({to:n,reloadDocument:s,href:r,publicHref:i,...o})=>{let a=!1;if(r)try{new URL(`${r}`),a=!0}catch{}if(a&&!s&&(s=!0),s){if(n!==void 0||!r){const l=this.buildLocation({to:n,...o});r=r??l.publicHref,i=i??l.publicHref}const u=!a&&i?i:r;if(Yt(u,this.protocolAllowlist))return;if(!o.ignoreBlocker){const l=this.history.getBlockers?.()??[];for(const c of l)if(c?.blockerFn&&await c.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:"PUSH"}))return}o.replace?window.location.replace(u):window.location.href=u;return}return this.buildAndCommitLocation({...o,href:r,to:n,_isNavigate:!0})},this.load=async n=>{this.updateLatestLocation(),n?.action&&(this._scroll.hash=n.action.type==="PUSH"||n.action.type==="REPLACE"),await Yl(this,n)},this.startViewTransition=n=>{const s=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,s&&typeof document.startViewTransition=="function"){let r;if(typeof s=="object"&&window.CSS?.supports?.("selector(:active-view-transition-type(a))")){const i=this.latestLocation,o=this.stores.resolvedLocation.get(),a=typeof s.types=="function"?s.types(cn(i,o)):s.types;if(a===!1)return n();r={update:n,types:a}}else r=n;return document.startViewTransition(r).updateCallbackDone}return n()},this.invalidate=n=>{const s=this._committed,r=n?.filter,i=this._preloads,o=new Set([...s,...this._cache.values(),...[...i?.values()??[]].flat(),...this._tx?.[3]??[]].filter(l=>!r||r(l)).map(l=>l.id)),a=[];for(const[l,c]of i??[])c.some(h=>o.has(h.id))&&(i.delete(l),a.push(l));const u=l=>{if(o.has(l.id)){const c=this.routesById[l.routeId],h={...l,invalid:!0,...(n?.forcePending||l.status==="error"||l.status==="notFound")&&Cr(c)?{status:"pending",error:void 0}:void 0};return l._flight=void 0,h}return l};this._committed=s.map(u);for(const[l,c]of this._cache)o.has(l)&&(c.invalid=!0,n?.forcePending&&(c.status="pending"));for(const l of o)this._flights?.delete(l);for(const l of a)l.abort();return this.shouldViewTransition=!1,this.load({sync:n?.sync})},this.resolveRedirect=n=>{const s=n.headers.get("Location");if(n.options.href){if(s)try{const r=new URL(s);if(this.origin&&r.origin===this.origin){const i=r.pathname+r.search+r.hash;n.options.href=i,n.headers.set("Location",i)}}catch{}}else{const r=this.buildLocation(n.options).publicHref||"/";n.options.href=r,n.headers.set("Location",r)}if(n.options.href&&Yt(n.options.href,this.protocolAllowlist))throw new Error("Redirect blocked: unsafe protocol");return n.headers.get("Location")||n.headers.set("Location",n.options.href),n},this.clearCache=n=>{const s=this._cache,r=this._preloads,i=n?.filter,o=[],a=[];for(const[l,c]of s)(!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)s.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=Je,this.preloadRoute=n=>Zl(this,n),this.matchRoute=(n,s)=>{const r={...n,to:n.to?this.resolvePathWithBase(n.from||"",n.to):void 0,params:n.params||{},leaveParams:!0},i=this.buildLocation(r),o=this.stores.status.get()==="pending";if(s?.pending&&!o)return!1;const a=s?.pending??!o?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),u=ul(i.pathname,s?.caseSensitive??!1,s?.fuzzy??!1,a.pathname,this.processedTree);return!u||n.params&&!Ee(u.rawParams,n.params,{partial:!0})?!1:s?.includeSearch??!0?Ee(a.search,i.search,{partial:!0})?u.rawParams:!1:u.rawParams},this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??"fuzzy",stringifySearch:e.stringifySearch??xl,parseSearch:e.parseSearch??Ml,protocolAllowlist:e.protocolAllowlist??sl}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;const s=this.options.notFoundRoute;s&&(s.init({originalIndex:99999999999}),this.routesById[s.id]=s)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=Yi(e),this.routeBranchCache.set(e,t)),t}matchRoutesInternal(e,t){const[n,s,r]=this.getMatchedRoutes(e.pathname);let i=n,o=!1;(r?r.path!=="/"&&s["**"]:ve(e.pathname))&&(this.options.notFoundRoute?i=[...i,this.options.notFoundRoute]:o=!0);const a=o?zl(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,m,v;{const F=p?.search??e.search,j=p?._strictSearch??void 0;try{const A=Kt(f.options.validateSearch,{...F})??void 0;g={...F,...A},m={...j,...A}}catch(A){let le=A;if(A instanceof nn||(le=new nn(A.message,{cause:A})),t?.throwOnError)throw le;g=F,m={},v=le}}let S="",C="";try{S=f.options.loaderDeps?.({search:g})??"",C=S&&JSON.stringify(S)||""}catch(F){if(t?.throwOnError)throw F;v??=F}const{interpolatedPath:w,usedParams:b}=gr({path:f.fullPath,params:s,decoder:this.pathParamsDecoder,server:this.isServer}),R=f.id+w+C,y=c(f,d),T=this._cache.get(R)??(y?.id===R?y:void 0);h=T?._strictParams??Object.assign(b,h);let _;if(!T)try{Er(f,h)}catch(F){if(Ye(F)||no(F)?_=F:_=new Bl(F.message,{cause:F}),t?.throwOnError)throw _}const E=y?"stay":"enter";let x;if(T)x={...T,cause:E,search:Oe(y?y.search:T.search,g),_strictSearch:m,searchError:v};else{const F=Cr(f)?"pending":"success";x={id:R,ssr:f.options.ssr,index:d,routeId:f.id,params:y?.params??h,_strictParams:h,pathname:w,updatedAt:Date.now(),search:y?Oe(y.search,g):g,_strictSearch:m,searchError:v,status:F,isFetching:!1,error:void 0,paramsError:_,context:{},abortController:t?._controller??new AbortController,cause:E,loaderDeps:y?Ne(y.loaderDeps,S):S,invalid:!1,preload:!1,staticData:f.options.staticData||{},fullPath:f.fullPath}}const N=a===f.id;x._notFound&&!N&&(x.error=void 0),x._notFound=N,u[d]=x}for(let d=0;d<u.length;d++){const f=u[d];f.params=f.cause==="stay"?Oe(f.params,h):h,t?._controller&&(f.context={})}return u}matchRoutesLightweight(e){const t=vt(this.stores.ids.get()),n=t?this.stores.byRoute.get(t).get():void 0,s=n?.id,r=this.lightweightCache.get(e);if(r&&r[0]===s)return r[1];const[i,o]=this.getMatchedRoutes(e.pathname),a=vt(i),u={...e.search};for(const d of i)try{Object.assign(u,Kt(d.options.validateSearch,u))}catch{}const l=n&&n.routeId===a.id&&n.pathname===e.pathname;let c;if(l)c=n.params;else{const d=Object.assign(Object.create(null),o);for(const f of i)try{Er(f,d)}catch{}c=d}const h=[i,a.fullPath,u,c];return this.lightweightCache.set(e,[s,h]),h}},nn=class extends Error{},Bl=class extends Error{};function Kt(e,t){if(e==null)return{};if("~standard"in e){const n=e["~standard"].validate(t);if(n instanceof Promise)throw new nn("Async validation not supported");if(n.issues)throw new nn(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return"parse"in e?e.parse(t):typeof e=="function"?e(t):{}}function Hl(e,t,n,s){const r=[];for(const o of n){const a=o.options;if("search"in a)a.search?.middlewares&&r.push(...a.search.middlewares);else if(a.preSearchFilters||a.postSearchFilters){const l=({search:c,next:h})=>{const d=h(a.preSearchFilters?a.preSearchFilters.reduce((f,p)=>p(f),c):c);return a.postSearchFilters?a.postSearchFilters.reduce((f,p)=>p(f),d):d};r.push(l)}const u=a.validateSearch;if(s&&u){const l=({search:c,next:h,meta:d})=>{const f=h(c);try{const p=Kt(u,f);if(d&&p)for(const g in p)g in f||(d.defaulted||=new Map).set(g,p[g]);return{...f,...p}}catch{}return f};r.push(l)}}const i=(o,a,u)=>{if(o>=r.length){if(!t.search)return{};if(t.search===!0)return a;const c=Xe(t.search,a);return u&&(u.explicit=c),c}const l=(c,h)=>{if(h){const d=u||{};return{search:i(o+1,c,d),meta:d}}return i(o+1,c,u)};return r[o]({search:a,next:l,meta:u})};return i(0,e)}function zl(e,t){if(e!=="root"){let n;for(let s=t.length-1;s>=0;s--){const r=t[s];if(r.options.notFoundComponent)return r.id;n||=r.children&&r.id}if(n)return n}return dt}function wr(e,t){if(e===!1||e===null)return Object.create(null);if((e??!0)===!0)return t;const n=Object.assign(Object.create(null),t);return Object.assign(n,Xe(e,n))}function Er(e,t){const n=e.options.params?.parse??e.options.parseParams;n&&Object.assign(t,n(t))}function es(e,t){return e.options[t]?.preload?.()}function Vl(e,t){const n=es(e,"component");let s=es(e,"pendingComponent");return t&&(s?s=s.then(t):t()),n&&s?Promise.all([n,s]).then(()=>{}):n??s}function Je(e,t,n){const s=()=>t===!1?void 0:t?es(e,t):Vl(e,n),r=e._lazy;if(r)return r===!0?s():r.then(s);if(!e.lazyFn)return s();const i=e.lazyFn().then(o=>{{const{id:a,...u}=o.options;Object.assign(e.options,u),e._lazy=!0}},o=>{throw e._lazy=void 0,o});return e._lazy=i,i.then(s)}function Ps(e){const t=e.findIndex(n=>n.status!=="success"||n._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var pe=0,ye=1,dn=2,Z=3,_e=[4];function St(e){return typeof e[0]=="number"}function Be(e,t){return t.aborted?Promise.race([Promise.reject(t),e]):new Promise((n,s)=>{const r=()=>s(t);t.addEventListener("abort",r,{once:!0}),Promise.resolve(e).then(n,s).finally(()=>t.removeEventListener("abort",r))})}function He(e,t){return e.routesById[t.routeId]}function yt(e,t,n){return no(e)?[Z,e]:Ye(e)?(e.routeId||=n,[dn,e]):t?(typeof e?.then=="function"&&(e=new Error("A Promise was thrown",{cause:e})),[ye,e]):[pe,e]}function ks(e,t){let n=yt(t,!0,e.id);if(n[0]!==ye)return n;try{e.options.onError?.(n[1])}catch(s){n=yt(s,!0,e.id)}return n}function ht(e,t,n,s,r){return r[0].signal.aborted?_e:Ns(e,t,n,ks(n,s),r)}async function ql(e,t,n,s,r,i){const[o,a]=t,u=n[0].signal,l=!!n[3];for(let c=n[6]??0;c<s;c++){const h=a[c],d=He(e,h);h.abortController=n[0];const f=a[c-1]?.context??e.options.context??{},p={params:h.params,location:o,navigate:S=>e.navigate({...S,_fromLocation:o}),buildLocation:e.buildLocation,cause:l?"preload":h.cause,abortController:n[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 Se(e,h),[c,ht(e,t,d,S,n)]}if(u.aborted)return[c,_e];const g=h.paramsError??h.searchError;if(g!==void 0)return Se(e,h),[c,ht(e,t,d,g,n)];const m=d.options.beforeLoad;if(!m)continue;const v=h.status;c>=i&&(h.status="pending",n[7]?.());try{It(e,h,"beforeLoad",n[0]);const S=await Be(m({...p,search:h.search,context:h.context,...e.options.additionalContext}),u);if(u.aborted)return[c,_e];const C=Ns(e,t,d,yt(S,!1,d.id),n);if(C[0]!==pe)return Se(e,h),[c,C];h.context={...h.context,...S}}catch(S){return Se(e,h),[c,ht(e,t,d,S,n)]}finally{h.status=v,It(e,h,!1,n[0])}}r()}function Ls(e,t,n){if(!(!n||--n[2])){if(e._flights?.get(t.id)===n){const s=e._tx;if(s&&!s[0].signal.aborted&&!s[3].includes(t)&&s[3].some(r=>r.id===t.id)&&s[3].some(r=>r.isFetching==="beforeLoad"))return;e._flights.delete(t.id)}return n[1]}}function Se(e,t){const n=t._flight;t._flight=void 0,Ls(e,t,n)?.abort()}function Q(e,t,n,s){const r=[];for(const i of t)if(!n?.includes(i)){const o=i._flight;if(i._flight=void 0,s&&o?.[2]===1&&e._flights?.get(i.id)===o&&n?.some(a=>a.id===i.id))o[2]=0;else{const a=Ls(e,i,o);a&&r.push(a)}}for(const i of r)i.abort()}function Fs(e){for(const t of e){const n=t._flight;n&&n[2]++}}function It(e,t,n,s){if(t.isFetching=n,s&&e._tx?.[0]!==s)return;const r=e.stores.byRoute.get(t.routeId),i=r?.get();i?.id===t.id&&r.set({...i,isFetching:n})}function ro(e,t,n,s,r,i,o){const a=t[0];return{params:n.params,location:a,navigate:u=>e.navigate({...u,_fromLocation:a}),cause:o?"preload":n.cause,abortController:r,preload:o,deps:n.loaderDeps,parentMatchPromise:i,context:n.context,route:s,...e.options.additionalContext}}async function Tr(e,t,n,s,r,i,o){const a=o[0],u=a.signal;if(u.aborted)return _e;if(!r)return[pe,void 0];let l=n._flight;It(e,n,"loader",a);try{if(!l){const c=new AbortController;l=[Promise.resolve().then(()=>r(ro(e,t,n,s,c,i,!!o[3]))).then(h=>yt(h,!1,s.id),h=>yt(h,!0,s.id)).then(h=>(h[0]!==pe&&e._flights?.get(n.id)===l&&(e._flights.delete(n.id),l[2]||c.abort()),h[0]===ye&&l[2]?ks(s,h[1]):h)),c,1],(e._flights??=new Map).set(n.id,l)}return n._flight=l,n.abortController=l[1],Ns(e,t,s,await Be(l[0],u),o)}catch(c){if(c!==u||!u.aborted)throw c;return Se(e,n),_e}finally{It(e,n,!1,a)}}function _r(e,t,n){t[0]!==Z&&(e.status="success",e.error=void 0,t[0]===pe?(e.loaderData=t[1],e.invalid=!1,e.updatedAt=Date.now(),e.preload=n):e.invalid=!0)}function Kl(e,t,n){const s=e._cache.get(t.id);if(s!==n||e._committed.some(i=>i.id===t.id&&i._flight===t._flight))return;const r={...t,_notFound:void 0,context:{}};r._flight&&r._flight[2]++,e._cache.set(t.id,r),s&&Se(e,s)}function Ar(e,t){return t[0]===ye||t[0]===dn?{...e,status:t[0]===ye?"error":"notFound",error:t[1],_flight:void 0}:e}function Ql(e,t,n,s,r,i,o){const a=t[1][n],u=He(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(ro(e,t,a,u,i[0],r,l))),i[0].signal.aborted&&(f=_e)),!f)if(a.status!=="success")d=!0;else{const N=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>=N&&(i[5]||a.cause==="enter"||i[2].some(F=>F.routeId===a.routeId&&F.id!==a.id)))}}catch(N){a.invalid=!0,Se(e,a),f=ht(e,t,u,N,i)}const p=u.options.loader,g=typeof p=="function",m=g?p:p?.handler,v=!l||u.options.preload!==!1;let S=v&&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"),w=d&&v,b=w&&!C&&(a.status!=="success"||!!p),R=n>=o?i[7]:void 0,y=u.lazyFn&&u._lazy!==!0?R:void 0;if(w&&!p&&(a.invalid=!1,a.updatedAt=Date.now()),S&&S[2]++,b){const N=a._flight;a._flight=S,Ls(e,a,N)?.abort(),n>=o&&(a.status="pending"),R?.()}w||(a.isFetching=!1);const T=(f?Promise.resolve(f):b?Tr(e,t,a,u,m,r,i):Promise.resolve([pe,a.loaderData])).then(N=>(b&&(_r(a,N,l),N[0]===pe&&(p&&!i[0].signal.aborted&&Kl(e,a,c),n>=o&&(a.status="pending"))),N)),_=Be(Promise.resolve().then(()=>Je(u,void 0,y)),i[0].signal).then(()=>{},N=>t[1].some((F,j)=>j<=n&&(F.status==="error"||F.status==="notFound"||F._notFound))?void 0:[n,ht(e,t,u,N,i)]).then(N=>T.then(F=>(b&&!N&&F[0]===pe&&a.status==="pending"&&!i[0].signal.aborted&&(a.status="success",R?.()),N)));if(s.push([n,T,_]),!C)return T.then(N=>Ar(a,N));const E={...a,status:"pending",preload:!1,_flight:S};a.invalid=!1,a.isFetching="loader";const x=Tr(e,t,E,u,m,r,i).then(N=>(a.isFetching=!1,_r(E,N,!1),N));return(t[2]??=[]).push([n,x,_,E]),x.then(N=>Ar(E,N))}async function ts(e,t,n,s,r=0){const i=n?.[1][1];let o=i?.routeId?t.findIndex(a=>a.routeId===i.routeId):n?.[0]??t.length-1;o<0&&(o=0);for(let a=o;a>=0;a--){const u=He(e,t[a]);try{const l=Je(u,!1);l&&await Be(l,s)}catch(l){if(l===s&&s.aborted)throw l}if(u.options.notFoundComponent)return a}return i?.routeId?o:r}function De(e,t){t[2]&&(Q(e,t[2].map(n=>n[3])),t[2]=void 0)}async function Mr(e,t,n,s){let r;try{await Promise.all(e.map(i=>i[1].then(async o=>{const a=i[0];if(!(s&&a>=await s)){if(o[0]>=Z)throw[a,o];!r&&o[0]!==pe&&(r=[a,o],await Promise.all((n??[]).map(u=>{if(!(u[0]<=a))return u[1].then(l=>{if(l[0]===Z)throw[u[0],l]})})))}})))}catch(i){return i}return t??r}function Ns(e,t,n,s,r,i){for(;s[0]===Z;){const o=s[1],a=o.options;if(a.reloadDocument?r[3]:r[1]>=20)return s;try{return a.href&&a.reloadDocument?(e.resolveRedirect(o),s):[Z,o,e.buildLocation({...a,_fromLocation:t[0],_includeValidateSearch:!0})]}catch(u){s=i?[ye,u]:ks(n,u),i=!0}}return s}async function io(e,t,n,s,r,i){const o=t[1];let a=await r,u=!1;const l=o.findIndex(f=>f._notFound),c=f=>f[1][0]===dn?ts(e,o,f,s.signal):f[0];let h=l<0?o.length:l;if((a?.[1][0]??0)>=Z)h=0;else if(a){h=a[2]??=await c(a);for(const f of n){if(f[0]>=h)break;const p=await f[1];if(p[0]!==pe&&p[0]<Z&&!("loaderData"in o[f[0]])){a=[f[0],p],h=a[2]=await c(a);break}}}for(const f of n){if(f[0]>=h)break;const p=await f[2];if(p){a=p;break}}if((a?.[1][0]??0)>=Z){const f=a[1];if(f[0]!==Z||f[1].options.reloadDocument||f[2])return De(e,t),f;u=!0,a=[0,[ye,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],m=f?.[1],v=()=>{f&&(g._notFound=void 0,p===ye?g.status="error":(m.routeId=g.routeId,g.routeId===e.routeTree.id?(g.status="success",g._notFound=!0):g.status="notFound"),g.error=m,g.isFetching=!1)};v(),f||i?.();const S=He(e,g);try{await Be(f?Promise.resolve().then(()=>Je(S,p===ye?"errorComponent":"notFoundComponent")):Promise.all([Je(S),Je(S,"notFoundComponent")]),s.signal)}catch(C){if(C===s.signal&&s.signal.aborted)return De(e,t),_e}f?u&&(s.abort(),await Promise.all([...n.map(C=>C[1]),...n.map(C=>C[2]),...(t[2]??[]).map(C=>C[1])]),De(e,t),Q(e,o),v()):g.status="success"}return t}async function oo(e,t,n,s=0,r=t[1].length){const i=t[1];for(let o=s;o<r;o++){const a=i[o],u=He(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 Be(Promise.all([u.head?.(l),u.scripts?.(l)]),n);a.meta=c?.meta,a.links=c?.links,a.headScripts=c?.scripts,a.styles=c?.styles,a.scripts=h}catch(l){if(l===n&&n.aborted)break;console.error(l)}if(a.status!=="success"||a._notFound)break}return t}async function ao(e,t,n,s){const r=[t,n],i=s[0].signal;let o;try{const a=e.stores.matches.get();let u=n.findIndex(v=>v._notFound);if(e.options.notFoundMode!=="root"&&u>=0){const v=await ts(e,n,void 0,i,u);n[u]._notFound=void 0,n[v]._notFound=!0,u=v}let l=u<0?n.length:u+1,c=0;for(;c<l&&c!==u;){const v=n[c],S=s[2][c],C=a[c];if(S?.id!==v.id||S.status!=="success"||S._notFound||v.preload||C?.id!==v.id||C.status!=="success"||C._notFound)break;c++}const h=[],d=s[6]??0;let f=d?Promise.resolve(n[d-1]):void 0;const p=()=>{for(let v=d;v<l&&!i.aborted;v++)f=Ql(e,r,v,h,f,s,c)},g=await ql(e,r,s,l,p,c);if(g){if(s[4]=!0,l=g[0],g[1][0]===dn){const v=await ts(e,n,g,i);g[2]=v,l=Math.min(l,v+1)}else g[1][0]>=Z&&(l=0);p()}if(!i.aborted&&!s[3]){const v=[];for(const[S,C]of e._flights??[])C[2]||(e._flights.delete(S),v.push(C[1]));for(const S of v)S.abort()}const m=io(e,r,h,s[0],Mr(h,g,r[2]),s[7]);r[2]?.length&&(r[3]=Mr(r[2],void 0,void 0,m.then(v=>St(v)?0:Ps(n).length,()=>0))),o=await m}catch(a){if(De(e,r),a===i&&i.aborted)return _e;throw a}return St(o)?o:oo(e,o,i,s[6]===n.length?s[6]:0)}function ns(e,t){if(e._tx!==t)return;const n=t[3],s=e.stores.matches.get();let r=e._pending;for(let i=0;i<n.length;i++){const o=n[i],a=o.status==="success"&&!o._notFound,u=s[i]?.id===o.id&&s[i]?.status==="pending";if(a&&!u)continue;const l=He(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 m=r[2]-Date.now();if(m>0){r[3]=setTimeout(()=>ns(e,t),m);return}r[2]=0}const p=n.map(m=>({...m,_flight:void 0}));p[i].status="pending";const g=r[4]=e.startTransition(()=>e.stores.setMatches(p),p).then(m=>(m&&e._pending===r&&r[4]===g&&!r[2]&&(r[2]=Date.now()+d),m));return}}function ot(e,t){const n=e._pending;(e._tx===t||!e._tx?.[3].some(s=>s.id===n?.[1]))&&(clearTimeout(n?.[3]),e._pending=void 0)}async function xr(e,t){const n=e._pending;if(!n)return;clearTimeout(n[3]);const s=n[2]-Date.now();if(!n[4]||s<=0||!Ps(t[3]).some(i=>i.id===n[1]))return;let r;try{await Be(new Promise(i=>{r=setTimeout(i,s)}),t[0].signal)}catch{}clearTimeout(r)}function lo(e,t){e._committed=t,e.stores.setMatches(t)}function Wl(e,t,n,s){const r=e._committed,i=e._cache;for(const u of n)u.preload=!1,s&&(u._assetEnd=void 0);const o=Ps(n).length,a=new Map;{const u=Date.now();for(const l of[...r,...i.values()]){if(l.status!=="success"||n.some((h,d)=>h.id===l.id&&(d<o||h.status==="success")))continue;const c=He(e,l);!c.options.loader||u-l.updatedAt>=(l.preload?c.options.preloadGcTime??e.options.defaultPreloadGcTime??3e5:c.options.gcTime??e.options.defaultGcTime??3e5)||a.set(l.id,i.get(l.id)===l?l:{...l,_flight:void 0,isFetching:!1,context:{}})}}t[3]=[],e._cache=a,lo(e,n),Q(e,[...i.values(),...r],[...n,...a.values()]),$l(e,r,n,t)}async function Pt(e,t){let n=e._tx;for(;n&&n!==t;){if(await n[5],e._tx===n)return;n=e._tx}}function uo(e,t,n){const s=n[1].options,r=n[2];if(!r)return e.navigate({...s,replace:!0,ignoreBlocker:!0});if(s.reloadDocument)return e.navigate({href:r.publicHref,reloadDocument:!0,replace:!0,ignoreBlocker:!0});r._redirects=t[1]+1,e._pendingLocation=r;const i=e.commitLocation({...r,viewTransition:s.viewTransition,replace:!0,resetScroll:s.resetScroll,hashScrollIntoView:s.hashScrollIntoView,ignoreBlocker:!0});return queueMicrotask(()=>{e._pendingLocation===r&&(e._pendingLocation=void 0)}),i}async function Jl(e,t,n,s,r){const i=n.map(u=>({...u}));Fs(i);for(const u of s)Se(e,i[u[0]]),i[u[0]]=u[3];const o=[t[2],i];let a;try{a=await io(e,o,s,t[0],r)}catch(u){throw Q(e,i),u}if(St(a)){Q(e,i),a[0]===Z&&e._tx===t&&e._committed===n&&await uo(e,t,a);return}if(await oo(e,a,t[0].signal),e._tx!==t||e._committed!==n){Q(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),Se(e,l))}lo(e,i),Q(e,n,i)}async function Xl(e,t,n,s,r,i){const o=await ao(e,t[2],t[3],[t[0],t[1],e._committed,void 0,r,n,i,s]);if(St(o)){const h=o[0]===Z&&e._tx===t;if((!h||o[1].options.reloadDocument)&&ot(e,t),Q(e,t[3]),t[3]=[],!h)return;if(e._tx!==t){ot(e,t);return}await uo(e,t,o);return}const a=o[1];if(e._tx===t&&await xr(e,t),e._tx!==t){ot(e,t),Q(e,a),De(e,o);return}const u=t[2],l=cn(u,e.stores.resolvedLocation.get()),c=o[2];await e.startViewTransition(async()=>{if(e._tx===t&&await xr(e,t),e._tx!==t){ot(e,t),Q(e,a),De(e,o);return}const h=()=>{ot(e,t),Wl(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){De(e,o);return}c?.length&&Jl(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 Yl(e,t){const n=e._tx,s=e.stores.resolvedLocation.get(),r=s??e.stores.location.get(),i=e.latestLocation,o=e._pendingLocation,a=o?.href===i.href?o._redirects??0:0,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 w=cn(i,s);e.emit({type:"onBeforeNavigate",...w}),c.signal.aborted||e.emit({type:"onBeforeLoad",...w})}if(c.signal.aborted){await Pt(e,n);return}const d=r.href===i.href;let f=c;const p=e.matchRoutes(i,{_controller:c});Fs(p);const g=l?u[1](p):void 0;if(g?f=l:l?.abort(),c.signal.aborted){Q(e,p),await Pt(e,n);return}e._preflight=void 0;let m;const v=()=>Xl(e,C,d,()=>ns(e,C),t?.sync,g),S=t?.sync?new Promise(w=>m=w):Promise.resolve().then(v).then(),C=[f,a,i,p,Date.now(),S];if(e._tx=C,n){for(const w of e.stores.matches.get()){if(e._tx!==C)break;w.isFetching&&It(e,w,!1)}n[0].abort(),Q(e,n[3],C[3],!0)}if(e._tx!==C){Q(e,C[3]),C[3]=[],m?.(),await Pt(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(w=>w._notFound))&&ns(e,C),m?.(v()),await S,await Pt(e,C)}async function Zl(e,t){let n=e.buildLocation(t);for(let s=0;;s++){const r=e._committed,i=new AbortController;let o,a,u;try{try{o=e.matchRoutes(n,{_controller:i}),Fs(o),a=(e._preloads??=new Map).set(i,o),u=await ao(e,n,o,[i,s,r,!0])}finally{a&&(a=a.delete(i),Q(e,o)),i.abort()}if(!St(u))return u[1];if(!a||u.length<3)return;n=u[2]}catch(l){Ye(l)||console.error(l);return}}}var eu="Error preloading route! ☝️",co=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.originalIndex;const n=this.options,s=!n?.path&&!n?.id;this.parentRoute=this.options.getParentRoute?.(),s?this._path=dt:this.parentRoute||Ms();let r=s?dt:n?.path;r&&r!=="/"&&(r=Zi(r));const i=n?.id||r;let o=s?dt:zt([this.parentRoute.id==="__root__"?"":this.parentRoute.id,i]);r==="__root__"&&(r="/"),o!=="__root__"&&(o=zt(["/",o]));const a=o==="__root__"?"/":zt([this.parentRoute.fullPath,r]);this._path=r,this._id=o,this._fullPath=a,this._to=ve(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=>kl({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.")}},tu=class extends co{constructor(e){super(e)}},Ds=class extends I.Component{constructor(...e){super(...e),this.state={error:null},this.reset=()=>{this.setState({error:null})}}static getDerivedStateFromProps(e,t){const n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){const e=this.state.error;return e?I.createElement(this.props.errorComponent??nu,{error:e,reset:this.reset}):this.props.children}};function nu({error:e}){const[t,n]=I.useState(!1);return(0,L.jsxs)("div",{style:{padding:".5rem",maxWidth:"100%"},children:[(0,L.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:".5rem"},children:[(0,L.jsx)("strong",{style:{fontSize:"1rem"},children:"Something went wrong!"}),(0,L.jsx)("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:()=>n(s=>!s),children:t?"Hide Error":"Show Error"})]}),(0,L.jsx)("div",{style:{height:".25rem"}}),t?(0,L.jsx)("div",{children:(0,L.jsx)("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"},children:e.message?(0,L.jsx)("code",{children:e.message}):null})}):null]})}function su({children:e,fallback:t=null}){return(0,L.jsx)(I.Fragment,{children:ho()?e:t})}function ho(){return I.useSyncExternalStore(ru,()=>!0,()=>!1)}function ru(){return()=>{}}var fo=I.createContext(null);function se(e){return I.useContext(fo)}var hn=I.createContext(void 0),iu=I.createContext(void 0),G=(e=>(e[e.None=0]="None",e[e.Mutable=1]="Mutable",e[e.Watching=2]="Watching",e[e.RecursedCheck=4]="RecursedCheck",e[e.Recursed=8]="Recursed",e[e.Dirty=16]="Dirty",e[e.Pending=32]="Pending",e))(G||{});function ou({update:e,notify:t,unwatched:n}){return{link:s,unlink:r,propagate:i,checkDirty:o,shallowPropagate:a};function s(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&&n(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 m=p.subs;m.nextSub!==void 0&&a(m),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 m=l.nextDep;if(m!==void 0){l=m;continue}}for(;d--;){const m=c.subs,v=m.nextSub!==void 0;if(v?(l=h.value,h=h.prev):l=m,f){if(e(c)){v&&a(m),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 au(e,t,n){const s=typeof e=="object",r=s?e:void 0;return{next:(s?e.next:e)?.bind(r),error:(s?e.error:t)?.bind(r),complete:(s?e.complete:n)?.bind(r)}}var ss=[],Qt=0,{link:Or,unlink:lu,propagate:uu,checkDirty:po,shallowPropagate:Pr}=ou({update(e){return e._update()},notify(e){ss[rs++]=e,e.flags&=~G.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=G.Mutable|G.Dirty,sn(e))}}),kt=0,rs=0,fe,is=0;function cu(e){try{++is,e()}finally{--is||go()}}function sn(e){const t=e.depsTail;let n=t!==void 0?t.nextDep:e.deps;for(;n!==void 0;)n=lu(n,e)}function go(){if(!(is>0)){for(;kt<rs;){const e=ss[kt];ss[kt++]=void 0,e.notify()}kt=0,rs=0}}function kr(e,t){const n=typeof e=="function",s=e,r={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?G.None:G.Mutable,get(){return fe!==void 0&&Or(r,fe,Qt),r._snapshot},subscribe(i){const o=au(i),a={current:!1},u=du(()=>{r.get(),a.current?o.next?.(r._snapshot):a.current=!0});return{unsubscribe:()=>{u.stop()}}},_update(i){const o=fe,a=t?.compare??Object.is;if(n)fe=r,++Qt,r.depsTail=void 0;else if(i===void 0)return!1;n&&(r.flags=G.Mutable|G.RecursedCheck);try{const u=r._snapshot,l=typeof i=="function"?i(u):i===void 0&&n?s(u):i;return u===void 0||!a(u,l)?(r._snapshot=l,!0):!1}finally{fe=o,n&&(r.flags&=~G.RecursedCheck),sn(r)}}};return n?(r.flags=G.Mutable|G.Dirty,r.get=function(){const i=r.flags;if(i&G.Dirty||i&G.Pending&&po(r.deps,r)){if(r._update()){const o=r.subs;o!==void 0&&Pr(o)}}else i&G.Pending&&(r.flags=i&~G.Pending);return fe!==void 0&&Or(r,fe,Qt),r._snapshot}):r.set=function(i){if(r._update(i)){const o=r.subs;o!==void 0&&(uu(o),Pr(o),go())}},r}function du(e){const t=()=>{const s=fe;fe=n,++Qt,n.depsTail=void 0,n.flags=G.Watching|G.RecursedCheck;try{return e()}finally{fe=s,n.flags&=~G.RecursedCheck,sn(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:G.Watching|G.RecursedCheck,notify(){const s=this.flags;s&G.Dirty||s&G.Pending&&po(this.deps,this)?t():this.flags=G.Watching},stop(){this.flags=G.None,this.depsTail=void 0,sn(this)}};return t(),n}var hu=Ze((e=>{var t=Cs();function n(d,f){return d===f&&(d!==0||1/d===1/f)||d!==d&&f!==f}var s=typeof Object.is=="function"?Object.is:n,r=t.useState,i=t.useEffect,o=t.useLayoutEffect,a=t.useDebugValue;function u(d,f){var p=f(),g=r({inst:{value:p,getSnapshot:f}}),m=g[0].inst,v=g[1];return o(function(){m.value=p,m.getSnapshot=f,l(m)&&v({inst:m})},[d,p,f]),i(function(){return l(m)&&v({inst:m}),d(function(){l(m)&&v({inst:m})})},[d]),a(p),p}function l(d){var f=d.getSnapshot;d=d.value;try{var p=f();return!s(d,p)}catch{return!0}}function c(d,f){return f()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:u;e.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:h})),fu=Ze(((e,t)=>{t.exports=hu()})),pu=Ze((e=>{var t=Cs(),n=fu();function s(c,h){return c===h&&(c!==0||1/c===1/h)||c!==c&&h!==h}var r=typeof Object.is=="function"?Object.is:s,i=n.useSyncExternalStore,o=t.useRef,a=t.useEffect,u=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(c,h,d,f,p){var g=o(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=u(function(){function S(y){if(!C){if(C=!0,w=y,y=f(y),p!==void 0&&m.hasValue){var T=m.value;if(p(T,y))return b=T}return b=y}if(T=b,r(w,y))return T;var _=f(y);return p!==void 0&&p(T,_)?(w=y,T):(w=y,b=_)}var C=!1,w,b,R=d===void 0?null:d;return[function(){return S(h())},R===null?void 0:function(){return S(R())}]},[h,d,f,p]);var v=i(c,g[0],g[1]);return a(function(){m.hasValue=!0,m.value=v},[v]),l(v),v}})),gu=Ze(((e,t)=>{t.exports=pu()})),mu=gu();function vu(e,t){return e===t}function Ie(e,t,n=vu){const s=(0,I.useCallback)(i=>{if(!e)return()=>{};const{unsubscribe:o}=e.subscribe(i);return o},[e]),r=(0,I.useCallback)(()=>e?.get(),[e]);return(0,mu.useSyncExternalStoreWithSelector)(s,r,r,t,n)}var Lr={};function mo(e,t){const n=I.useRef();return s=>{const r=e?.select?e.select(s):s;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=Ne(n.current,r):r}}function ze(e){const t=se(),n=I.useContext(e.from?iu:hn),s=e.from??n,r=t.stores.getMatchStore(s),i=mo(e,t),o=Ie(r,a=>a?i(a):Lr);if(o!==Lr)return o;(e.shouldThrow??!0)&&Ms()}function vo(e){return ze({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function So(e){const{select:t,...n}=e;return ze({...n,select:s=>t?t(s.loaderDeps):s.loaderDeps})}function yo(e){return ze({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function Io(e){return ze({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function js(e){const t=se();return I.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function Gf(e){const t=se(),n=js(),s=I.useRef(null);return As(()=>{s.current!==e&&(n(e),s.current=e)},[t,e,n]),null}function Ro(e){return ze({...e,select:t=>e.select?e.select(t.context):t.context})}function Tn(e){const t=I.useRef(e);return Ee(t.current,e,{ignoreUndefined:!1})||(t.current=e),t.current}function Su(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function yu(e,t,n){if(e?.external)return Yt(e.href,n)?void 0:e.href;if(!Tu(t)&&!(typeof t!="string"||t.indexOf(":")===-1))try{return new URL(t),Yt(t,n)?void 0:t}catch{}}function Iu(e,t,n,s,r,i){if(i)return!1;if(n?.exact){if(!ml(e.pathname,t.pathname,s))return!1}else{const o=en(e.pathname,s),a=en(t.pathname,s);if(!(o.startsWith(a)&&(o.length===a.length||o[a.length]==="/")))return!1}return(n?.includeSearch??!0)&&!Ee(e.search,t.search,{partial:!n?.exact,ignoreUndefined:!n?.explicitUndefined})?!1:n?.includeHash?r&&e.hash===t.hash:!0}function Ru(e,t){const n=se(),s=Xa(t),{activeProps:r,inactiveProps:i,activeOptions:o,to:a,preload:u,preloadDelay:l,preloadIntentProximity:c,hashScrollIntoView:h,replace:d,startTransition:f,resetScroll:p,viewTransition:g,children:m,target:v,disabled:S,style:C,className:w,onClick:b,onBlur:R,onFocus:y,onMouseEnter:T,onMouseLeave:_,onTouchStart:E,ignoreBlocker:x,params:N,search:F,hash:j,state:A,mask:le,reloadDocument:Ks,unsafeRelative:Qs,from:Ws,_fromLocation:Js,...bt}=e,wt=ho(),Sn=Tn(e.search),yn=Tn(e.params),Et=Tn(o),xe=I.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,Sn,yn,e.state,e.mask,e.unsafeRelative]),In=I.useCallback(M=>{const $=n.buildLocation({_fromLocation:M,...xe}),ce=Eu($.maskedLocation?$.maskedLocation.publicHref:$.publicHref,$.maskedLocation?$.maskedLocation.external:$.external,n.history,S),Cn=yu(ce,a,n.protocolAllowlist);return[ce?.href,Cn,Iu(M,$,Et,n.basepath,wt,Cn!==void 0)]},[Et,S,wt,xe,n,a]),[Rn,tt,nt]=Ie(n.stores.location,In,Su),re=nt?Xe(r,{})??Cu:_n,W=nt?_n:Xe(i,{})??_n,Tt=[w,re.className,W.className].filter(Boolean).join(" "),_t=(C||re.style||W.style)&&{...C,...re.style,...W.style},D=I.useRef(!1),O=e.reloadDocument||tt||S?!1:u??n.options.defaultPreload,ue=l??n.options.defaultPreloadDelay??0,J=I.useCallback(()=>{n.preloadRoute(xe).catch(M=>{console.warn(M),console.warn(eu)})},[n,xe]),Re=I.useCallback(M=>{if(!M){An(s);return}if(!(M.isIntersecting??O==="intent")){M.isIntersecting===!1&&An(s);return}if(!ue){J();return}ft.has(s)||ft.set(s,setTimeout(()=>{ft.delete(s),J()},ue))},[J,s,O,ue]);Ja(s,Re,O!=="viewport"),I.useEffect(()=>{D.current||O==="render"&&(J(),D.current=!0)},[J,O]);const st=M=>{const $=M.currentTarget.getAttribute("target"),ce=v!==void 0?v:$;!S&&!(M.metaKey||M.altKey||M.ctrlKey||M.shiftKey)&&!M.defaultPrevented&&(!ce||ce==="_self")&&M.button===0&&(M.preventDefault(),n.navigate({...xe,replace:d,resetScroll:p,hashScrollIntoView:h,startTransition:f,viewTransition:g,ignoreBlocker:x}))};if(tt)return{...bt,ref:s,href:tt,...m&&{children:m},...v&&{target:v},...S&&{disabled:S},...C&&{style:C},...w&&{className:w},...b&&{onClick:b},...R&&{onBlur:R},...y&&{onFocus:y},...T&&{onMouseEnter:T},..._&&{onMouseLeave:_},...E&&{onTouchStart:E}};const z=()=>{O==="intent"&&J()},rt=()=>{O==="intent"&&An(s)};return{...bt,...re,...W,href:Rn,ref:s,onClick:Ve([b,st]),onBlur:Ve([R,rt]),onFocus:Ve([y,Re]),onMouseEnter:Ve([T,Re]),onMouseLeave:Ve([_,rt]),onTouchStart:Ve([E,z]),disabled:!!S,target:v,..._t&&{style:_t},...Tt&&{className:Tt},...S&&bu,...nt&&wu}}var _n={},Cu={className:"active"},bu={role:"link","aria-disabled":!0},wu={"data-status":"active","aria-current":"page"},ft=new WeakMap,An=e=>{clearTimeout(ft.get(e)),ft.delete(e)},Ve=e=>t=>{for(const n of e)if(n){if(t.defaultPrevented)return;n(t)}};function Eu(e,t,n,s){if(!s)return t?{href:e,external:!0}:{href:n.createHref(e)||"/",external:!1}}function Tu(e){if(typeof e!="string")return!1;const t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var Co=I.forwardRef((e,t)=>{const{_asChild:n,...s}=e,{type:r,...i}=Ru(s,t),o=typeof s.children=="function"?s.children({isActive:i["data-status"]==="active"}):s.children;if(!n){const{disabled:a,...u}=i;return I.createElement("a",u,o)}return I.createElement(n,i,o)}),_u=class extends co{constructor(e){super(e),this.useMatch=t=>ze({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>Ro({...t,from:this.id}),this.useSearch=t=>Io({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>yo({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>So({...t,from:this.id}),this.useLoaderData=t=>vo({...t,from:this.id}),this.useNavigate=()=>js({from:this.fullPath}),this.Link=I.forwardRef((t,n)=>(0,L.jsx)(Co,{ref:n,from:this.fullPath,...t}))}};function Au(e){return new _u(e)}var Mu=class extends tu{constructor(e){super(e),this.useMatch=t=>ze({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>Ro({...t,from:this.id}),this.useSearch=t=>Io({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>yo({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>So({...t,from:this.id}),this.useLoaderData=t=>vo({...t,from:this.id}),this.useNavigate=()=>js({from:this.fullPath}),this.Link=I.forwardRef((t,n)=>(0,L.jsx)(Co,{ref:n,from:this.fullPath,...t}))}};function $f(e){return new Mu(e)}function Uf(e){return t=>{const n=Au(t);return n.isRoot=!1,n}}function Bf(e,t){let n,s,r;const i=()=>(n||(r=void 0,n=e().then(a=>{n=void 0,o.preload=void 0,s=a[t??"default"]}).catch(a=>{n=void 0,r=a})),n),o=function(u){if(r){if(el(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(!s)if(ur)ur(i());else throw i();return I.createElement(s,u)};return o.preload=i,o}function xu(e){const t=se(),n=`not-found-${Ie(t.stores.location,s=>s.pathname)}-${Ie(t.stores.status,s=>s)}`;return(0,L.jsx)(Ds,{getResetKey:()=>n,onCatch:(s,r)=>{if(Ye(s))e.onCatch?.(s,r);else throw s},errorComponent:({error:s})=>{if(Ye(s))return e.fallback?.(s);throw s},children:e.children})}function Ou(){return(0,L.jsx)("p",{children:"Not Found"})}function Qe(e){return(0,L.jsx)(L.Fragment,{children:e.children})}function bo(e,t,n){return t.options.notFoundComponent?(0,L.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,L.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,L.jsx)(Ou,{})}function fn(e,t){const n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,L.jsx)(n,{}):null}var Pu=(e,t)=>e[0]===t[0]&&e[1]===t[1],wo=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n==="data-only"||!e.ssr,Eo=I.memo(function({routeId:t}){const n=se();return(0,L.jsx)(ku,{router:n,match:Ie(n.stores.getMatchStore(t),s=>s)})});function ku({router:e,match:t}){const n=e.routesById[t.routeId],s=fn(e,n),r=n.options.errorComponent??e.options.defaultErrorComponent,i=n.options.onCatch??e.options.defaultOnCatch,o=n.isRoot?n.options.notFoundComponent??e.options.notFoundRoute?.options.component:n.options.notFoundComponent,a=t.ssr===!1||t.ssr==="data-only",u=wo(e,n,t.ssr)&&(n.options.wrapInSuspense??s??(n.options.errorComponent?.preload||a))?I.Suspense:Qe,l=r?Ds:Qe,c=o?xu:Qe;return(0,L.jsxs)(n.isRoot?n.options.shellComponent??Qe:Qe,{children:[(0,L.jsx)(hn.Provider,{value:t.routeId,children:(0,L.jsx)(u,{fallback:s,children:(0,L.jsx)(l,{getResetKey:()=>t,errorComponent:r,onCatch:(h,d)=>{if(Ye(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:s,children:(0,L.jsx)(Fr,{match:t})}):(0,L.jsx)(Fr,{match:t})})})})}),null]})}var Fr=I.memo(function({match:t}){const n=se(),s=t.routeId,r=n.routesById[s],i=I.useMemo(()=>{const a=(r.options.remountDeps??n.options.defaultRemountDeps)?.({routeId:s,loaderDeps:t.loaderDeps,params:t._strictParams,search:t._strictSearch});return a?JSON.stringify(a):void 0},[s,t.loaderDeps,t._strictParams,t._strictSearch,r.options.remountDeps,n.options.defaultRemountDeps]),o=I.useMemo(()=>{const a=r.options.component??n.options.defaultComponent;return a?(0,L.jsx)(a,{},i):(0,L.jsx)(Lu,{})},[i,r.options.component,n.options.defaultComponent]);if(t.status==="pending"){if(n.ssr&&!wo(n,r,t.ssr))return o;if(n._tx)throw n._tx[5];return fn(n,r)}if(t.status==="notFound")return bo(n,r,t.error);if(t.status==="error")throw t.error;return o}),Lu=I.memo(function(){const t=se(),n=I.useContext(hn);let s,r,i;{const a=t.stores.getMatchStore(n);[s,r]=Ie(a,u=>[!!u._notFound,u.error],Pu),i=Ie(t.stores.ids,u=>u[u.indexOf(n)+1])}if(s)return bo(t,t.routesById[n],r);if(!i)return null;const o=(0,L.jsx)(Eo,{routeId:i});return n==="__root__"?(0,L.jsx)(I.Suspense,{fallback:fn(t),children:o}):o});function To(e,t){const n=e[1];e.length=0,n?.(t)}function Fu({t:e}){const t=se(),n=t._rendered??=[];return t.startTransition=(s,r)=>new Promise(i=>{To(n,!1),n.push(r,i),e(t),I.startTransition(s)}),As(()=>{const s=t.history.subscribe(t.load);t.updateLatestLocation();const r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(ve(r.publicHref)!==ve(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),s;const o=t.stores.resolvedLocation.get();return o?.href===r.href&&o.state.__TSR_key===r.state.__TSR_key?n.push(t.stores.matches.get(),a=>{a&&t.emit({type:"onRendered",...cn(o,o)})}):t._tx||t.load({sync:!0}).catch(console.error),s},[t,t.history]),null}function Nu(){const e=se(),t=e.routesById[dt],n=fn(e,t),s=e.ssr?Qe:I.Suspense,r=(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(Fu,{t:I.useState()[1]}),(0,L.jsx)(s,{fallback:n,children:(0,L.jsx)(Du,{})})]});return e.options.InnerWrap?(0,L.jsx)(e.options.InnerWrap,{children:r}):r}function Du(){const e=se(),t=e._rendered,n=Ie(e.stores.matches,o=>t[0]??o),s=n[0],r=s?.routeId;As(()=>{t[0]===n&&To(t,!0)},[t,n]);const i=r?(0,L.jsx)(Eo,{routeId:r}):null;return(0,L.jsx)(hn.Provider,{value:r,children:e.options.disableGlobalCatchBoundary?i:(0,L.jsx)(Ds,{getResetKey:()=>s,onCatch:void 0,children:i})})}var ju=e=>({createMutableStore:kr,createReadonlyStore:kr,batch:cu}),Hf=e=>new Gu(e),Gu=class extends Ul{constructor(e){super(e,ju)}};function $u({router:e,children:t,...n}){Ki(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});const s=(0,L.jsx)(fo.Provider,{value:e,children:t});return e.options.Wrap?(0,L.jsx)(e.options.Wrap,{children:s}):s}function zf({router:e,...t}){return(0,L.jsx)($u,{router:e,...t,children:(0,L.jsx)(Nu,{})})}function Vf(e){const t=se();return Ie(t.stores.location,mo(e,t))}function Uu(){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 Bu=/^[a-z][a-z0-9-]{0,63}$/,Hu="x-byok-";function ie(e){return typeof e=="string"&&Bu.test(e)}function Nr(e){if(!ie(e))throw new Error(`Invalid BYOK provider id: ${e}`);return`${Hu}${e}`}function zu(e){if(typeof e!="object"||e===null||!("error"in e))return!1;const t=e.error;return!(typeof t!="object"||t===null||!("type"in t)||t.type!=="byok_missing"||!("provider"in t)||typeof t.provider!="string"||!ie(t.provider)||!("message"in t)||typeof t.message!="string")}var os=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name="ByokMissingError",this.provider=e}},rn=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}},_o=class extends Error{constructor(){super("BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider."),this.name="ByokUnresolvedProviderError"}};function Lt(e){return e.length<=4?"••":e.slice(-4)}var Vu={status:{},locked:!1,prompt:null,storageError:null};function Pe(e){if(!ie(e))throw new Error(`Invalid BYOK provider id: ${e}`);return e}function Ft(e,t){return e instanceof Error&&e.message.length>0?e.message:t}function qu(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[n,s]of Object.entries(e))ie(n)&&typeof s=="string"&&s.length>0&&(t[n]=s);return t}var Ku=class{storage;#t={};#e={};#n;#s=null;#i=!1;#r={};#a={};#l=new Set;#h;#o=null;#u;constructor(e={}){this.storage=e.storage??Uu();for(const t of e.providers??[])t.with?.length&&(this.#a[Pe(t.id)]=t.with.map(n=>Pe(n.id)));this.#n=!!this.storage.unlockable,this.#h=this.#f(),this.#u=this.#m()}ready=()=>this.#u;subscribe=e=>(this.#l.add(e),()=>{this.#l.delete(e)});getSnapshot=()=>this.#h;#f(){return{status:{...this.#e},locked:this.#n,prompt:this.#s,storageError:this.#o}}keys(){return{...this.#t}}request(e,t){this.#s={provider:Pe(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){Pe(e);for(const n of this.#p(e)){const s=this.#t[n];s&&(t[Nr(n)]=s)}return t}for(const[n,s]of Object.entries(this.#t))s&&(t[Nr(n)]=s);return t}async prepare(e){if(await this.#u,this.storage.unlockable&&this.#n&&await this.unlock(),!!e){Pe(e);for(const t of this.#p(e))if(!(this.#t[t]||this.#d(t)))throw this.request(t,"missing"),new rn(t,"missing")}}async update(e,t){await this.#u;let n,s;if(t===void 0){if(!this.#s)throw new Error("byok.update(key) cannot run when prompt is null");n=this.#s.provider,s=e}else n=Pe(e),s=t;if(s=s.trim(),s.length===0)throw new Error("BYOK key must be non-empty");this.storage.unlockable&&this.#n&&await this.unlock();const r=this.#t,i={...this.#e},o=this.#n,a=this.#s,u=this.#o,l={...this.#t,[n]:s};try{await this.storage.save(l)}catch(c){throw this.#t=r,this.#e=i,this.#n=o,this.#s=a,this.#o=u,this.#e[n]={state:"error",masked:Lt(s),message:Ft(c,`Failed to persist ${n} key`)},this.#c(),c}this.#t=l,this.#e[n]={state:"set",masked:Lt(s)},this.#n=!1,this.#s=null,this.#o=null,this.#c()}async clear(e){if(await this.#u,e){Pe(e),this.storage.unlockable&&this.#n&&await this.unlock();const i=this.#t,o={...this.#e},a={...this.#t};delete a[e];try{await this.storage.save(a)}catch(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,n=this.#e,s=this.#n,r=this.#s;try{await this.storage.clear()}catch(i){throw this.#t=t,this.#e=n,this.#n=s,this.#s=r,this.#c(),i}this.#t={},this.#e={},this.#n=!1,this.#s=null,this.#o=null,this.#c()}async unlock(){if(await this.#u,!!this.storage.unlockable)try{const e=Dr(await this.storage.load());this.#t={...e,...this.#t};for(const[t,n]of Object.entries(e)){if(!ie(t)||!n)continue;const s=this.#e[t];(!s||s.state==="locked")&&(this.#e[t]={state:"set",masked:Lt(n)})}this.#n=!1,this.#o=null,this.#c()}catch(e){if(qu(e)){const t=this.#g();if(t)throw this.request(t,"locked"),new rn(t,"locked")}throw this.#o=Ft(e,"Failed to unlock keyring"),this.#c(),e instanceof Error?e:new Error(String(e))}}#g(){if(this.#s&&ie(this.#s.provider))return this.#s.provider;for(const[e,t]of Object.entries(this.#e))if(t?.state==="locked"&&ie(e))return e}async#m(){if(this.storage.unlockable){if(!this.storage.peek)return;try{const e=await this.storage.peek();for(const[t,n]of Object.entries(e))!ie(t)||this.#e[t]||(this.#e[t]={state:"locked",masked:n||"••"});this.#n=Object.keys(e).length>0,this.#o=null,this.#c()}catch(e){this.#o=Ft(e,"Failed to read keyring"),this.#c()}return}try{const e=Dr(await this.storage.load());this.#t={...e,...this.#t};for(const[t,n]of Object.entries(e))!ie(t)||!n||(this.#e[t]={state:"set",masked:Lt(n)});this.#o=null,this.#c()}catch(e){this.#o=Ft(e,"Failed to read keyring"),this.#c()}}#c(){this.#h=this.#f();for(const e of this.#l)e()}};function qf(e={}){return new Ku(e)}var as=class extends Error{missingFeature;constructor(e){super(Qu(e)),this.name="UnsupportedResponseStreamError",this.missingFeature=e}};function Qu(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 Wu(e){if(!e.body)throw new as("Response.body");if(typeof e.body.getReader!="function")throw new as("Response.body.getReader");return e.body.getReader()}function Ju(){if(typeof globalThis.TextDecoder!="function")throw new as("TextDecoder");return new globalThis.TextDecoder}function Xu(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 Yu(e){const t=jr(e.createdAt),n=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:s,...r}=e;return t?{...r,parts:n,createdAt:t}:{...r,parts:n}}function Ao(e){return e.map(Yu)}function Gr(e){return Object.keys(e).length>0?e:void 0}function Mo(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)&&"promptTokens"in e}function Zu(e,t){return Mo(e)?e:Array.isArray(e)?$r(e,t):$r(void 0,t)}function $r(e,t){const n=e?.[0];if(n==null&&t==null)return;const{promptTokensDetails:s,completionTokensDetails:r,...i}=t??{},o=Gr({...n?.cachedInputTokens!==void 0?{cachedTokens:n.cachedInputTokens}:{},...s}),a=Gr({...n?.reasoningTokens!==void 0?{reasoningTokens:n.reasoningTokens}:{},...r});return{promptTokens:n?.inputTokens??0,completionTokens:n?.outputTokens??0,totalTokens:n?.totalTokens??0,...i,...o!==void 0?{promptTokensDetails:o}:{},...a!==void 0?{completionTokensDetails:a}:{}}}function Ur(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function xo(e,t){if(t==null)return e;if(e==null)return{...t};const n={...e,...t};return Ur(e.tanstack)&&Ur(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function U(e){if(e==null)return;const t="metadata"in e?e.metadata:void 0,n=(t!=null&&typeof t=="object"&&!Array.isArray(t)?t:e).tanstack;if(!(n==null||typeof n!="object"||Array.isArray(n)))return n}function Oo(e,t){const n=e.metadata,s=U(e)??{};return{...e,metadata:{...n??{},tanstack:{...s,...t}}}}var Nt=(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})({}),ec=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 de(e,t){return e>>>t|e<<32-t}function tc(e){const t=new TextEncoder().encode(e),n=t.length*8,s=t.length+1,r=s+(56-s%64+64)%64+8,i=new Uint8Array(r);i.set(t),i[t.length]=128;const o=new DataView(i.buffer);o.setUint32(r-8,Math.floor(n/4294967296)),o.setUint32(r-4,n>>>0);let a=1779033703,u=3144134277,l=1013904242,c=2773480762,h=1359893119,d=2600822924,f=528734635,p=1541459225;const g=new Uint32Array(64);for(let v=0;v<r;v+=64){for(let E=0;E<16;E++)g[E]=o.getUint32(v+E*4);for(let E=16;E<64;E++){const x=g[E-15]??0,N=g[E-2]??0,F=de(x,7)^de(x,18)^x>>>3,j=de(N,17)^de(N,19)^N>>>10;g[E]=(g[E-16]??0)+F+(g[E-7]??0)+j>>>0}let S=a,C=u,w=l,b=c,R=h,y=d,T=f,_=p;for(let E=0;E<64;E++){const x=de(R,6)^de(R,11)^de(R,25),N=R&y^~R&T,F=_+x+N+(ec[E]??0)+(g[E]??0)>>>0,j=(de(S,2)^de(S,13)^de(S,22))+(S&C^S&w^C&w)>>>0;_=T,T=y,y=R,R=b+F>>>0,b=w,w=C,C=S,S=F+j>>>0}a=a+S>>>0,u=u+C>>>0,l=l+w>>>0,c=c+b>>>0,h=h+R>>>0,d=d+y>>>0,f=f+T>>>0,p=p+_>>>0}const m=v=>(v>>>0).toString(16).padStart(8,"0");return m(a)+m(u)+m(l)+m(c)+m(h)+m(d)+m(f)+m(p)}function nc(e){return`sha256:${tc(e)}`}function ls(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!="object")throw new TypeError("Interrupt values must be JSON-compatible.");if(t.has(e))throw new TypeError("Interrupt values must not cycle.");if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError("Interrupt values must use plain JSON objects.");t.add(e);let n;if(Array.isArray(e)){const s=[];for(let r=0;r<e.length;r++)s.push(ls(e[r],t));n=`[${s.join(",")}]`}else{const s=e;n=`{${Object.keys(s).sort().map(r=>`${JSON.stringify(r)}:${ls(s[r],t)}`).join(",")}}`}return t.delete(e),n}function $e(e){return ls(e,new WeakSet)}function Ue(e,t=nc){if(typeof e!="string")throw new TypeError("Interrupt digests require canonical JSON text.");return t(e)}function Po(e){e===null||typeof e!="object"||Object.isFrozen(e)||(Object.values(e).forEach(Po),Object.freeze(e))}function B(e){const t=JSON.parse($e(e));return Po(t),t}function sc(e){const t=[...e].sort((r,i)=>r.interruptId.localeCompare(i.interruptId)),n=B(t),s=$e(n);return Object.freeze({resolutions:n,canonicalResolutions:s,fingerprint:Ue(s)})}function Br(e){const t={};for(const[n,s]of Object.entries(e))n!=="$schema"&&(t[n]=s);return t}function ko(e){return(typeof e=="object"||typeof e=="function")&&e!==null}function Ct(e){if(!ko(e)||!("~standard"in e))return!1;const t=e["~standard"];return typeof t!="object"||t===null||!("version"in t)||t.version!==1||!("jsonSchema"in t)||typeof t.jsonSchema!="object"||t.jsonSchema===null||!("input"in t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function Me(e){return ko(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 rc(e){return Object.keys(e).length>0?e:void 0}function Hr(e){if(Array.isArray(e)){const n=e.map(r=>on(r,r.required||[])),s=n.map(r=>r.nullWidening??{});return{schema:n.map(r=>r.schema),itemMap:s.some(r=>Object.keys(r).length>0)?s:void 0}}const t=on(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function on(e,t=[]){const n={...e},s={};if(n.type==="object"&&n.properties){const r={...n.properties},i=Object.keys(r),o={};for(const a of i){const u=r[a];if(!u)continue;const l=!t.includes(a);let c=!1,h;if(u.type==="object"&&u.properties){const d=on(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}:{}})}n.properties=r,n.required=i,n.additionalProperties=!1,Object.keys(o).length>0&&(s.properties=o)}if(n.type==="array"&&n.items){const r=Hr(n.items);n.items=r.schema,r.itemMap&&(s.items=r.itemMap)}return{schema:n,nullWidening:rc(s)}}function ic(e){if(Ct(e)){const t=Br(e["~standard"].jsonSchema.input({target:"draft-07"}));return"properties"in t&&!t.type&&(t.type="object"),t.type==="object"&&!("properties"in t)&&(t.properties={}),t.type==="object"&&!("required"in t)&&(t.required=[]),t}if(Me(e))throw new Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e!="object"?e:Br(e)}function us(e,t={}){if(!e)return;const{forStructuredOutput:n=!1}=t;if(!n&&!Ct(e)&&!Me(e))return e;const s=ic(e);return!s||typeof s!="object"||!n?s:on(s,s.required||[]).schema}var oc=class extends Error{name="StandardSchemaValidationError";issues;constructor(e){super(`Validation failed: ${e.map(t=>t.message||"Validation failed").join(", ")}`),this.issues=e}};function ac(e,t){if(!Me(e))return t;const n=e["~standard"].validate(t);if(n instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!n.issues)return n.value;throw new oc(n.issues)}var lc=new Set(["$schema","$id","$ref","$defs","type","properties","required","additionalProperties","items","oneOf","anyOf","allOf","enum","const","format","minimum","maximum","minLength","maxLength","pattern"]);function Lo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Gs(e){return Lo(e)&&Object.keys(e).some(t=>lc.has(t))}function uc(e){return Me(e)||Ct(e)||Gs(e)}function cc(e){if(!Lo(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>n==="approve"||n==="reject")&&t.every(n=>uc(e[n]))}function dc(e){const t={};for(const[n,s]of Object.entries(e))t[n]=s;return t}function ut(e){if(Me(e)){const t=Ct(e)?dc(e["~standard"].jsonSchema.input({target:"draft-2020-12"})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Gs(e))return{source:e,jsonSchema:e};throw new TypeError("Expected a supported SchemaInput.")}function zr(e){const t={approved:{const:e.approved}},n=["approved"];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push("payload")),{type:"object",properties:t,required:n,additionalProperties:!1}}function hc(e,t){const n=t===void 0?null:ut(t);let s=null,r=null;if(e!==void 0)if(Me(e)||Gs(e))s=ut(e),r=s;else if(cc(e))s=e.approve===void 0?null:ut(e.approve),r=e.reject===void 0?null:ut(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:s,inputSchema:n}),zr({approved:!1,payload:r,inputSchema:null})]},o=$e(i),a=$e({approve:s?.jsonSchema??null,reject:r?.jsonSchema??null});return{branches:{approve:s,reject:r},responseSchema:i,responseSchemaHash:Ue(o),approvalSchemaHash:Ue(a)}}function Vr(e){if(e===void 0)return Ue("undefined");const t=ut(e).jsonSchema??{standardValidator:"unserialized"};return Ue($e(t))}var pn="tanstack:interruptBinding",Fo=pn;function an(e){return e&&typeof e=="object"?e:null}function K(e,t){return typeof e[t]=="string"?e[t]:void 0}function fc(e){const t=e.v;return t===void 0?!0:t===1}function No(e){const t=an(e.metadata),n=t?an(t[Fo]):null;if(!n||K(n,"interruptId")!==e.id||!fc(n))return;const s=K(n,"kind"),r=K(n,"interruptId"),i=K(n,"responseSchemaHash"),o=K(n,"expiresAt");if(!r||i===""||o!==void 0&&!Number.isFinite(Date.parse(o)))return;const a=1;if(s==="generic"){const c=K(n,"definitionId"),h=K(n,"key"),d=n.batchIndex,f=K(n,"payloadSchemaHash");return(c!==void 0||h!==void 0||d!==void 0||f!==void 0)&&(!c||!h||typeof d!="number"||!Number.isInteger(d)||d<0)?void 0:{v:a,kind:s,interruptId:r,...i?{responseSchemaHash:i}:{},...o?{expiresAt:o}:{},...c?{definitionId:c}:{},...h?{key:h}:{},...typeof d=="number"?{batchIndex:d}:{},...f?{payloadSchemaHash:f}:{}}}if(!i)return;const u=K(n,"toolName"),l=K(n,"toolCallId");if(!(!u||!l)){if(s==="client-tool-execution"){const c=K(n,"outputSchemaHash");return c?{v:a,kind:s,interruptId:r,toolName:u,toolCallId:l,outputSchemaHash:c,responseSchemaHash:i,...o?{expiresAt:o}:{}}:void 0}if(s==="tool-approval"){const c=K(n,"inputSchemaHash"),h=K(n,"approvalSchemaHash");return!c||!h?void 0:{v:a,kind:s,interruptId:r,toolName:u,toolCallId:l,originalArgs:n.originalArgs,inputSchemaHash:c,approvalSchemaHash:h,responseSchemaHash:i,...o?{expiresAt:o}:{}}}}}function pc(e){const t=No(e);if(!t)return;const n=an(e.metadata),s=n?an(n[Fo]):null;if(!s)return;const r=K(s,"interruptedRunId"),i=s.generation;if(!(!r||typeof i!="number"||!Number.isInteger(i)||i<0))return{...t,interruptedRunId:r,generation:i}}var gc="tanstack:interruptPayload";function mc(e,t){if(!Ct(e))throw new TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{const n=e["~standard"].jsonSchema.input({target:"draft-07"});if(n===void 0)throw new TypeError("The exported schema is undefined.");if(typeof n=="function")throw new TypeError("The exported schema must not be a function.");if(Array.isArray(n))throw new TypeError("The exported schema must be a plain JSON object.");if(!n||typeof n!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(n)))throw new TypeError("The exported schema must be a plain JSON object.");const s={};for(const[r,i]of Object.entries(n))r!=="$schema"&&(s[r]=i);return{json:s,canonicalJson:$e(s)}}catch(n){throw new TypeError(`${t} could not export compatible JSON Schema: ${n instanceof Error?n.message:String(n)}`)}}function vc(e){return Ue(mc(e,"Interrupt schema").canonicalJson)}var Sc="tanstack:interruptContinuation";function yc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ic(e){return{[Sc]:e}}function Rc(e){const t=No(e);if(t?.kind!=="generic"||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;const n=yc(e.metadata)?e.metadata:void 0,s=n!==void 0&&Object.prototype.hasOwnProperty.call(n,"tanstack:interruptPayload");return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??"",...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{},...t.responseSchemaHash!==void 0?{responseSchemaHash:t.responseSchemaHash}:{},...t.payloadSchemaHash!==void 0?{payloadSchemaHash:t.payloadSchemaHash}:{},...s?{payload:n[gc]}:{}}}var Cc=new Set(["text","image","audio","video","document"]);function bc(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.type!="string"||!Cc.has(t.type))return!1;if(t.type==="text")return typeof t.content=="string";const n=t.source;if(typeof n!="object"||n===null)return!1;const s=n;return typeof s.value!="string"?!1:s.type==="data"?typeof s.mimeType=="string":s.type==="url"}function cs(e){return Array.isArray(e)&&e.length>0&&e.every(bc)}function $s(e){return typeof e=="string"||cs(e)?e:JSON.stringify(e)}function wc(e){const t=e?.metadata;return typeof t=="object"&&t!==null&&t.providerExecuted===!0?t:null}function Do(e){return wc(e)!==null}function Mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ec(e){return e.type==="text"||e.type==="image"||e.type==="audio"||e.type==="video"||e.type==="document"}function Tc(e){try{return JSON.stringify(e)??""}catch{return""}}function qr(e){return typeof e=="string"&&e!==""?e:void 0}function _c(e){if("encryptedValue"in e){const t=qr(e.encryptedValue);if(t!==void 0)return t}return qr(U(e)?.signature)}function jo(e){return e.length===0?null:e.every(t=>t.type==="text")?e.map(t=>t.content).join("")||null:e}function Go(e){return e==null?"":typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.content).join("")}function Ac(e){return Array.isArray(e)?e:Go(e)}function Mc(e){if(!("role"in e)||e.role!=="tool")return e;const t=e,n=U(t)?.toolResult;if(!Mn(n)||"content"in n&&!cs(n.content))return e;const s={...e};if("id"in n||Reflect.deleteProperty(s,"id"),"createdAt"in n||Reflect.deleteProperty(s,"createdAt"),typeof n.id=="string"&&Reflect.set(s,"id",n.id),typeof n.createdAt=="string"){const i=ne(n.createdAt);i&&Reflect.set(s,"createdAt",i)}cs(n.content)&&Reflect.set(s,"content",n.content);const r=Reflect.get(t,"metadata");if(Mn(r)){const i=r.tanstack;if(Mn(i)){const{toolResult:o,...a}=i,u={...r};Object.keys(a).length?u.tanstack=a:delete u.tanstack,Object.keys(u).length?Reflect.set(s,"metadata",u):Reflect.deleteProperty(s,"metadata")}}return s}function ne(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 $o(e){if(e.type!=="tool-result")return e;const t=ne(e.createdAt),{createdAt:n,...s}=e;return t===void 0?s:{...s,createdAt:t}}function Uo(e){return ne(U(e)?.createdAt)}function ds(e){const t=ne(e.createdAt);return t!==void 0?{createdAt:t}:{}}function gn(e){return e.name!==void 0?{name:e.name}:{}}function mn(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 Bo(e,t){if(t.length===0)return e;const n=new Set(e.parts.filter(mn).map(r=>Kr(r))),s=t.filter(r=>!n.has(Kr(r)));return s.length===0?e:{...e,parts:[...e.parts,...s]}}function xc(e){const t=e.parts.filter(mn),n=e.metadata??{},s=U(e),r={};s?.model!==void 0&&(r.model=s.model),s?.signature!==void 0&&(r.signature=s.signature),t.length>0&&(r.uiResources=t);const i={...n};return Object.keys(r).length>0?i.tanstack=r:delete i.tanstack,Object.keys(i).length>0?i:void 0}function Oc(e){return e.role==="system"?[]:e.role!=="assistant"?[Pc(e)]:Lc(e)}function Pc(e){const t=[];for(const n of e.parts)Ec(n)&&t.push(n);return{id:e.id,role:e.role,content:jo(t),...gn(e),...ds(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function Qr(){return{contentParts:[],toolCalls:[]}}function kc(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 Lc(e){const t=[];let n=Qr(),s=[];const r=new Set,i={id:e.id,...gn(e),...ds(e)},o=xc(e),a={...i,...o!==void 0&&{metadata:o}};function u(l=!1){const c=jo(n.contentParts),h=c!==null,d=n.toolCalls.length>0,f=s.length>0;(l||h||d||f)&&(t.push({...a,role:"assistant",content:c,...d&&{toolCalls:n.toolCalls},...f&&{thinking:s},...n.structuredOutput&&{structuredOutput:n.structuredOutput}}),s=[]),n=Qr()}for(const l of e.parts)switch(l.type){case"text":case"image":case"audio":case"video":case"document":n.contentParts.push(l);break;case"tool-call":kc(l)&&n.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},...ds(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)&&(n.toolCalls.some(Do)&&u(),s.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?Tc(l.data):"";c!==""&&(n.contentParts.push({type:"text",content:c}),n.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:$s(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 ln(e,t){const n=[],s=ne(e.createdAt);if(e.role==="assistant"&&e.thinking?.length)for(const a of e.thinking)!a.content&&!a.signature||n.push({type:"thinking",content:a.content,...a.signature&&{signature:a.signature}});const r=e.structuredOutput??Ho(U(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&&n.push({type:"text",content:u})}n.push(r)}else if(e.role==="tool"&&e.toolCallId)n.push({type:"tool-result",toolCallId:e.toolCallId,content:Ac(e.content),state:e.error===void 0?"complete":"error",...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name},...e.metadata!==void 0&&{metadata:e.metadata},...s!==void 0&&{createdAt:s},...e.error!==void 0&&{error:e.error}});else if(Array.isArray(e.content))for(const a of e.content)n.push(a);else{const a=Go(e.content);a&&n.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}n.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||je(),role:e.role==="tool"?"assistant":e.role,parts:n,...gn(e),...s!==void 0&&{createdAt:s},...e.metadata!==void 0&&{metadata:e.metadata}},o=U(e)?.uiResources;return Bo(i,Array.isArray(o)?o.filter(mn):[])}function Fc(e){if("parts"in e)return ke(e,{...e,id:e.id||je()});const t=e.id||je();switch(e.role){case"user":return ke(e,{id:t,role:"user",parts:Nc(e.content)});case"assistant":{const n=U(e),s=n?.toolCallMetadata,r=Ho(n?.structuredOutput),i=e.toolCalls?.map(o=>{const a=s!=null&&typeof s=="object"?s[o.id]:void 0;return a!==void 0?{...o,metadata:a}:o});return ke(e,ln({role:"assistant",content:e.content??null,...gn(e),...i&&{toolCalls:i},...r&&{structuredOutput:r}},t))}case"tool":{e=Mc(e);const n=ne("createdAt"in e?e.createdAt:void 0)??Uo(e);return ke(e,ln({role:"tool",content:e.content,toolCallId:e.toolCallId,..."name"in e&&typeof e.name=="string"?{name:e.name}:{},..."id"in e&&typeof e.id=="string"?{id:e.id}:{},..."metadata"in e&&e.metadata!=null?{metadata:e.metadata}:{},...n!==void 0?{createdAt:n}:{},...e.error!==void 0&&{error:e.error}},t))}case"system":case"developer":return ke(e,{id:t,role:"system",parts:e.content?[{type:"text",content:e.content}]:[]});case"reasoning":{const n=_c(e),s=typeof e.content=="string"?e.content:"";return ke(e,{id:t,role:"assistant",parts:s||n!==void 0?[{type:"thinking",content:s,...n!==void 0?{signature:n}:{}}]:[]})}default:return ke(e,{id:t,role:"assistant",parts:[]})}}function ke(e,t){const n=t.parts.map(l=>$o(l));n!==t.parts&&(t={...t,parts:n});const s="name"in e&&typeof e.name=="string"?e.name:void 0;let r=s!==void 0?{...t,name:s}:t,i;if("metadata"in e){const l=e.metadata;l!=null&&typeof l=="object"&&!Array.isArray(l)&&(i=l,r={...r,metadata:i})}const o=ne(r.createdAt)??(i!==void 0?Uo(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=U(i)?.uiResources,u=Array.isArray(a)?a.filter(mn):[];return Bo(r,u)}function Ho(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 Nc(e){if(typeof e=="string")return e?[{type:"text",content:e}]:[];const t=[];for(const n of e)n.type==="text"?t.push({type:"text",content:n.text}):n.type!=="binary"&&t.push(n);return t}function Dc(e,t){if("parts"in e){const n=e.parts.map(s=>$o(s));return{...e,parts:n,id:e.id||t(),createdAt:ne(e.createdAt)??new Date}}else return{...ln(e,t()),createdAt:ne(e.createdAt)??new Date}}function je(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function Wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xn(e,t,n,s,r=!1){const i=Wr(e)?e:{},o=Wr(i.tanstack)?{...i.tanstack}:{};r&&delete o.uiResources;const a=ne(t),u={...n!==void 0?{id:n}:{},...a&&{createdAt:a.toISOString()},...Array.isArray(s)&&{content:s}},l={...i,tanstack:{...o,toolResult:u}};return Object.keys(l).length?l:void 0}function jc(e,t){const n=[],s=new Set(e.flatMap(o=>"id"in o&&o.id&&o.role!=="tool"?[o.id]:[])),r=t?.includeSnapshotStructuredOutput??!1,i=new Set;for(const o of e)o.role==="assistant"&&o.id!==void 0&&i.add(o.id);for(const o of e){if(!("parts"in o)&&o.role==="tool"&&o.toolCallId){const d=Pn(qc(o.id,o.toolCallId,i),s),f=xn(o.metadata,o.createdAt,o.id,o.content);n.push({role:"tool",id:d,...o.name!==void 0&&{name:o.name},toolCallId:o.toolCallId,content:typeof o.content=="string"?o.content:JSON.stringify(o.content),...o.error!==void 0&&{error:o.error},...f!==void 0&&{metadata:f}});continue}const a="parts"in o?o:ln(o,o.id),u=a.parts;if(s.add(a.id),o.role==="system"){n.push(On(a,"system",{content:u.length>0?hs(u):o.content??""},u,r));continue}if(o.role==="user"){n.push(On(a,"user",{content:u.length>0?Bc(u):o.content??""},u,r));continue}for(const d of u)if(d.type==="thinking"){const f={role:"reasoning",id:zo(Vc(a.id,d),s),content:d.content};d.signature&&(f.encryptedValue=d.signature),n.push(f)}const l=hs(u),c=zc(u);n.push(On(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=Pn(d.id??fs(d.toolCallId),s),p=xn(d.metadata,d.createdAt,d.id,d.content,!0);n.push({role:"tool",id:f,toolCallId:d.toolCallId,...d.name!==void 0&&{name:d.name},content:typeof d.content=="string"?d.content:JSON.stringify(d.content),...d.error!==void 0&&{error:d.error},...p!==void 0&&{metadata:p}})}else if(d.type==="tool-call"){const f=d.approval?.approved;if(h.has(d.id)||d.output===void 0&&(d.state!=="approval-responded"||f===void 0))continue;const p=d.output!==void 0?$s(d.output):JSON.stringify({approved:f,...f&&{pendingExecution:!0},message:f?"User approved this action":"User denied this action"}),g=typeof p=="string"?p:JSON.stringify(p);n.push({role:"tool",id:Pn(fs(d.id),s),toolCallId:d.id,content:g,metadata:xn(void 0,void 0,void 0,p)})}}return n}function On(e,t,n,s,r){const i=Gc(e,s,r),o={id:e.id,...e.name!==void 0&&{name:e.name},...i!==void 0&&{metadata:i}};return t==="system"?{...o,role:t,content:String(n.content??"")}:t==="user"?{...o,role:t,content:n.content??""}:{...o,role:t,...typeof n.content=="string"&&{content:n.content},...n.toolCalls!==void 0&&{toolCalls:n.toolCalls}}}function Gc(e,t,n){const s={...e.metadata??{}},r=U(e),i={};r?.model!==void 0&&(i.model=r.model),r?.signature!==void 0&&(i.signature=r.signature);const o=ne(e.createdAt);o!==void 0&&(i.createdAt=o.toISOString());const a=$c(t,n);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?s.tanstack=i:delete s.tanstack,Object.keys(s).length>0?s:void 0}function $c(e,t){for(const n of e)if(n.type==="structured-output"&&(t||n.status!=="complete"))return Uc(n,t)}function Uc(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 hs(e){const t=[];for(const n of e)n.type==="text"?t.push(n.content):n.type==="structured-output"&&n.status==="complete"&&n.raw!==""&&t.push(n.raw);return t.join("")}function Bc(e){if(!e.some(n=>n.type==="image"||n.type==="audio"||n.type==="video"||n.type==="document"))return hs(e);const t=[];for(const n of e)n.type==="text"?t.push({type:"text",text:n.content}):(n.type==="image"||n.type==="audio"||n.type==="video"||n.type==="document")&&t.push(n);return t}function Hc(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 zc(e){const t=[];for(const n of e)if(n.type==="tool-call"){const s=Hc(n.metadata);t.push({id:n.id,type:"function",function:{name:n.name,arguments:n.arguments},...s!==void 0?{encryptedValue:s}:{}})}return t.length>0?t:void 0}function Vc(e,t){return`${e}-reasoning-${t.id??Kc(t.content)}`}function fs(e){return`tool-${e}`}function Pn(e,t){return zo(e,t)}function zo(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}-${n}`);)n++;const s=`${e}-${n}`;return t.add(s),s}function qc(e,t,n){const s=fs(t);return e===void 0||n.has(e)?s:e}function Kc(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function Qc(e){if((e.type===Nt.RUN_FINISHED||e.type===Nt.RUN_ERROR)&&(Array.isArray(e.usage)||Mo(e.usage))){const t=Zu(e.usage,U(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===Nt.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===Nt.TOOL_CALL_END&&e.input===void 0){const t=U(e)?.input;t!==void 0&&(e.input=t)}return e}function Vo(e){Qc(e);const t=U(e),n=e;if(t==null)return n;for(const[s,r]of Object.entries(t))s==="usage"||s==="interruptErrors"||n[s]===void 0&&r!==void 0&&(n[s]=r);return t.interruptErrors!==void 0&&(n["tanstack:interruptErrors"]=t.interruptErrors),n}function Jr(e){return typeof e=="string"&&e!==""?e:void 0}function qo(e){if("runId"in e){const t=Jr(e.runId);if(t!==void 0)return t}return Jr(U(e)?.runId)}var Xr=Ze((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})),Wc=Ze((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]})),n=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 s=Xr();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return s.Allow}}),n(Xr(),e);var r=class extends Error{};e.PartialJSON=r;var i=class extends Error{};e.MalformedJSON=i;function o(l,c=s.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=b=>{throw new r(`${b} at position ${d}`)},p=b=>{throw new i(`${b} at position ${d}`)},g=()=>(w(),d>=h&&f("Unexpected end of input"),l[d]==='"'?m():l[d]==="{"?v():l[d]==="["?S():l.substring(d,d+4)==="null"||s.Allow.NULL&c&&h-d<4&&"null".startsWith(l.substring(d))?(d+=4,null):l.substring(d,d+4)==="true"||s.Allow.BOOL&c&&h-d<4&&"true".startsWith(l.substring(d))?(d+=4,!0):l.substring(d,d+5)==="false"||s.Allow.BOOL&c&&h-d<5&&"false".startsWith(l.substring(d))?(d+=5,!1):l.substring(d,d+8)==="Infinity"||s.Allow.INFINITY&c&&h-d<8&&"Infinity".startsWith(l.substring(d))?(d+=8,1/0):l.substring(d,d+9)==="-Infinity"||s.Allow._INFINITY&c&&1<h-d&&h-d<9&&"-Infinity".startsWith(l.substring(d))?(d+=9,-1/0):l.substring(d,d+3)==="NaN"||s.Allow.NAN&c&&h-d<3&&"NaN".startsWith(l.substring(d))?(d+=3,NaN):C()),m=()=>{const b=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(b,++d-Number(R)))}catch(y){p(String(y))}else if(s.Allow.STR&c)try{return JSON.parse(l.substring(b,d-Number(R))+'"')}catch{return JSON.parse(l.substring(b,l.lastIndexOf("\\"))+'"')}f("Unterminated string literal")},v=()=>{d++,w();const b={};try{for(;l[d]!=="}";){if(w(),d>=h&&s.Allow.OBJ&c)return b;const R=m();w(),d++;try{b[R]=g()}catch(y){if(s.Allow.OBJ&c)return b;throw y}w(),l[d]===","&&d++}}catch{if(s.Allow.OBJ&c)return b;f("Expected '}' at end of object")}return d++,b},S=()=>{d++;const b=[];try{for(;l[d]!=="]";)b.push(g()),w(),l[d]===","&&d++}catch{if(s.Allow.ARR&c)return b;f("Expected ']' at end of array")}return d++,b},C=()=>{if(d===0){l==="-"&&p("Not sure what '-' is");try{return JSON.parse(l)}catch(R){if(s.Allow.NUM&c)try{return JSON.parse(l.substring(0,l.lastIndexOf("e")))}catch{}p(String(R))}}const b=d;for(l[d]==="-"&&d++;l[d]&&",]}".indexOf(l[d])===-1;)d++;d==h&&!(s.Allow.NUM&c)&&f("Unterminated number literal");try{return JSON.parse(l.substring(b,d))}catch{l.substring(b,d)==="-"&&f("Not sure what '-' is");try{return JSON.parse(l.substring(b,l.lastIndexOf("e")))}catch(y){p(String(y))}}},w=()=>{for(;d<h&&`
|
|
2
|
+
\r `.includes(l[d]);)d++};return g()},u=o;e.parse=u})),Jc=Wc(),Xc=class{parse(e){if(!(!e||e.trim()===""))try{return(0,Jc.parse)(e)}catch{return}}},Ko=new Xc;function Yc(e){return Ko.parse(e)}var Zc=class{shouldEmit(e,t){return!0}};function ed(e){const t=new Error(e.message||e.error?.message||"An error occurred"),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}function td(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type==="text"?r[r.length-1]={type:"text",content:n}:r.push({type:"text",content:n}),{...s,parts:r}})}function Dt(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.find(l=>l.type==="tool-call"&&l.id===n.id),o=n.metadata??i?.metadata,a=n.input??i?.input,u={type:"tool-call",id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...a!==void 0&&{input:a},...o!==void 0&&{metadata:o}};return i?r[r.indexOf(i)]=u:r.push(u),{...s,parts:r}})}function Yr(e,t,n,s,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===n),l={type:"tool-result",toolCallId:n,content:s,state:r,...i&&{error:i}};return u>=0?a[u]=l:a.push(l),{...o,parts:a}})}function Zr(e,t,n,s){return e.map(r=>{if(r.id!==t)return r;const i=[...r.parts],o=i.find(a=>a.type==="tool-call"&&a.id===n);if(o){const a=i.indexOf(o);i[a]={...o,state:"approval-requested",approval:{id:s,needsApproval:!0}}}return{...r,parts:i}})}function ei(e,t,n,s,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}:n,state:s??(r?"error":"complete")}}return{...i,parts:o}})}function nd(e,t,n){return e.map(s=>{const r=[...s.parts],i=r.find(o=>o.type==="tool-call"&&o.approval?.id===t);if(i&&i.approval){const o=r.indexOf(i);r[o]={...i,approval:{...i.approval,approved:n},state:"approval-responded"}}return{...s,parts:r}})}function sd(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.findIndex(h=>h.type==="structured-output"),o=i>=0?r[i]:null,a=(o?.raw??"")+n,u=Yc(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),{...s,parts:r}})}function rd(e,t,n,s,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(h=>h.type==="structured-output"),u=a>=0?o[a].raw:"";let l=s||u;if(l===""&&n!==void 0)try{l=JSON.stringify(n)}catch{}const c={type:"structured-output",status:"complete",data:n,partial:n,raw:l,...r!==void 0?{reasoning:r}:{}};return a>=0?o[a]=c:o.push(c),{...i,parts:o}})}function ti(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.findIndex(a=>a.type==="structured-output");if(i<0)return r.push({type:"structured-output",status:"error",raw:"",errorMessage:n}),{...s,parts:r};const o=r[i];return o.status==="complete"?s:(r[i]={...o,status:"error",errorMessage:n},{...s,parts:r})})}function kn(e,t,n,s,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(l=>l.type==="thinking"&&l.stepId===n),u={type:"thinking",content:s,stepId:n,...r&&{signature:r}};return a>=0?o[a]=u:o.push(u),{...i,parts:o}})}var id=12;function od(e){return e.some(t=>{const n=t.metadata;if(!n||typeof n!="object"||Array.isArray(n))return!1;const s=n[pn];return s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.kind==="generic"})}var ad=class Qo{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 Zc,this.events=t.events||{},this.jsonParser=t.jsonParser||Ko,this.recordingEnabled=t.recording??!1,t.initialMessages&&(this.messages=[...t.initialMessages])}setMessages(t){this.messages=[...t],this.emitMessagesChange()}addUserMessage(t,n,s){const r=typeof t=="string"?[{type:"text",content:t}]:t.map(o=>o),i={id:n??je(),role:"user",parts:r,createdAt:new Date,...s!=null?{metadata:s}:{}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(t){this.prepareAssistantMessage();const{messageId:n}=this.ensureAssistantMessage(t);return this.pendingManualMessageId=n,n}getCurrentAssistantMessageId(){let t=null;for(const[n,s]of this.messageStates)s.role==="assistant"&&(t=n);return t}addToolResult(t,n,s){const r=this.messages.find(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,n,s?"error":void 0,s);const o=$s(n),a=s?"error":"complete";i=Yr(i,r.id,t,o,a,s),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(t,n){this.messages=nd(this.messages,t,n),this.emitMessagesChange()}toModelMessages(){const t=[];for(const n of this.messages)t.push(...Oc(n));return t}getMessages(){return this.messages}areAllToolsComplete(){const t=this.messages.findLast(r=>r.role==="assistant");if(!t)return!0;const n=t.parts.filter(r=>r.type==="tool-call");if(n.length===0)return!0;const s=new Set(t.parts.filter(r=>r.type==="tool-result").map(r=>r.toolCallId));return n.every(r=>r.state==="complete"||r.state==="approval-responded"||r.output!==void 0&&!r.approval||s.has(r.id)||Do(r))}removeMessagesAfter(t){const n=new Set(this.messages.slice(0,t+1).map(s=>s.id));for(const s of this.structuredMessageIds)n.has(s)||this.structuredMessageIds.delete(s);for(const s of this.structuredOutputUpdateBatches.keys())n.has(s)||this.structuredOutputUpdateBatches.delete(s);for(const s of this.messageStates.keys())n.has(s)||this.messageStates.delete(s);for(const[s,r]of this.toolCallToMessage)n.has(r)||this.toolCallToMessage.delete(s);for(const s of this.activeMessageIds)n.has(s)||this.activeMessageIds.delete(s);this.messages=this.messages.slice(0,t+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(t){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(const n of t)this.processChunk(n);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(t){switch(this.recording&&this.recording.chunks.push({chunk:t,timestamp:Date.now(),index:this.recording.chunks.length}),t.type){case"TEXT_MESSAGE_START":this.handleTextMessageStartEvent(t);break;case"TEXT_MESSAGE_CONTENT":this.handleTextMessageContentEvent(t);break;case"TEXT_MESSAGE_END":this.handleTextMessageEndEvent(t);break;case"TOOL_CALL_START":this.handleToolCallStartEvent(t);break;case"TOOL_CALL_ARGS":this.handleToolCallArgsEvent(t);break;case"TOOL_CALL_END":this.handleToolCallEndEvent(t);break;case"RUN_FINISHED":this.handleRunFinishedEvent(t);break;case"RUN_ERROR":this.handleRunErrorEvent(t);break;case"STEP_FINISHED":this.handleStepFinishedEvent(t);break;case"MESSAGES_SNAPSHOT":this.handleMessagesSnapshotEvent(t);break;case"CUSTOM":this.handleCustomEvent(t);break;case"RUN_STARTED":this.handleRunStartedEvent(t);break;case"REASONING_START":case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"REASONING_MESSAGE_CONTENT":this.handleReasoningMessageContentEvent(t);break;case"REASONING_ENCRYPTED_VALUE":this.handleReasoningEncryptedValueEvent(t);break;case"TOOL_CALL_RESULT":this.handleToolCallResultEvent(t);break;case"STEP_STARTED":this.handleStepStartedEvent(t)}}createMessageState(t,n){const s={id:t,role:n,totalTextContent:"",currentSegmentText:"",lastEmittedText:"",hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(t,s),s}getMessageState(t){return this.messageStates.get(t)}consumePendingThinkingStep(t){if(!this.pendingThinkingStepId)return;const n=this.pendingThinkingStepId;t.currentThinkingStepId=n,t.thinkingSteps.has(n)||(t.thinkingSteps.set(n,""),t.thinkingStepOrder.push(n)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){const t=Array.from(this.activeMessageIds).reverse();for(const n of t){const s=this.messageStates.get(n);if(s&&s.role==="assistant")return n}for(const[n,s]of[...this.messageStates].reverse())if(s.role==="assistant")return n;return null}resumeAssistantState(t,n){this.activeMessageIds.add(t),(n.isComplete||this.isDone)&&(n.isComplete=!1,this.isDone=!1)}ensureAssistantMessage(t){if(t){const o=this.getMessageState(t);if(o)return this.resumeAssistantState(t,o),{messageId:t,state:o}}const n=this.getActiveAssistantMessageId();if(n){const o=this.getMessageState(n);if(o)return this.resumeAssistantState(n,o),{messageId:n,state:o}}if(t){const o=this.messages.find(a=>a.id===t);if(o){const a=this.createMessageState(t,o.role);this.activeMessageIds.add(t);const 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 s=t||je(),r={id:s,role:"assistant",parts:[],createdAt:new Date};this.messages=[...this.messages,r];const i=this.createMessageState(s,"assistant");return this.activeMessageIds.add(s),this.pendingManualMessageId=s,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:s,state:i}}mergeMessageMetadata(t,n){if(n==null||typeof n!="object"||Array.isArray(n))return;const s=this.messages.find(c=>c.id===t);if(!s)return;const r=n,i=U(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=xo(s.metadata,o),u=ne(U(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:n,role:s}=t,r=s==="user"||s==="system"?s:"assistant";if(this.pendingManualMessageId){const o=this.pendingManualMessageId;if(this.pendingManualMessageId=null,o!==n){this.messages=this.messages.map(l=>l.id===o?{...l,id:n}:l);const u=this.messageStates.get(o);u&&(u.id=n,this.messageStates.delete(o),this.messageStates.set(n,u)),this.activeMessageIds.delete(o),this.activeMessageIds.add(n);for(const[l,c]of this.toolCallToMessage)c===o&&this.toolCallToMessage.set(l,n)}let a=this.messageStates.get(n);a?a.hasToolCallsSinceTextStart&&(a.currentSegmentText!==a.lastEmittedText&&this.emitTextUpdateForMessage(n),a.currentSegmentText="",a.lastEmittedText="",a.hasToolCallsSinceTextStart=!1):(a=this.createMessageState(n,r),this.activeMessageIds.add(n)),this.mergeMessageMetadata(n,t.metadata),this.emitMessagesChange();return}if(this.messages.find(o=>o.id===n)){this.activeMessageIds.add(n);const o=this.messageStates.get(n);o?o.hasToolCallsSinceTextStart&&(o.currentSegmentText!==o.lastEmittedText&&this.emitTextUpdateForMessage(n),o.currentSegmentText="",o.lastEmittedText="",o.hasToolCallsSinceTextStart=!1):this.createMessageState(n,r),this.mergeMessageMetadata(n,t.metadata);return}const i={id:n,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(n,r),this.activeMessageIds.add(n),this.mergeMessageMetadata(n,t.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(t){const{messageId:n}=t;this.mergeMessageMetadata(n,t.metadata);const s=this.getMessageState(n);s&&(s.isComplete||s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(n))}handleMessagesSnapshotEvent(t){this.resetStreamState();const n=this.messages,s=new Map(n.map(i=>[i.id,i])),r=this.mergeReasoningFanOut(t.messages.map(Fc));this.messages=this.reconcileSnapshotToolCalls(r,n).map(i=>{if(i.metadata!=null)return i;const o=s.get(i.id);return o?.metadata==null?i:{...i,metadata:o.metadata}}),this.emitMessagesChange()}mergeReasoningFanOut(t){const n=[];let s=[];const r=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=()=>{n.push(...s),s=[]};for(const u of t){if(i(u)){s.push(u);continue}if(u.role==="assistant"&&s.length>0&&!o(u)){n.push({...u,parts:[...s.flatMap(r),...u.parts]}),s=[];continue}a(),n.push(u)}return a(),n}reconcileSnapshotToolCalls(t,n){const s=new Map;for(const o of n)for(const a of o.parts)a.type==="tool-call"&&s.set(a.id,a);const r=new Set;for(const o of t)for(const a of o.parts)a.type==="tool-call"&&r.add(a.id);const i=[];for(const o of t){const a=o.parts.filter(h=>h.type==="tool-result"),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=s.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,s)}enrichSnapshotToolCallsFromResults(t,n){const s=new Map;for(const r of t)for(const i of r.parts)i.type==="tool-result"&&s.set(i.toolCallId,i);return t.map(r=>{const i=r.parts.map(o=>{if(o.type!=="tool-call")return o;const a=n.get(o.id),u=s.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:n,state:s}=this.ensureAssistantMessage(t.messageId);if(this.mergeMessageMetadata(n,t.metadata),this.structuredMessageIds.has(n)){const c=t.delta||"";c!==""&&(this.messages=sd(this.messages,n,c),s.totalTextContent+=c,this.queueStructuredOutputUpdate(n,c),this.emitMessagesChange());return}const r=s.currentSegmentText;s.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(t,r)&&(r!==s.lastEmittedText&&this.emitTextUpdateForMessage(n),s.currentSegmentText="",s.lastEmittedText="",s.hasToolCallsSinceTextStart=!1),s.hasToolCallsSinceTextStart=!1;const i=s.currentSegmentText,o=t.delta||"",a=o!==""?i+o:i,u=a.slice(i.length);s.currentSegmentText=a,s.totalTextContent+=u;const l=t.delta||"";this.chunkStrategy.shouldEmit(l,s.currentSegmentText)&&s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(n)}handleToolCallStartEvent(t){const n=t.parentMessageId??this.getActiveAssistantMessageId(),{messageId:s,state:r}=this.ensureAssistantMessage(n??void 0);r.hasToolCallsSinceTextStart=!0;const i=t.toolCallId;if(!r.toolCalls.get(i)){const o="awaiting-input",a=t.toolCallName,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,s),this.messages=Dt(this.messages,s,{id:t.toolCallId,name:a,arguments:"",state:o,...u!==void 0&&{metadata:u}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(s,t.toolCallId,o,"")}}handleToolCallArgsEvent(t){const n=t.toolCallId,s=this.toolCallToMessage.get(n);if(!s)return;const r=this.getMessageState(s);if(!r)return;const i=r.toolCalls.get(n);if(!i)return;const o=i.state==="awaiting-input";i.arguments+=t.delta||"",o&&t.delta&&(i.state="input-streaming"),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=Dt(this.messages,s,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(s,i.id,i.state,i.arguments)}handleToolCallEndEvent(t){const n=this.toolCallToMessage.get(t.toolCallId);if(!n)return;const s=this.getMessageState(n);if(!s)return;const r=t.input!==void 0?t.input:U(t)?.input,i=s.toolCalls.get(t.toolCallId);if(i&&i.state!=="input-complete"){if(r!==void 0&&!i.arguments)try{i.arguments=JSON.stringify(r)}catch{}const o=s.toolCallOrder.indexOf(t.toolCallId);this.completeToolCall(n,o,i),r!==void 0&&(i.parsedArguments=r,this.messages=Dt(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:"input-complete",input:r,...i.metadata!==void 0&&{metadata:i.metadata}}),this.emitMessagesChange())}}extractToolResultError(t){return t&&typeof t=="object"&&"error"in t&&typeof t.error=="string"?t.error:typeof t=="string"?t:"Tool execution failed"}handleToolCallResultEvent(t){const n=this.toolCallToMessage.get(t.toolCallId)??this.messages.find(o=>o.parts.some(a=>a.type==="tool-call"&&a.id===t.toolCallId))?.id;if(!n)return;const s=t.state==="output-error"||U(t)?.state==="output-error";let r;try{r=JSON.parse(t.content)}catch{r=t.content}this.messages=ei(this.messages,t.toolCallId,r,s?"error":void 0);const i=s?"error":"complete";this.messages=Yr(this.messages,n,t.toolCallId,t.content,i,i==="error"?this.extractToolResultError(r):void 0),this.emitMessagesChange()}handleRunStartedEvent(t){this.activeRuns.add(t.runId)}handleRunFinishedEvent(t){const n=t;if(this.finishReason=n.finishReason!==void 0?n.finishReason:U(t)?.finishReason??null,this.activeRuns.delete(t.runId),t.outcome?.type==="interrupt"&&this.handleInterrupts(t.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason==="tool_calls"&&t.outcome?.type!=="interrupt")return;this.isDone=!0,this.finalizeStream()}}handleInterrupts(t){const n=od(t);for(const s of t){const r=s.metadata&&typeof s.metadata=="object"?s.metadata:{},i=typeof r.kind=="string"?r.kind:void 0,o=s.toolCallId;if(!o)continue;const a=typeof r.toolName=="string"?r.toolName:this.findToolCallName(o),u=Object.hasOwn(r,"input")?r.input:{};if(i==="approval"||s.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,s.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:o,toolName:a,input:u,approvalId:s.id});continue}if(i==="client_tool"||s.reason==="client_tool_input"){if(n)continue;this.events.onToolCall?.({toolCallId:o,toolName:a,input:u})}}}findToolCallName(t){for(const n of this.messageStates.values()){const s=n.toolCalls.get(t);if(s)return s.name}return""}handleRunErrorEvent(t){this.hasError=!0;const n=qo(t);n?this.activeRuns.delete(n):this.activeRuns.clear();const{messageId:s}=this.ensureAssistantMessage(),r=t.message||"An error occurred";t.message||console.error("[StreamProcessor] RUN_ERROR with no message; original chunk:",t),this.structuredMessageIds.has(s)&&(this.flushStructuredOutputUpdate(s),this.messages=ti(this.messages,s,r),this.structuredMessageIds.delete(s),this.emitStructuredOutputChange(s,"error"),this.emitMessagesChange()),this.events.onError?.(ed(t))}handleStepStartedEvent(t){const n=t.stepName||je(),s=this.getActiveAssistantMessageId();if(s){const r=this.getMessageState(s);if(r){r.currentThinkingStepId=n,r.thinkingSteps.has(n)||(r.thinkingSteps.set(n,""),r.thinkingStepOrder.push(n)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=n}handleStepFinishedEvent(t){const n=t,s=n.signature;if(!s)return;const{messageId:r,state:i}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),o=i.currentThinkingStepId??n.stepId;if(!o)return;const a=i.thinkingSteps.get(o);a!==void 0&&(i.thinkingStepSignatures.set(o,s),this.messages=kn(this.messages,r,o,a,s),this.emitMessagesChange())}handleReasoningMessageContentEvent(t){const{messageId:n,state:s}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);s.hasSeenReasoningEvents=!0;const r=t.delta||"";this.consumePendingThinkingStep(s);const i=s.currentThinkingStepId??t.messageId;s.thinkingSteps.has(i)||(s.thinkingSteps.set(i,""),s.thinkingStepOrder.push(i),s.currentThinkingStepId=i);const o=(s.thinkingSteps.get(i)??"")+r;s.thinkingSteps.set(i,o),this.messages=kn(this.messages,n,i,o,s.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(n,i,o)}handleReasoningEncryptedValueEvent(t){const n=t.encryptedValue;if(typeof n!="string"||n==="")return;if(t.subtype==="tool-call"){this.attachToolCallSignature(t.entityId,n);return}const{messageId:s,state:r}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),i=r.currentThinkingStepId??t.entityId;r.thinkingStepSignatures.set(i,n);const o=r.thinkingSteps.get(i)??"";r.thinkingSteps.has(i)||(r.thinkingSteps.set(i,o),r.thinkingStepOrder.push(i)),this.messages=kn(this.messages,s,i,o,n),this.emitMessagesChange()}attachToolCallSignature(t,n){this.messages=this.messages.map(s=>{let r=!1;const i=s.parts.map(o=>o.type!=="tool-call"||o.id!==t?o:(r=!0,{...o,metadata:{...o.metadata!=null&&typeof o.metadata=="object"?o.metadata:{},thoughtSignature:n}}));return r?{...s,parts:i}:s});for(const s of this.messageStates.values()){const r=s.toolCalls.get(t);r&&(r.metadata={...r.metadata??{},thoughtSignature:n})}this.emitMessagesChange()}handleCustomEvent(t){const n=this.getActiveAssistantMessageId();if(t.name==="structured-output.start"&&t.value){const s=t.value,{messageId:r}=this.ensureAssistantMessage(s.messageId??n??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:"start",messageId:r,status:"streaming",raw:""}));return}if(t.name==="structured-output.complete"&&t.value){const s=t.value,{messageId:r}=this.ensureAssistantMessage(s.messageId??n??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=rd(this.messages,r,s.object,s.raw??"",s.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,"complete"),this.emitMessagesChange())}if(t.name==="tool-input-available"&&t.value){const{toolCallId:s,toolName:r,input:i}=t.value;this.events.onToolCall?.({toolCallId:s,toolName:r,input:i});return}if(t.name==="approval-requested"&&t.value){const{toolCallId:s,toolName:r,input:i,approval:o}=t.value,a=n??this.toolCallToMessage.get(s);a&&(this.messages=Zr(this.messages,a,s,o.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:s,toolName:r,input:i,approvalId:o.id});return}if(t.name==="ui-resource"&&t.value){const s=t.value,r=this.toolCallToMessage.get(s.toolCallId)??n;if(r){const i={type:"ui-resource",resource:s.resource,toolCallId:s.toolCallId,toolName:s.toolName,...s.serverId!==void 0&&{serverId:s.serverId},...s.meta!==void 0&&{meta:s.meta}};this.messages=this.messages.map(o=>o.id===r?{...o,parts:[...o.parts,i]}:o),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${s.toolCallId}" (toolName "${s.toolName}")`);return}if(this.events.onCustomEvent){const s=t.value&&typeof t.value=="object"?t.value.toolCallId:void 0;this.events.onCustomEvent(t.name,t.value,{toolCallId:s})}}isNewTextSegment(t,n){return!0}completeAllToolCalls(){for(const t of this.activeMessageIds)this.completeAllToolCallsForMessage(t)}completeAllToolCallsForMessage(t){const n=this.getMessageState(t);n&&n.toolCalls.forEach((s,r)=>{if(s.state!=="input-complete"){const i=n.toolCallOrder.indexOf(r);this.completeToolCall(t,i,s)}})}completeToolCall(t,n,s){s.state="input-complete";let r=!1;try{s.parsedArguments=JSON.parse(s.arguments),r=!0}catch{s.parsedArguments=void 0}this.isToolCallPartErrored(s.id)||this.isToolCallPartAwaitingUserAction(s.id)||(this.messages=Dt(this.messages,t,{id:s.id,name:s.name,arguments:s.arguments,state:"input-complete",...r&&{input:s.parsedArguments},...s.metadata!==void 0&&{metadata:s.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(t,s.id,"input-complete",s.arguments))}isToolCallPartAwaitingUserAction(t){return this.messages.some(n=>n.parts?.some(s=>s.type==="tool-call"&&s.id===t&&(s.state==="approval-requested"||s.state==="approval-responded")))}isToolCallPartErrored(t){return this.messages.some(n=>n.parts?.some(s=>s.type==="tool-call"&&s.id===t&&s.state==="error"))}emitTextUpdateForMessage(t){const n=this.getMessageState(t);n&&(n.lastEmittedText=n.currentSegmentText,this.messages=td(this.messages,t,n.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(t,n.currentSegmentText))}queueStructuredOutputUpdate(t,n){const s=this.structuredOutputUpdateBatches.get(t),r={delta:`${s?.delta??""}${n}`,chunkCount:(s?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(t,r),r.chunkCount>=id&&this.flushStructuredOutputUpdate(t)}flushStructuredOutputUpdate(t){const n=this.structuredOutputUpdateBatches.get(t);!n||n.chunkCount===0||(this.structuredOutputUpdateBatches.delete(t),this.emitStructuredOutputChange(t,"update",n.delta))}emitStructuredOutputChange(t,n,s){const r=this.messages.find(i=>i.id===t)?.parts.find(i=>i.type==="structured-output");r&&this.events.onStructuredOutputChange?.({phase:n,messageId:t,status:r.status,raw:r.raw,...r.partial!==void 0?{partial:r.partial}:{},...r.data!==void 0?{data:r.data}:{},...r.reasoning!==void 0?{reasoning:r.reasoning}:{},...r.errorMessage!==void 0?{errorMessage:r.errorMessage}:{},...s!==void 0?{delta:s}:{}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;let t;for(const n of this.activeMessageIds){const s=this.getMessageState(n);if(!s)continue;this.completeAllToolCallsForMessage(n),s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(n),s.isComplete=!0;const r=this.messages.find(i=>i.id===n);r&&r.role==="assistant"&&(t=r)}for(const n of this.structuredMessageIds)this.flushStructuredOutputUpdate(n),this.messages=ti(this.messages,n,"Stream ended without structured-output.complete"),this.emitStructuredOutputChange(n,"error");if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),t&&!this.hasError&&this.isWhitespaceOnlyMessage(t)){this.messages=this.messages.filter(n=>n.id!==t.id),this.emitMessagesChange();return}t&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(t))}getCompletedToolCalls(){const t=[];for(const n of this.messageStates.values())for(const s of n.toolCalls.values())s.state==="input-complete"&&t.push({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments},...s.metadata!==void 0&&{metadata:s.metadata}});return t}getResult(){const t=this.getCompletedToolCalls();let n="",s="";for(const r of this.messageStates.values()){n+=r.totalTextContent;for(const i of r.thinkingStepOrder)s+=r.thinkingSteps.get(i)??""}return{content:n,thinking:s||void 0,toolCalls:t.length>0?t:void 0,finishReason:this.finishReason}}getState(){let t="",n="";const s=new Map,r=[];for(const i of this.messageStates.values()){t+=i.totalTextContent;for(const o of i.thinkingStepOrder)n+=i.thinkingSteps.get(o)??"";for(const[o,a]of i.toolCalls)s.set(o,a);r.push(...i.toolCallOrder)}return{content:t,thinking:n,toolCalls:s,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:"1.0",timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.streamEndEmitted=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(t){return t.parts.length===0?!1:t.parts.every(n=>n.type==="text"&&n.content.trim()==="")}static async replay(t,n){return new Qo(n).process(ld(t))}};function ld(e){return{async*[Symbol.asyncIterator](){for(const{chunk:t}of e.chunks)yield t}}}var ps=(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})({}),Wo=new WeakMap;function te(e){return Wo.get(e)??qo(e)}var Jo=class extends Error{constructor(){super("Stream ended with unterminated trailing data — connection was likely cut short."),this.name="StreamTruncatedError"}},Us=class extends Error{constructor(e){super("Stream response body read failed",{cause:e}),this.name="StreamReadError"}},ud=class extends Error{constructor(){super("Durable run ended without a terminal event and could not resume — the run did not complete."),this.name="DurableStreamIncompleteError"}},cd=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name="StreamReconnectLimitError"}};function dd(e){const t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw new Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function hd(e){const t=dd(e),n=new Set;let s,r=0;return{get lastEventId(){return s},note(i){return i===void 0?"new":i===""?(s=void 0,n.clear(),"reset"):n.has(i)?"duplicate":(n.add(i),s=i,"new")},async waitBeforeReconnect(i,o){if(i)r=0;else if(r+=1,r>t.maxAttempts)throw new cd(t.maxAttempts);await fd(t.delayMs,o)}}}function fd(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{const s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}function ni(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function jt(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 at(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((n,s)=>{t[s]=n}),t}return e}var pd="X-Run-Id";function gd(e){return e===void 0?{}:{[pd]:e}}function Bs(e,t){const n=e.indexOf("#"),s=n===-1?"":e.slice(n),r=n===-1?e:e.slice(0,n),i=r.indexOf("?"),o=i===-1?r:r.slice(0,i),a=new URLSearchParams(i===-1?"":r.slice(i+1));for(const[l,c]of Object.entries(t))a.set(l,c);const u=a.toString();return`${o}${u.length===0?"":`?${u}`}${s}`}async function*md(e,t){try{const n=Ju();let s="";for(;!t?.aborted;){let r;try{r=await e.read()}catch(u){if(t?.aborted)return;throw new Us(u)}const{done:i,value:o}=r;if(i)break;s+=n.decode(o,{stream:!0});const a=s.split(`
|
|
3
|
+
`);s=a.pop()||"";for(const u of a){const l=u.endsWith("\r")?u.slice(0,-1):u;l.trim()&&(yield l)}}if(s+=n.decode(),s.trim()&&!t?.aborted)throw new Jo}finally{e.releaseLock()}}function vd(e){return Vo(e)}function Sd(e){const t=U(e)?.model;if(typeof t=="string")return t;const n="usage"in e?e.usage:void 0;if(Array.isArray(n)){const s=n[0]?.model;if(typeof s=="string")return s}}async function*yd(e,t){let n,s,r,i;for await(const o of e){if(o==="id"||o.startsWith("id:")){const h=o==="id"?"":o.slice(3);i=h.startsWith(" ")?h.slice(1):h;continue}if(o.startsWith(":")||o.startsWith("event:")||o.startsWith("retry:"))continue;const a=Xu(o);if(a==="[DONE]"){yield{chunk:Oo({type:ps.RUN_FINISHED,threadId:n??t?.threadId??"",runId:s??t?.runId??"",timestamp:Date.now()},{finishReason:"stop",...r!==void 0?{model:r}:{}})};return}const u=vd(JSON.parse(a));"threadId"in u&&typeof u.threadId=="string"&&(n=u.threadId),"runId"in u&&typeof u.runId=="string"&&(s=u.runId);const l=Sd(u);l!==void 0&&(r=l);const c=i;i=void 0,yield{chunk:u,...c!==void 0?{id:c}:{}}}}async function Hs(e){if(!e.ok){if(e.status===401){const t=await e.clone().json().catch(()=>null);if(zu(t))throw new os(t.error.provider)}throw new Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}async function Id(e,t,n,s,r){const i=await e(Bs(t,{threadId:r}),{method:"GET",headers:{Accept:"application/json",...n},credentials:s});await Hs(i);const o=await i.json(),a=o.activeRun&&typeof o.activeRun.runId=="string"?{runId:o.activeRun.runId}:null,u=o.interrupts&&typeof o.interrupts.runId=="string"&&Array.isArray(o.interrupts.pending)&&o.interrupts.pending.length>0?{runId:o.interrupts.runId,pending:o.interrupts.pending}:null;return{messages:Array.isArray(o.messages)?Ao(o.messages):[],activeRun:a,interrupts:u}}async function Rd(e,t,n,s,r){const i=await e(Bs(t,{threadId:r}),{method:"GET",headers:{Accept:"application/json",...n},credentials:s});await Hs(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*gs(e,t,n){await Hs(e),yield*yd(md(Wu(e),t),n)}async function*Cd(e,t){for await(const{chunk:n}of gs(e,t))yield n}function si(e,t,n,s){return async function*(r,i){let o;try{o=await e(t,{...n,headers:{...n.headers,...r},...i?{signal:i}:{}})}catch(a){throw new Us(a)}yield*s(o,i)}}async function*ri(e,t,n){const s=hd(n);for(;;){if(t?.aborted)return;const r=s.lastEventId!==void 0?{"Last-Event-ID":s.lastEventId}:{};let i=!1,o=!1;try{for await(const{chunk:a,id:u}of e(r,t))s.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 Jo||a instanceof Us)&&s.lastEventId!==void 0){await s.waitBeforeReconnect(o,t);continue}throw a}if(t?.aborted||i)return;if(s.lastEventId!==void 0){if(o){await s.waitBeforeReconnect(!0,t);continue}throw new ud}return}}function ii(e){if(!e)throw new Error("Connection adapter is required");const t="connect"in e,n="subscribe"in e,s="send"in e;if(t&&(n||s))throw new Error("Connection adapter must provide either connect or both subscribe and send, not both modes");if(n&&s){const u=e.joinRun?.bind(e),l=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...u?{joinRun:u}:{},...l?{hydrate:l}:{}}}if(!t)throw new Error("Connection adapter must provide either connect or both subscribe and send");let r=[],i=[];function o(u,l){l&&Wo.set(u,l);const c=i.shift();c?c(u):r.push(u)}async function a(u){const l=()=>r.length===0&&(i.length>0||u?.aborted);for(let h=0;h<16&&!u?.aborted;h++){if(l())return;await Promise.resolve()}let c=0;for(;!u?.aborted;)if(l()||(await new Promise(h=>setTimeout(h,0)),c++,i.length===0&&c>=32))return}return{subscribe(u){const l=r.splice(0),c=[];return r=l,i=c,(async function*(){for(;!u?.aborted;){let h;const d=l.shift();d!==void 0?h=d:h=await new Promise(f=>{const p=()=>f(null);c.push(g=>{u?.removeEventListener("abort",p),f(g)}),u?.addEventListener("abort",p,{once:!0})}),h!==null&&(yield h)}})()},async send(u,l,c,h){let d=!1,f,p;try{const g=e.connect(u,l,c,h);for await(const m of g)"threadId"in m&&typeof m.threadId=="string"&&(f=m.threadId),"runId"in m&&typeof m.runId=="string"&&(p=m.runId),(m.type==="RUN_FINISHED"||m.type==="RUN_ERROR")&&(d=!0),o(m,h?.runId);!c?.aborted&&!d&&o(Oo({type:ps.RUN_FINISHED,threadId:jt(f??h?.threadId,"threadId"),runId:jt(p??h?.runId,"runId"),timestamp:Date.now()},{finishReason:"stop",model:"connect-wrapper"}),h?.runId)}catch(g){if(!c?.aborted&&!d)try{const m=g instanceof Error?g.message:"Unknown error in connect()";o({type:ps.RUN_ERROR,threadId:jt(f??h?.threadId,"threadId"),runId:jt(p??h?.runId,"runId"),timestamp:Date.now(),message:m},h?.runId)}catch{}throw g}await a(c)},...typeof e.joinRun=="function"?{joinRun:(u,l)=>e.joinRun(u,l)}:{},...(()=>{const u=e.hydrate;return typeof u=="function"?{hydrate:l=>u(l)}:{}})()}}function bd(e,t,n,s){const r=jc(e),i={...s.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??ni("thread"),runId:n?.runId??ni("run"),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:r,tools:n?.clientTools??[],context:[],forwardedProps:i,data:{...i}}}function Kf(e,t={}){return{async*connect(n,s,r,i){const o=typeof e=="function"?e():e,a=typeof t=="function"?await t():t,u={"Content-Type":"application/json",...at(a.headers),...at(i?.headers),...gd(i?.runId)},l=bd(n,s,i,a),c=a.fetchClient??fetch,h=r||a.signal;yield*ri(si(c,o,{method:"POST",headers:u,body:JSON.stringify(l),credentials:a.credentials||"same-origin"},(d,f)=>gs(d,f,{...i?.threadId!==void 0?{threadId:i.threadId}:{},...i?.runId!==void 0?{runId:i.runId}:{}})),h,a.reconnect)},async*joinRun(n,s){const r=typeof e=="function"?e():e,i=typeof t=="function"?await t():t,o=Bs(r,{offset:"-1",runId:n}),a={...at(i.headers)},u=i.fetchClient??fetch,l=s||i.signal;yield*ri(si(u,o,{method:"GET",headers:a,credentials:i.credentials||"same-origin"},(c,h)=>gs(c,h,{runId:n})),l,i.reconnect)},async hydrate(n){const s=typeof e=="function"?e():e,r=typeof t=="function"?await t():t;return Id(r.fetchClient??fetch,s,at(r.headers),r.credentials||"same-origin",n)},async hydrateGeneration(n){const s=typeof e=="function"?e():e,r=typeof t=="function"?await t():t;return Rd(r.fetchClient??fetch,s,at(r.headers),r.credentials||"same-origin",n)}}}function wd(e){return{async*connect(t,n,s,r){if(!s)throw new Error("fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.");if(!r)throw new Error("fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.");const i=await e({messages:t,data:n,threadId:r.threadId,runId:r.runId,...r.parentRunId!==void 0?{parentRunId:r.parentRunId}:{},...r.resume!==void 0?{resume:r.resume}:{}},{signal:s,headers:r.headers});i instanceof Response?yield*Cd(i,s):yield*Ed(i,s)}}}async function*Ed(e,t){if(t.aborted)return;const n=e[Symbol.asyncIterator](),s=new Promise(r=>{t.addEventListener("abort",()=>r({done:!0,value:void 0}),{once:!0})});try{for(;;){const r=await Promise.race([n.next(),s]);if(r.done)return;yield r.value}}finally{await n.return?.()}}function ge(e){return e.resumable}function Ln(e,t){const n=Rc(e.descriptor);return n?{...t,metadata:Ic(n)}:t}function Td(e){return"cancel"in e&&"clearResolution"in e}var _d=new Set(["invalid-payload","invalid-edited-args","invalid-tool-output","invalid-response-schema","unknown-interrupt","expired","stale","conflict","legacy-unsupported"]),Ad=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 oe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xo(e){return oe(e)&&e.kind==="approval"&&typeof e.toolName=="string"&&"input"in e}function Yo(e){return oe(e)&&e.kind==="client_tool"&&typeof e.toolName=="string"&&"input"in e}function Md(e){return Xo(e.metadata)||Yo(e.metadata)}function oi(e){return pc(e)}function xd(e){if(!oe(e.metadata))return!1;const t=e.metadata[pn];return!oe(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 Od(e){if(!oe(e.metadata))return!1;const t=e.metadata[pn];return!oe(t)||t.kind!=="generic"?!1:"definitionId"in t||"key"in t||"batchIndex"in t||"payloadSchemaHash"in t}function Pd(e){return e.metadata?.["tanstack:interruptPayload"]}function kd(e){return e==="tanstack:client_tool_execution"||e==="client_tool_input"}function ct(e){if(e.responseSchema!==void 0)try{return Ue($e(e.responseSchema))}catch{return}}function ai(e){if(e!==void 0)try{return vc(e)}catch{return}}function Le(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"then"in e&&typeof e.then=="function"}function Gt(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(Me(e)){const s=e["~standard"].validate(t),r=i=>i.issues?{code:n,message:i.issues[0]?.message??"Schema validation failed."}:{valid:!0,payload:i.value};return Le(s)?Promise.resolve(s).then(r):r(s)}return{valid:!0,payload:t}}function Ld(e){for(const t of _d)if(t===e)return!0;return!1}function Fd(e){for(const t of Ad)if(t===e)return!0;return!1}function li(e){if(!oe(e))return!1;const t=e.scope,n=e.code;return typeof n=="string"&&typeof e.message=="string"&&typeof e.retryable=="boolean"&&typeof e.threadId=="string"&&typeof e.interruptedRunId=="string"&&typeof e.generation=="number"?t==="item"?Ld(n)&&typeof e.interruptId=="string"&&(e.source==="client"||e.source==="server"):t==="batch"&&Fd(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(s=>typeof s=="string")&&(e.source==="client"||e.source==="server"||e.source==="transport"):!1}function Nd(e){return li(e)?[e]:!oe(e)||!Array.isArray(e.errors)?[]:e.errors.every(li)?e.errors:[]}function Zo(e,t){if(e.length!==t.length)return!1;const n=[...e].sort(),s=[...t].sort();return n.every((r,i)=>r===s[i])}function ui(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&Zo(e.interruptIds,t.interruptIds)}function Dd(e,t,n){const s=n.filter(a=>a.source!=="transport"),r=a=>t.includes(a)&&s.some(u=>ui(a,u)),i=e.filter(a=>!r(a)),o=t.filter(a=>!s.some(u=>ui(a,u)));return Object.freeze({rootErrors:Object.freeze([...i,...n]),submissionRootErrors:Object.freeze([...o,...s])})}function jd(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;const n=t.resolutions.map(s=>s.interruptId);return e.scope==="item"?n.includes(e.interruptId):Zo(e.interruptIds,n)}function Fn(e,t,n){const s=ct(e)??n?.responseSchemaHash;return B({v:1,kind:"generic",interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...s!==void 0?{responseSchemaHash:s}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}})}function Gd(e,t){const n=B(e.descriptor),s=e.error===void 0?Object.freeze([]):Object.freeze([B(e.error)]),r=s[0];return{id:n.id,interruptId:n.id,reason:n.reason,...n.message!==void 0?{message:n.message}:{},...n.responseSchema!==void 0?{responseSchema:n.responseSchema}:{},...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{},...n.metadata!==void 0?{metadata:n.metadata}:{},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:s,...r!==void 0?{error:r}:{},canResolve:e.canResolve}}var $d=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;const t=new Map;for(const n of e.interrupts??[]){if(t.has(n.id))throw new Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t="live"){this.activeSubmissionOperation=void 0,this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:B(e.interrupts)};const n=new Map;for(const s of e.interrupts){const r=oi(s);r?.kind==="generic"&&r.definitionId!==void 0&&r.key!==void 0&&r.batchIndex!==void 0&&n.set(r.batchIndex,(n.get(r.batchIndex)??0)+1)}this.items=e.interrupts.map(s=>this.hydrateInterrupt(s,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind==="generic"&&e.definition!==void 0)}reset(e){this.activeSubmissionOperation=void 0,this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??"live")}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e=="boolean"){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(const e of this.items)ge(e)&&(e.validationGeneration++,e.resolution=Object.freeze(Ln(e,{interruptId:e.descriptor.id,status:"cancelled"})),e.status="staged",e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw new Error("Interrupt submission is already active.");const e=this.retrySubmission;if(!e){this.addRootError("transport","There is no retryable interrupt submission.",!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){const n=this.items.find(s=>s.kind==="client-tool-execution"&&s.binding?.kind==="client-tool-execution"&&s.binding.toolCallId===e||s.kind==="generic"&&kd(s.descriptor.reason)&&s.descriptor.toolCallId===e&&Yo(s.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){const n=this.items.find(s=>s.descriptor.id===e&&(s.kind==="tool-approval"||s.kind==="generic"&&s.descriptor.reason==="approval_required"&&Xo(s.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){const s=B(e),r=oi(s),i=r===void 0&&Md(s);if(r===void 0&&!i)return xd(s)?{descriptor:s,binding:Fn(s,t,void 0),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","The interrupt binding is invalid or incomplete."),validationGeneration:0}:{descriptor:s,binding:void 0,kind:"unbound",status:"pending",canResolve:!1,resumable:!1,validationGeneration:0};const o=r!==void 0&&r.interruptId===s.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&ct(s)===r.responseSchemaHash,a=r!==void 0&&r.interruptId===s.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&r.responseSchemaHash===(ct(s)??r.responseSchemaHash);if(r!==void 0&&Od(s)&&(!a||r.kind!=="generic"||r.definitionId===void 0||r.key===void 0||r.batchIndex===void 0))return{descriptor:s,binding:Fn(s,t,r),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","The interrupt binding does not match this interrupted run."),validationGeneration:0};if(a&&r.kind==="tool-approval"){const l=this.tools?.find(c=>c.name===r.toolName);if(l?.needsApproval===!0&&s.toolCallId===r.toolCallId)try{const c=hc(l.approvalSchema,l.inputSchema);if(Vr(l.inputSchema)===r.inputSchemaHash&&c.approvalSchemaHash===r.approvalSchemaHash&&c.responseSchemaHash===r.responseSchemaHash)return{descriptor:s,binding:B(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&&s.toolCallId===r.toolCallId&&Vr(l.outputSchema)===r.outputSchemaHash)return{descriptor:s,binding:B(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&&n.get(r.batchIndex)!==1)return{descriptor:s,binding:B(r),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","Generic interrupt batch contains a duplicate batchIndex."),validationGeneration:0};if(o&&r.kind==="generic"&&r.definitionId!==void 0&&r.key!==void 0&&r.batchIndex!==void 0&&r.key.length>0&&n.get(r.batchIndex)===1){const 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=Pd(s);return{descriptor:s,binding:B(r),definition:l,kind:"generic",status:"pending",canResolve:!0,resumable:!0,...c===void 0?{}:{payload:B(c)},validationGeneration:0}}}const u=i||r!==void 0&&r.interruptId===s.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&(r.kind!=="generic"||ct(s)===void 0||r.responseSchemaHash===ct(s));return{descriptor:s,binding:Fn(s,t,r),kind:"generic",status:"pending",canResolve:u,resumable:u,validationGeneration:0}}buildSnapshot(e){const t=this.requireHydration(),n=this.items.filter(s=>s.kind!=="client-tool-execution"&&s.status!=="submitting").map(s=>{const r=Gd(s,t);if(s.kind==="unbound"||s.binding===void 0){const a={...r,kind:"unbound",canResolve:!1};return Object.freeze(a)}if(s.kind==="tool-approval"&&s.binding.kind==="tool-approval"){const a=B(s.binding),u={...r,kind:"tool-approval",binding:a,toolName:s.binding.toolName,toolCallId:s.binding.toolCallId,originalArgs:B(s.binding.originalArgs),cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:(l,c)=>{const h=oe(c)?c:void 0;this.resolveItem(s.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=s.binding.kind==="generic"?B(s.binding):B({v:1,kind:"generic",interruptId:s.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof s.binding.responseSchemaHash=="string"?{responseSchemaHash:s.binding.responseSchemaHash}:{}});if(s.definition!==void 0&&s.binding.kind==="generic"){const a={...r,kind:"generic",definitionId:s.definition.id,key:s.binding.key??"",payload:s.payload,binding:i,cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:u=>this.resolveItem(s.descriptor.id,u,e)};return Object.freeze(a)}const o={...r,kind:"generic",binding:i,cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:a=>this.resolveItem(s.descriptor.id,a,e)};return Object.freeze(o)});return Object.freeze(n)}publish(e="live"){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,n){this.assertItemMutable(n);const s=this.findItem(e);if(this.invalidateRetry(),!s.canResolve){s.status="error",s.error=this.itemError(e,"invalid-response-schema","The interrupt response schema is invalid and cannot be resolved."),n||this.publish();return}const r=++s.validationGeneration,i=this.validateCandidate(s,t);if(Le(i)){s.status="validating",s.error=void 0,n||this.publish(),Promise.resolve(i).then(o=>{r===s.validationGeneration&&this.applyValidation(s,o,n)}).catch(o=>{r===s.validationGeneration&&this.applyValidation(s,{code:this.validationCode(s),message:o instanceof Error?o.message:String(o)},n)});return}this.applyValidation(s,i,n)}cancelItem(e,t){this.assertItemMutable(t);const n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(Ln(n,{interruptId:e,status:"cancelled"})),n.status="staged",n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);const n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status="pending",t||this.publish()}maybeSubmit(){const e=this.items.some(i=>i.kind==="generic"),t=this.items.filter(i=>ge(i)&&!(e&&i.kind==="client-tool-execution"));if(t.length===0||t.some(i=>i.resolution===void 0||i.status!=="staged"))return;const n=this.requireHydration(),s=sc(t.map(i=>i.resolution).filter(i=>i!==void 0)),r=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:s.resolutions,canonicalResolutions:s.canonicalResolutions,fingerprint:s.fingerprint});this.submitBatch(r)}applyValidation(e,t,n){if(!("valid"in t)){e.status="error";const s=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=s,e.kind==="client-tool-execution"&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(r=>!(r.code==="item-validation-failed"&&r.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:"batch",code:"item-validation-failed",message:s.message,source:"client",retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:s.threadId,interruptedRunId:s.interruptedRunId,generation:s.generation})])),n||this.publish();return}e.resolution=B(Ln(e,{interruptId:e.descriptor.id,status:"resolved",payload:t.payload})),e.status="staged",e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind==="generic"){const n=Gt(e.definition?.responseSchema??e.descriptor.responseSchema,t,"invalid-payload");if(e.definition===void 0)return n;const s=r=>"valid"in r?{valid:!0,payload:t}:r;return Le(n)?Promise.resolve(n).then(s):s(n)}return e.kind==="client-tool-execution"?Gt(e.tool?.outputSchema,t,"invalid-tool-output"):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!oe(t)||typeof t.approved!="boolean")return{code:"invalid-payload",message:"Tool approval resolutions require an approved boolean."};const n=t.approved,s=t.editedArgs;if(!n&&s!==void 0)return{code:"invalid-edited-args",message:"Rejected tool approvals cannot edit tool arguments."};if(n&&s!==void 0){const r=Gt(e.tool?.inputSchema,s,"invalid-edited-args");return Le(r)?Promise.resolve(r).then(i=>"valid"in i?this.validateApprovalPayload(e,t,i.payload):i):"valid"in r?this.validateApprovalPayload(e,t,r.payload):r}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){const s=t.approved===!0,r=this.approvalBranchSchema(e.tool,s),i=t.payload;if(r===void 0&&i!==void 0)return{code:"invalid-payload",message:"This approval branch does not accept a payload."};if(r!==void 0&&i===void 0)return{code:"invalid-payload",message:"This approval branch requires a payload."};const o=Gt(r,i,"invalid-payload"),a=u=>"valid"in u?{valid:!0,payload:{approved:s,...n!==void 0?{editedArgs:n}:{},...r!==void 0?{payload:u.payload}:{}}}:u;return Le(o)?Promise.resolve(o).then(a):a(o)}approvalBranchSchema(e,t){const n=e?.approvalSchema;return!oe(n)||!("approve"in n||"reject"in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind==="client-tool-execution"?"invalid-tool-output":"invalid-payload"}resolveBooleanBulk(e){const t=this.items.filter(n=>ge(n)&&n.kind!=="client-tool-execution");if(!t.every(n=>n.kind==="tool-approval"&&this.approvalBranchSchema(n.tool,e)===void 0)||t.length===0){this.addRootError("unsupported-bulk-operation","Boolean bulk resolution requires payloadless tool approvals.",!1);return}this.invalidateRetry();for(const n of t)n.validationGeneration++,n.resolution=B({interruptId:n.descriptor.id,status:"resolved",payload:{approved:e}}),n.status="staged",n.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){const t=this.items.map(i=>({status:i.status,...i.resolution!==void 0?{resolution:i.resolution}:{},...i.error!==void 0?{error:i.error}:{},validationGeneration:i.validationGeneration})),n={active:!0};this.activeTransaction=n;const s=this.buildSnapshot(n).filter(Td);let r;try{for(const i of s){const o=e(i);if(o!==void 0){r={code:Le(o)?"async-resolver":"inactive-transaction",message:Le(o)?"Interrupt transaction resolvers must be synchronous.":"Interrupt transaction resolvers must return literal undefined."};break}}r===void 0&&this.items.some(i=>ge(i)&&i.kind!=="client-tool-execution"&&(i.resolution===void 0||i.status!=="staged"))&&(r={code:"incomplete-batch",message:"Interrupt transaction did not resolve every item."})}catch(i){r={code:"item-validation-failed",message:i instanceof Error?i.message:String(i)}}finally{n.active=!1,this.activeTransaction=void 0}if(r){this.restoreCheckpoints(t),this.addRootError(r.code,r.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,n)=>{const s=e[n];s&&(t.status=s.status,t.resolution=s.resolution,t.error=s.error,t.validationGeneration=s.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active)throw new Error("Interrupt transaction is inactive.");if(this.activeTransaction&&e!==this.activeTransaction)throw new Error("Interrupt transaction is inactive.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}assertRootMutable(){if(this.activeTransaction)throw new Error("Interrupt transaction is already active.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){const t={submission:e};this.activeSubmissionOperation=t,this.resuming=!0,this.retrySubmission=void 0;for(const n of this.items)ge(n)&&(n.status="submitting");this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){const n=Nd(e);if(n.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)ge(l)&&(l.status="error");return}const s=n.filter(u=>jd(u,t));s.length!==n.length&&this.addRootError("protocol","Interrupt submission errors did not match the active batch.",!1);let r=!1,i=!1;const o=[];for(const u of s)if((u.code==="stale"||u.code==="expired"||u.code==="conflict")&&(r=!0),i||=u.retryable,u.scope==="item"){const l=this.items.find(c=>ge(c)&&c.descriptor.id===u.interruptId);l&&(l.status="error",l.error=B(u))}else o.push(B(u));const a=Dd(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=a.rootErrors,this.submissionRootErrors=a.submissionRootErrors;for(const u of this.items)ge(u)&&u.status==="submitting"&&(u.status="error");this.retrySubmission=i&&!r?t:void 0}addRootError(e,t,n,s="client"){const r=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:"batch",code:e,message:t,source:s,retryable:n,interruptIds:Object.freeze(this.items.filter(ge).map(i=>i.descriptor.id)),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})]),this.publish()}findItem(e){const t=this.items.find(n=>n.descriptor.id===e);if(!t)throw new Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw new Error("InterruptManager is not hydrated.");return this.hydration}itemError(e,t,n,s){const r=this.requireHydration();return Object.freeze({scope:"item",interruptId:e,code:t,message:n,...s!==void 0?{path:Object.freeze([...s])}:{},source:"client",retryable:!1,threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})}};function Ud(e,...t){const n=e?.();if(ie(n))return n;for(const s of t)if(ie(s))return s}async function Bd(e,t){if(!t)throw new _o;return await e.prepare(t),e.headers(t)}function Hd(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():Math.random().toString(36).slice(2)}var $t;function ci(){return $t!==void 0||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__=Hd()),$t=globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__),$t}var zd=0;function he(e){return e==null||e===""?"missing":`value-${encodeURIComponent(String(e))}`}function ms(e){const t=e.runtimeId??ci(),n=e.eventId&&e.eventId.length>0?e.eventId:[e.source,e.eventType,he(t),he(e.clientId),he(e.requestId),he(e.streamId),he(e.hookId),he(e.threadId),he(e.runId),he(e.messageId),he(e.toolCallId),he(e.sequence),e.timestamp,ci(),zd++].join(":");return{...e,runtimeId:t,eventId:n}}var Vd=class{#t=!0;#e;#n;#s;#i;#r;#a;#l;#h=0;#o=5;#u=!1;#f=!1;#d=null;#p=()=>{this.debugLog("Connected to event bus"),this.#r=!0,this.#u=!1,this.debugLog("Emitting queued events",this.#i),this.#i.forEach(e=>this.emitEventToBus(e)),this.#i=[],this.stopConnectLoop(),this.#n().removeEventListener("tanstack-connect-success",this.#p)};#g=()=>{if(this.#h<this.#o){this.#h++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#n().removeEventListener("tanstack-connect",this.#g),this.#f=!0,this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};#m=()=>{this.#u||(this.#u=!0,this.#n().addEventListener("tanstack-connect-success",this.#p),this.#g())};constructor({pluginId:e,debug:t=!1,enabled:n=!0,reconnectEveryMs:s=300}){this.#e=e,this.#t=n,this.#n=this.getGlobalTarget,this.#s=t,this.debugLog(" Initializing event subscription for plugin",this.#e),this.#i=[],this.#r=!1,this.#f=!1,this.#a=null,this.#l=s}startConnectLoop(){this.#a!==null||this.#r||(this.debugLog(`Starting connect loop (every ${this.#l}ms)`),this.#a=setInterval(this.#g,this.#l))}stopConnectLoop(){this.#u=!1,this.#a!==null&&(clearInterval(this.#a),this.#a=null,this.#i=[],this.debugLog("Stopped connect loop"))}debugLog(...e){this.#s&&console.log(`🌴 [tanstack-devtools:${this.#e}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;const e=typeof EventTarget<"u"?new EventTarget:void 0;return typeof e>"u"||typeof e.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog("Using new EventTarget as fallback"),e)}getPluginId(){return this.#e}dispatchCustomEventShim(e,t){try{const n=new Event(e,{detail:t});this.#n().dispatchEvent(n)}catch{this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(e,t){try{this.#n().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog("Emitting event to client bus",e),this.dispatchCustomEvent("tanstack-dispatch-event",e)}createEventPayload(e,t){return{type:`${this.#e}:${e}`,payload:t,pluginId:this.#e}}emit(e,t){if(!this.#t){this.debugLog("Event bus client is disabled, not emitting event",e,t);return}if(this.#d&&(this.debugLog("Emitting event to internal event target",e,t),this.#d.dispatchEvent(new CustomEvent(`${this.#e}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#f){this.debugLog("Previously failed to connect, not emitting to bus");return}if(!this.#r){this.debugLog("Bus not available, will be pushed as soon as connected"),this.#i.push(this.createEventPayload(e,t)),typeof CustomEvent<"u"&&!this.#u&&(this.#m(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,n){const s=n?.withEventTarget??!1,r=`${this.#e}:${e}`;if(s&&(this.#d||(this.#d=new EventTarget),this.#d.addEventListener(r,o=>{t(o.detail)})),!this.#t)return this.debugLog("Event bus client is disabled, not registering event",r),()=>{};const i=o=>{this.debugLog("Received event from bus",o.detail),t(o.detail)};return this.#n().addEventListener(r,i),this.debugLog("Registered event to bus",r),()=>{s&&this.#d?.removeEventListener(r,i),this.#n().removeEventListener(r,i)}}onAll(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=n=>{const s=n.detail;e(s)};return this.#n().addEventListener("tanstack-devtools-global",t),()=>this.#n().removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=n=>{const s=n.detail;this.#e&&s.pluginId!==this.#e||e(s)};return this.#n().addEventListener("tanstack-devtools-global",t),()=>this.#n().removeEventListener("tanstack-devtools-global",t)}},qd=class extends Vd{constructor(){super({pluginId:"tanstack-ai-devtools"})}},di=Symbol.for("tanstack.ai.devtools.eventClient");function Kd(){const e=globalThis,t=e[di];if(t)return t;const n=new qd;return e[di]=n,n}var Rt=Kd();function Y(e,t){Rt.emit(e,t)}var ea=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent("client:created",{initialMessageCount:e})}loadingChanged(e){this.emitEvent("client:loading:changed",{isLoading:e})}errorChanged(e){this.emitEvent("client:error:changed",{error:e})}textUpdated(e,t,n,s){this.emitEvent("text:chunk:content",{streamId:e,messageId:t,content:n,...s})}toolCallStateChanged(e,t,n,s,r,i,o){this.emitEvent("tools:call:updated",{streamId:e,messageId:t,toolCallId:n,toolName:s,state:r,arguments:i,...o})}thinkingUpdated(e,t,n,s,r){this.emitEvent("text:chunk:thinking",{streamId:e,messageId:t,content:n,delta:s,...r})}structuredOutputChanged(e,t,n,s,r){this.emitEvent(e,{streamId:t,messageId:n,...s,...r})}approvalRequested(e,t,n,s,r,i,o){this.emitEvent("tools:approval:requested",{streamId:e,messageId:t,toolCallId:n,toolName:s,input:r,approvalId:i,...o})}messageAppended(e,t,n){const s=e.parts.filter(r=>r.type==="text").map(r=>r.content).join(" ");this.emitEvent("text:message:created",{streamId:t,messageId:e.id,role:e.role,content:s,parts:e.parts,...n})}messageSent(e,t){const n=typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.content).join("");this.emitEvent("text:message:created",{messageId:e,role:"user",content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent("text:message:user",{messageId:e,role:"user",content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent("client:reloaded",{fromMessageIndex:e})}stopped(){this.emitEvent("client:stopped")}messagesCleared(){this.emitEvent("client:messages:cleared")}toolResultAdded(e,t,n,s,r){this.emitEvent("tools:result:added",{toolCallId:e,toolName:t,output:n,state:s,...r})}toolApprovalResponded(e,t,n,s){this.emitEvent("tools:approval:responded",{approvalId:e,toolCallId:t,approved:n,...s})}toolFixtureApplied(e){this.emitEvent("devtools:tool-fixture:applied",{...e})}},Qd=class extends ea{emitEvent(e,t){const n=Date.now(),s=e.startsWith("text:")||e.startsWith("tools:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",r=e.startsWith("client:")||e.startsWith("tools:")||e.startsWith("text:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",i=s?"user-visible":"client-state",o={hookId:this.clientId,...typeof t?.threadId=="string"?{threadId:t.threadId}:{},...typeof t?.runId=="string"?{runId:t.runId}:{},...typeof t?.streamId=="string"?{streamId:t.streamId}:{},...typeof t?.messageId=="string"?{messageId:t.messageId}:{},...typeof t?.toolCallId=="string"?{toolCallId:t.toolCallId}:{}};if(r){const a=ms({eventType:e,clientId:this.clientId,...o,source:"client",visibility:i,timestamp:n});Rt.emit(e,{...t,...a})}else{const a=ms({eventType:e,source:"client",visibility:"client-state",timestamp:n});Rt.emit(e,{...t,...a})}}},Wd=class extends ea{emitEvent(){}},Jd=class{events;constructor(e){this.events=new Wd(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,s){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return""}observeChunk(e){}recordMemoryState(e){}recordCompactionEvent(e,t){}recordCompactionState(e){}recordSkillsState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Xd=e=>new Jd(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 Yd(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var Zd=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,s){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=s}writeState(){const e=[...this.lastMessages];if(e.length===0&&!this.lastResume){const s=this.generation;this.runOperation(()=>{if(s===this.generation)return this.adapter.removeItem(this.id)});return}const t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}readInitial(){try{const e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(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(n=>{!n||this.messagesGeneration!==t||(this.lastResume=n.resume??null,this.lastMessages=n.messages,this.applyMessages(n.messages),n.resume&&this.applyResume&&this.applyResume(n.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;const e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){const t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{const t=e();if(t instanceof Promise){this.queuePending=!0;const n=t.catch(()=>{});this.queue=n,n.finally(()=>{this.queue===n&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){const t=te(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const n=fi(e);if(n&&this.clearedToolCallIds.has(n))return!0;const s=Yd(e);if(s&&this.clearedMessageIds.has(s))return n&&this.clearedToolCallIds.add(n),!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 n=fi(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return te(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 eh(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var th=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=te(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const n=gi(e);if(n&&this.clearedToolCallIds.has(n))return!0;const s=eh(e);if(s&&this.clearedMessageIds.has(s))return n&&this.clearedToolCallIds.add(n),!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 n=gi(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return te(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 nh(e){const t=new Set;for(const n of e??[]){if(t.has(n.id))throw new Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function vi(e){const{connection:t,fetcher:n}=e;if(t&&n)throw new Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return wd(n);throw new Error("ChatClient: either `connection` or `fetcher` is required.")}function Si(e){return"connect"in e}function sh(e){if(e.type!=="RUN_FINISHED"||e.outcome?.type==="interrupt")return!1;const t=e;return t.finishReason!==void 0?t.finishReason==="tool_calls":U(e)?.finishReason==="tool_calls"}function yi(e){const t={whenBusy:"queue",drain:"fifo",onOverflow:"reject"};if(!e)return t;if(typeof e=="string")return{...t,whenBusy:e};if(typeof e=="function")return{...t,strategy:e};const n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new Error("ChatClient: queue.maxSize must be a non-negative integer");return{whenBusy:e.whenBusy??"queue",drain:e.drain??"fifo",onOverflow:e.onOverflow??"reject",...n!==void 0?{maxSize:n}:{}}}function rh(e){const t=e.at(-1)?.body,n=[];for(const i of e){if(typeof i.content!="string")break;n.push(i.content)}if(n.length===e.length)return{content:n.join(`
|
|
4
|
+
`),...t!==void 0?{body:t}:{}};const s=[];let r;for(const i of e){if(typeof i.content=="string"){s.push({type:"text",content:i.content});continue}typeof i.content.content=="string"?s.push({type:"text",content:i.content.content}):s.push(...i.content.content),r=xo(r,i.content.metadata)}return{content:{content:s,...r!==void 0?{metadata:r}:{}},...t!==void 0?{body:t}:{}}}function ih(e){if(!(e===null||typeof e!="object"||Array.isArray(e))&&!(!("approved"in e)||typeof e.approved!="boolean"))return e.approved}function oh(e){const t=e;if(t===null||typeof t!="object"||!("resumeState"in t))return;const n=t.resumeState;if(!(n===null||typeof n!="object"||!("threadId"in n)||typeof n.threadId!="string"||n.threadId.length===0||!("runId"in n)||typeof n.runId!="string"||n.runId.length===0))return{threadId:n.threadId,runId:n.runId}}var ah=2e3,lh=new Set(["TEXT_MESSAGE_START","TEXT_MESSAGE_CONTENT","TOOL_CALL_START","MESSAGES_SNAPSHOT"]),uh=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new th;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status="ready";connectionStatus="disconnected";abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;connectionDrainsOnSend=!1;errorReportedGeneration=null;streamGeneration=0;continuationGeneration=0;streamContinuationGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){nh(e.interrupts),this.threadId=e.threadId||"",this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1}else if(e.persistence){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new Zd(e.persistence,e.threadId,a=>this.processor.setMessages(a),a=>this.applyPersistedResume(a))}this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=yi(e.queue);const n=vi(e);if(this.connectionDrainsOnSend=Si(n),this.connection=ii(n),this.clientToolsRef={current:new Map},e.tools)for(const a of e.tools)this.clientToolsRef.current.set(a.name,a);this.devtoolsBridge=(e.devtoolsBridgeFactory??Xd)(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 $d({...e.tools!==void 0?{tools:e.tools}:{},...e.interrupts!==void 0?{interrupts:e.interrupts}:{},submit:a=>this.submitInterruptBatch(a),onChange:a=>this.notifyResumeStateChange(a)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);const s=this.persistor?.readInitial(),r=s instanceof Promise?void 0:s,i=r?r.messages:e.initialMessages;let o=null;if(r?.resume){const a=r.resume;Array.isArray(a.pendingInterrupts)&&a.pendingInterrupts.length>0?this.applyResumeSnapshot(a):a.resumeState.runId&&(o=a.resumeState.runId)}if(!o&&e.initialResumeSnapshot){const a=e.initialResumeSnapshot;!(Array.isArray(a.pendingInterrupts)&&a.pendingInterrupts.length>0)&&a.resumeState.runId&&(o=a.resumeState.runId)}this.processor=new ad({...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(s),this.rejoinRunId=o,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){const t=oh(e);if(t===void 0){this.interruptManager.reset({source:"hydrate"});return}this.lastResume=t;const n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:"hydrate"});return}const s=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:s,interrupts:n},"hydrate")}applyPersistedResume(e){this.applyResumeSnapshot(e);const t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){const e=this.connection.hydrate;e&&(this.isLoading||this.abortController||this.disposed||(async()=>{let t;try{t=await e(this.threadId)}catch{return}this.disposed||!this.tailing||this.isLoading||this.abortController||(t.messages.length>0&&this.processor.setMessages(Ao(t.messages)),t.interrupts&&t.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId))})())}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||(this.threadId=this.generateUniqueId("thread")),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!=="RUN_ERROR")return;const t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=te(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),te(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type==="RUN_STARTED"){const r=te(e)??e.runId;this.activeResumeThreadId="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=r,this.activeRunIds.add(r),this.clearedStreamTracker.onRunStarted(r),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:r});return}if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const n=te(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type==="RUN_ERROR"&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);const s=e.type==="RUN_FINISHED"&&sh(e);t?.resolveProcessing!==!1&&!s&&this.resolveProcessing()}observeInterruptState(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR"||this.activeInterruptSubmission&&e.type==="RUN_ERROR")return;const t=te(e),n="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId;if(e.type==="RUN_FINISHED"&&e.outcome?.type==="interrupt"){const l=this.currentRunId??t??this.activeResumeRunId??"";this.lastResume={threadId:n??this.threadId,runId:l},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:l,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},"live");return}const s=e.type==="RUN_ERROR"&&!t,r=!!(t&&this.lastResume?.runId===t),i=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),a=this.isLoading&&e.type==="RUN_FINISHED"&&!t,u=!!(this.activeInterruptSubmission&&this.isLoading&&e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt");if(s||r||i||o||a||u){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange("live")}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e=="boolean"){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){const n=t??this.lastResume;return n?this.resumeInterruptsUnsafeForGeneration(e,n,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,n){return n!==this.continuationGeneration?Promise.resolve(!1):this.isLoading?new Promise((s,r)=>{this.queuePostStreamAction(async()=>{try{s(await this.resumeInterruptsUnsafeForGeneration(e,t,n))}catch(i){r(i)}})}):(this.pendingResumeThreadId=t.threadId,this.pendingResumeParentRunId=t.runId,this.pendingResumeItems=[...e],this.streamResponse())}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){const t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(const r of e.resolutions){const i=ih(r.payload);if(i===void 0)continue;const o=r.interruptId;this.processor.addToolApprovalResponse(o,i)}const n=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},t).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(t!==this.continuationGeneration)return;const s=this.takeInterruptSubmissionFailure();if(s!==void 0)throw{errors:s.errors};if(!n)throw new Error("Interrupt continuation could not be started.");this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){const e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(const n of e){const s=n.metadata?.["tanstack:interruptBinding"];if(s===null||typeof s!="object"||!("generation"in s)||typeof s.generation!="number"||!Number.isInteger(s.generation)||s.generation<0||t!==void 0&&t!==s.generation)return 0;t=s.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){const t=this.getResumeState(),n=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}const t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){const t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??"useChat",outputKind:e?.outputKind??"chat",...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:n=>{this.processor.setMessages(n)},addToolResult:(n,s,r)=>{this.processor.addToolResult(n,s,r)},generateId:n=>this.generateUniqueId(n)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){const t=this.processor.getMessages();for(const n of t)if(n.parts.find(s=>s.type==="tool-call"&&s.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus("ready")}reportStreamError(e){const t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status==="submitted"||this.status==="streaming")&&this.setStatus("error"),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;const e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(t=>{t instanceof Error&&t.name!=="AbortError"&&(this.setConnectionStatus("error"),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(t)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!=="error"&&this.setConnectionStatus("disconnected")))})}async consumeSubscription(e){const t=this.connection.subscribe(e);for await(const n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}resumeInFlightRun(e){const t=this.connection.joinRun;if(!t)return;const n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus("streaming"),(async()=>{let s=!1,r=!1,i=!1;const o=setTimeout(()=>{r||n.abort()},ah);try{for await(const a of t(e,n.signal)){if(n.signal.aborted)break;r||(r=!0,clearTimeout(o)),!s&&lh.has(a.type)&&(s=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(a){const 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===n&&(this.abortController=null,this.setIsLoading(!1),this.status==="streaming"&&this.setStatus("ready"),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){const e=this.processor.getMessages(),t=e[e.length-1];t&&t.role==="assistant"&&this.processor.setMessages(e.slice(0,-1))}async processIncomingChunk(e,t){if(e=Vo(e),e.type==="RUN_ERROR"&&this.isActiveInterruptSubmissionFailure(e)){const n=U(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(n)?n:[]}}if(this.connectionStatus==="connecting"&&this.setConnectionStatus("connected"),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR")&&(te(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>"u"||!document.hidden)&&await new Promise(n=>setTimeout(n,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){const t=this.activeInterruptSubmission,n=U(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;const s=te(e);return s!==void 0&&s!==this.currentRunId||typeof e.threadId=="string"&&e.threadId!==t.threadId?!1:n.every(r=>r==null||typeof r!="object"||typeof r.threadId!="string"||typeof r.interruptedRunId!="string"||typeof r.generation!="number"?!1:r.threadId===t.threadId&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation)}resolveJoinedRun(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=te(e);if(t===void 0)return;const n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),typeof e=="string"&&!e.trim())return;if(this.hasPendingInterrupts())throw new Error("ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.");const s={...t,...n?.body};if(this.isSendBusy()){const{action:r,id:i}=this.decideWhenBusy(e,n);if(r==="drop")return;if(r==="queue"){this.enqueueMessage(e,s,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,s)}finally{this.sendInFlight=!1}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?"streaming":this.messageQueueDraining?"draining":"sendInFlight"}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{const n=this.normalizeMessageInput(e);this.pendingMessageBody=t;const s=this.processor.addUserMessage(n.content,n.id,n.metadata);return this.events.messageSent(s.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){const n=this.generateUniqueId("queued");if(t?.whenBusy)return{action:t.whenBusy,id:n};const{strategy:s,whenBusy:r}=this.queueConfig;if(s){const{action:i}=s({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:i,id:n}}return{action:r,id:n}}enqueueMessage(e,t,n){const{maxSize:s,onOverflow:r}=this.queueConfig;if(s!==void 0&&this.messageQueue.length>=s){if(r==="reject"||s===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId("queued"),content:e,createdAt:Date.now(),...t!==void 0?{body:t}:{}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e=="string"?{content:e.trim()}:{content:e.content,id:e.id,...e.metadata!==void 0?{metadata:e.metadata}:{}}}async append(e){if(this.mountDevtools(),this.hasPendingInterrupts())throw new Error("ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.");const t=Dc(e,je);if(t.role==="system")return;const n=t;this.events.messageAppended(n);const s=this.processor.getMessages();if(this.processor.setMessages([...s,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;const e=++this.streamGeneration;this.streamContinuationGeneration=this.continuationGeneration;const t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,s=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;const r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(r),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=r,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus("submitted"),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;const i=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,a=null,u=!1;try{const l=this.processor.getMessages(),c=new Map(this.clientToolsRef.current),h=this.context;if(await this.callbacksRef.current.onResponse(),i.aborted)return!1;const d={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId("stream"),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=c,this.activeContext=h,this.processor.prepareAssistantMessage(),this.ensureSubscription();const f=this.waitForProcessing();let p;if(this.byok){const m=Ud(this.byokProvider,d.provider);p=await Bd(this.byok,m)}const g={threadId:t??this.threadId,runId:r,...n!==null?{parentRunId:n}:{},clientTools:Array.from(c.values()).map(m=>({name:m.name,description:m.description,parameters:m.inputSchema?us(m.inputSchema):{type:"object"}})),forwardedProps:{...d},...s?{resume:s}:{},...p?{headers:p}:{}};if(this.devtoolsBridge.beginRun(g.runId,g.threadId),a=g.runId,this.devtoolsBridge.emitRunLifecycle("run:created",g.runId,"created"),this.devtoolsBridge.emitRunLifecycle("run:started",g.runId,"started"),this.devtoolsBridge.emitSnapshot(),await this.connection.send(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 os&&this.byok?.request(c.provider,"missing"),c instanceof rn&&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 os||c instanceof rn||c instanceof _o))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.status!=="ready"&&this.setStatus("ready"),this.messageQueueDraining||await this.drainQueue()):this.flushQueue())}return o}subscribe(e){const t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus("connecting"),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected")}async reload(){const e=this.processor.getMessages();if(e.length===0)return;const t=e.findLastIndex(n=>n.role==="user");t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){this.continuationGeneration++;const e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),this.lastResume=null,this.activeInterruptSubmission=void 0,this.interruptManager.reset(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){const e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.discardPendingSends(),this.persistor?.remove(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){const t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t,this.streamContinuationGeneration)}async addToolResultForClientTool(e,t,n,s){if(t&&e.state!=="output-error")try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(r){e={...e,output:null,state:"output-error",errorText:r.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||"output-available",s),n===this.continuationGeneration&&(this.processor.addToolResult(e.toolCallId,e.output,e.state==="output-error"?e.errorText||"Tool execution failed":void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state==="output-error"?{error:e.errorText||"Tool execution failed"}:e.output))){if(this.isLoading){this.queuePostStreamAction(()=>n===this.continuationGeneration?this.checkForContinuation():Promise.resolve());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&Me(e.outputSchema)?ac(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;const t=this.processor.getMessages();let n;for(const s of t){const r=s.parts.find(i=>i.type==="tool-call"&&i.approval?.id===e.id);if(r){n=r.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){const t=this.continuationGeneration;this.postStreamActions.push(async()=>{t===this.continuationGeneration&&await e()})}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.streamContinuationGeneration===this.continuationGeneration&&!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;const e=this.processor.getMessages().findLast(t=>t.role==="assistant");return!e||!e.parts.some(t=>t.type==="tool-call")?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain==="batch"){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.splice(0);this.emitQueueChange();const t=rh(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){const t=this.messageQueue.findIndex(n=>n.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){const t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected");const n=vi({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=Si(n),this.connection=ii(n),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),e.byok!==void 0&&(this.byok=e.byok),e.byokProvider!==void 0&&(this.byokProvider=e.byokProvider),"context"in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(const t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=yi(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 Ii(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 Ri(e){if(!Array.isArray(e))return;const t=[];for(const n of e)!n||typeof n!="object"||!("role"in n)||!("tokens"in n)||!("text"in n)||typeof n.role!="string"||typeof n.tokens!="number"||typeof n.text!="string"||t.push({role:n.role,tokens:n.tokens,text:n.text});return t}function ch(e){if(!e||typeof e!="object"||!("before"in e)||!("after"in e)||!("messagesBefore"in e)||!("messagesAfter"in e)||typeof e.before!="number"||typeof e.after!="number"||typeof e.messagesBefore!="number"||typeof e.messagesAfter!="number")return null;const t="reusedCheckpoint"in e&&e.reusedCheckpoint===!0,n="maxTokens"in e&&typeof e.maxTokens=="number"?e.maxTokens:void 0,s="strategyKey"in e&&typeof e.strategyKey=="string"?e.strategyKey:void 0,r="dropped"in e?Ri(e.dropped):void 0,i="result"in e?Ri(e.result):void 0;return{before:e.before,after:e.after,messagesBefore:e.messagesBefore,messagesAfter:e.messagesAfter,reusedCheckpoint:t,...n!==void 0?{maxTokens:n}:{},...s?{strategyKey:s}:{},...r?{dropped:r}:{},...i?{result:i}:{}}}var Ci=Symbol.for("tanstack.ai.devtools.activeBridgeByHookId");function Nn(){const e=globalThis,t=e[Ci];if(t)return t;const n=new Map;return e[Ci]=n,n}function dh(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 hh=class{options;unsubscribers=[];disposed=!1;superseded=!1;registered=!1;constructor(e){this.options=e}emitRegistered(){this.prepareForMountEmit()&&(this.registered=!0,Y("hook:registered",{...this.createEnvelope("hook:registered"),...this.createMetadataPayload(),lifecycle:"mounted"}))}emitUpdated(){this.prepareForEmit()&&Y("hook:updated",{...this.createEnvelope("hook:updated"),...this.createMetadataPayload(),lifecycle:"active"})}emitSnapshot(){this.prepareForEmit()&&Y("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?us(t.inputSchema):{type:"object"},outputSchema:t.outputSchema?us(t.outputSchema):void 0,needsApproval:t.needsApproval,metadata:t.metadata})):[];Y("tools:registered",{...this.createEnvelope("tools:registered"),...this.createMetadataPayload(),tools:e})}emitRunLifecycle(e,t,n,s={}){this.prepareForEmit()&&Y(e,{...this.createEnvelope(e,"client-state",{runId:t}),runId:t,status:n,...s.error?{error:s.error}:{}})}deactivate(){const e=Nn();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(Nn().get(this.options.hookId)!==this){this.deactivate();return}const e={...this.createEnvelope("hook:unregistered"),...this.createMetadataPayload(),reason:"disposed"};Y("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=Nn(),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(Rt.on("devtools:request-state",n=>{this.handleRequestState(n)})),this.options.applyToolFixture&&this.unsubscribers.push(Rt.on("devtools:tool-fixture:apply",n=>{this.handleToolFixtureApply(n)})))}handleRequestState(e){if(this.disposed||this.superseded)return;const t=e.payload.targetHookId;t&&t!==this.options.hookId||(this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot(),this.onReplayState())}onReplayState(){}async handleToolFixtureApply(e){const t=e.payload;this.matchesFixtureTarget(t)&&await this.options.applyToolFixture?.(t)}matchesFixtureTarget(e){return!e.hookId&&!e.threadId?!1:e.hookId?e.hookId===this.options.hookId:!(e.threadId&&(!this.options.threadId||e.threadId!==this.options.threadId))}createEnvelope(e,t="client-state",n={}){return ms({eventType:e,source:"client",visibility:t,clientId:this.options.clientId,hookId:this.options.hookId,...this.options.threadId?{threadId:this.options.threadId}:{},...n.runId?{runId:n.runId}:{},timestamp:Date.now()})}createMetadataPayload(){return{hookId:this.options.hookId,hookName:this.options.metadata.hookName,...this.options.metadata.name?{displayName:this.options.metadata.name}:{},...this.options.metadata.outputKind?{outputKind:this.options.metadata.outputKind}:{},...this.options.metadata.framework?{framework:this.options.metadata.framework}:{}}}},fh=class extends hh{events;chatOptions;currentRunId=null;currentRunThreadId=null;currentStreamId=null;lastStreamId=null;lastRunEventContext;lastMemoryStateValue=null;lastCompactionEvents=[];lastSkillsStateValue=null;constructor(e){super(dh(e,{getSnapshot:e.getSnapshot,applyToolFixture:t=>this.applyFixture(t)})),this.chatOptions=e,this.events=new yh(()=>e.clientId,this)}setCurrentStreamId(e){this.currentStreamId=e,e&&(this.lastStreamId=e)}recordStreamId(e){e&&(this.lastStreamId=e)}mountWithTools(e){this.events.clientCreated(e),this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot()}notifyToolsChanged(){this.emitToolsRegistered(),this.emitSnapshot()}getCurrentStreamId(){return this.currentStreamId}getLastStreamId(){return this.lastStreamId}resolveStreamId(){return this.currentStreamId??this.lastStreamId??this.chatOptions.generateId("stream")}beginRun(e,t){this.currentRunId=e,this.currentRunThreadId=t,this.lastRunEventContext={runId:e,threadId:t}}observeChunk(e){if(e.type==="RUN_STARTED"){this.beginRun(e.runId,e.threadId);return}if(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR"){const t=(e.type==="RUN_FINISHED",e.runId);if(!t||t===this.currentRunId){const n=this.getCurrentRunEventContext();n&&(this.lastRunEventContext=n),this.currentRunId=null,this.currentRunThreadId=null}}}recordMemoryState(e){this.lastMemoryStateValue=e,this.emitMemoryState(e)}recordSkillsState(e){this.lastSkillsStateValue=e,this.emitSkillsState(e)}emitMemoryState(e){if(!e||typeof e!="object")return;const t=e,n=t.scope,s=t.adapter;if(!n||typeof s!="string")return;const r=this.currentRunId?{runId:this.currentRunId}:{};Y("memory:retrieve:started",{...this.createEnvelope("memory:retrieve:started","client-state",r),scope:n,adapter:s,query:t.query??""}),t.recall&&Y("memory:retrieve:completed",{...this.createEnvelope("memory:retrieve:completed","client-state",r),scope:n,adapter:s,fragmentCount:t.recall.fragmentCount??0,hasTools:!!t.recall.hasTools,systemPromptChars:t.recall.systemPromptChars??0,durationMs:t.recall.durationMs??0}),t.snapshot&&Y("memory:snapshot",{...this.createEnvelope("memory:snapshot","client-state",r),scope:n,adapter:s,takenAt:t.snapshot.takenAt,data:t.snapshot.data,facts:t.snapshot.facts??[]})}recordCompactionEvent(e,t){this.lastCompactionEvents.push({eventType:e,value:t}),this.lastCompactionEvents.length>60&&this.lastCompactionEvents.splice(0,this.lastCompactionEvents.length-60),this.emitCompactionEvent(e,t)}recordCompactionState(e){this.recordCompactionEvent("compaction:state",e)}emitCompactionEvent(e,t){const n=this.currentRunId?{runId:this.currentRunId}:{};if(e==="compaction:started"){const s=Ii(t);Y("compaction:started",{...this.createEnvelope("compaction:started","client-state",n),...s});return}if(e==="compaction:ended"){const s=Ii(t);Y("compaction:ended",{...this.createEnvelope("compaction:ended","client-state",n),...s});return}if(e==="compaction:state"){const s=ch(t);if(!s)return;Y("compaction:state",{...this.createEnvelope("compaction:state","client-state",n),...s})}}emitSkillsState(e){if(!e||typeof e!="object")return;const t=e,n=Array.isArray(t.catalog)?t.catalog:[],s=Array.isArray(t.activated)?t.activated:[],r=this.currentRunId?{runId:this.currentRunId}:{};Y("skills:snapshot",{...this.createEnvelope("skills:snapshot","client-state",r),catalog:n,activated:s})}onReplayState(){this.lastMemoryStateValue!=null&&this.emitMemoryState(this.lastMemoryStateValue);for(const e of this.lastCompactionEvents)this.emitCompactionEvent(e.eventType,e.value);this.lastSkillsStateValue!=null&&this.emitSkillsState(this.lastSkillsStateValue)}getCurrentRunEventContext(){if(this.currentRunId)return{threadId:this.currentRunThreadId??this.chatOptions.threadId??"",runId:this.currentRunId}}getCurrentOrLastRunEventContext(){return this.getCurrentRunEventContext()??this.lastRunEventContext}findToolCallContext(e){const t={toolCallId:e},n=this.getCurrentRunEventContext();return n?{threadId:n.threadId,runId:n.runId,toolCallId:e}:this.chatOptions.threadId?{threadId:this.chatOptions.threadId,toolCallId:e}:t}async applyFixture(e){const t=this.chatOptions.getMessages(),n=e.threadId??this.chatOptions.threadId??"";if(e.execute){await this.executeFixture(e,t,n);return}const{message:s,toolCallId:r}=this.createReplayMessageFromFixture(e,t),i=s.id;this.events.messageAppended(s,void 0,{threadId:n,toolCallId:r,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,s]),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:n,...e.runId?{runId:e.runId}:{},toolName:e.toolName,input:e.input,output:e.output,messageId:i,toolCallId:r,...e.execute!==void 0?{execute:e.execute}:{},...e.message?{message:e.message}:{},...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}async executeFixture(e,t,n){const s=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i={id:r,role:"assistant",parts:[{type:"tool-call",id:s,name:e.toolName,arguments:Dn(e.input),input:e.input,state:"input-complete"}],createdAt:new Date};this.events.messageAppended(i,void 0,{threadId:n,toolCallId:s,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,i]),this.emitSnapshot();const o=this.findClientTool(e.toolName)?.execute;if(!o){console.warn(`[ai-devtools] tool fixture "${e.toolName}" requested execute=true but no client tool implementation is registered; replaying saved output instead.`),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:s,threadId:n,output:e.output,errorText:e.errorText});return}let a;try{a=await o(e.input)}catch(u){console.error(`[ai-devtools] tool fixture "${e.toolName}" execute threw`,u),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:s,threadId:n,output:null,errorText:u instanceof Error?`${u.name}: ${u.message}`:`Tool execution failed: ${String(u)}`});return}this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:s,threadId:n,output:a})}addToolResultForFixture(e){const t=e.errorText?"output-error":"output-available";this.events.toolResultAdded(e.toolCallId,e.fixture.toolName,e.output,t,{threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolCallId:e.toolCallId}),this.chatOptions.addToolResult(e.toolCallId,e.output,e.errorText),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolName:e.fixture.toolName,input:e.fixture.input,output:e.output,execute:!0,messageId:e.messageId,toolCallId:e.toolCallId,...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}createReplayMessageFromFixture(e,t){const n=this.cloneFixtureSourceMessage(e,t);if(n)return n;const s=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i=e.errorText?"error":"complete";return{toolCallId:s,message:{id:r,role:"assistant",parts:[{type:"tool-call",id:s,name:e.toolName,arguments:Dn(e.input),input:e.input,state:"input-complete",output:e.output},{type:"tool-result",toolCallId:s,content:Dn(e.output),state:i,...e.errorText?{error:e.errorText}:{}}],createdAt:new Date}}}cloneFixtureSourceMessage(e,t){const n=e.message;if(!n||!Array.isArray(n.parts))return;const s=this.createFixtureToolCallIdMap(n.parts,t),r=n.parts.map(a=>gh(a,s)).filter(a=>!!a),i=e.toolCallId?s.get(e.toolCallId):void 0;if(vh(r,{...i?{mappedToolCallId:i}:{},output:e.output}),r.length===0)return;const o=(e.toolCallId?s.get(e.toolCallId):void 0)??mh(r);if(o)return{toolCallId:o,message:{id:this.resolveFixtureMessageId(n.id,t),role:n.role,parts:r,createdAt:new Date}}}createFixtureToolCallIdMap(e,t){const n=new Map;for(const s of e)!ta(s)||s.type!=="tool-call"||typeof s.id=="string"&&n.set(s.id,this.resolveFixtureToolCallId(s.id,t));return n}resolveFixtureMessageId(e,t){return e&&!t.some(n=>n.id===e)?e:this.chatOptions.generateId("fixture-msg")}resolveFixtureToolCallId(e,t){return e&&!Sh(t,e)?e:this.chatOptions.generateId("fixture-tool-call")}findClientTool(e){const t=this.chatOptions.getTools?.();if(t){for(const n of t)if(n.name===e)return n}}};function ta(e){return typeof e=="object"&&e!==null}function Dn(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 ph(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 gh(e,t){if(!ta(e)||typeof e.type!="string")return;const n={...e};return e.type==="tool-call"&&typeof e.id=="string"&&(n.id=t.get(e.id)??e.id),e.type==="tool-result"&&typeof e.toolCallId=="string"&&(n.toolCallId=t.get(e.toolCallId)??e.toolCallId),n}function mh(e){const t=e.find(n=>n.type==="tool-call");return t?.type==="tool-call"?t.id:void 0}function vh(e,t){for(const n of e){if(n.type!=="tool-result")continue;const s=e.find(r=>r.type==="tool-call"&&r.id===n.toolCallId&&r.output===void 0);s&&(s.output=Array.isArray(n.content)?n.content:ph(n.content))}if(t.mappedToolCallId&&t.output!==void 0){const n=e.find(s=>s.type==="tool-call"&&s.id===t.mappedToolCallId&&s.output===void 0);n&&(n.output=t.output)}}function Sh(e,t){return e.some(n=>n.parts.some(s=>s.type==="tool-call"?s.id===t:s.type==="tool-result"?s.toolCallId===t:!1))}var yh=class extends Qd{getClientId;helper;constructor(e,t){super(e()),this.getClientId=e,this.helper=t}emitEvent(e,t){this.clientId=this.getClientId(),super.emitEvent(e,t)}afterEmit(e){e&&this.helper.recordStreamId(e),this.helper.emitSnapshot()}textUpdated(e,t,n,s){super.textUpdated(e,t,n,s??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}thinkingUpdated(e,t,n,s,r){super.thinkingUpdated(e,t,n,s,r??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}messageAppended(e,t,n){super.messageAppended(e,t,n??this.helper.getCurrentRunEventContext()),this.afterEmit(t)}toolCallStateChanged(e,t,n,s,r,i,o){super.toolCallStateChanged(e,t,n,s,r,i,o??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}structuredOutputChanged(e,t,n,s,r){super.structuredOutputChanged(e,t,n,s,r??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(t)}approvalRequested(e,t,n,s,r,i,o){super.approvalRequested(e,t,n,s,r,i,o??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(e)}toolResultAdded(e,t,n,s,r){super.toolResultAdded(e,t,n,s,r??this.helper.getCurrentRunEventContext()),this.afterEmit()}toolApprovalResponded(e,t,n,s){super.toolApprovalResponded(e,t,n,s??this.helper.getCurrentRunEventContext()),this.afterEmit()}clientCreated(e){super.clientCreated(e),this.afterEmit()}loadingChanged(e){super.loadingChanged(e),this.afterEmit()}errorChanged(e){super.errorChanged(e),this.afterEmit()}reloaded(e){super.reloaded(e),this.afterEmit()}stopped(){super.stopped(),this.afterEmit()}messagesCleared(){super.messagesCleared(),this.afterEmit()}messageSent(e,t){super.messageSent(e,t),this.afterEmit()}toolFixtureApplied(e){super.toolFixtureApplied(e),this.afterEmit()}};function Ih(e){return new fh(e)}var bi=Object.freeze([]),Rh=Object.freeze([]);function Qf(e){const t=(0,I.useId)(),n=e.threadId??t,[s,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,m]=(0,I.useState)(!1),[v,S]=(0,I.useState)([]),[C,w]=(0,I.useState)(null),[b,R]=(0,I.useState)(()=>({interrupts:bi,pendingInterrupts:bi,interruptErrors:Rh,resuming:!1})),y=(0,I.useRef)(e.initialMessages||[]),T=(0,I.useRef)(!0),_=(0,I.useRef)(!1),E=(0,I.useRef)(null),x=(0,I.useRef)(null),N=(0,I.useRef)(null);y.current=s;const F=(0,I.useRef)(e);F.current=e;const j=(0,I.useCallback)(D=>{D&&(w(D.getCurrentRunId()),R(D.getInterruptState()))},[]),{client:A,initialization:le}=(0,I.useMemo)(()=>{const D=e.initialMessages||[];T.current=!1;const O=F.current,ue=O.connection?{connection:O.connection}:{fetcher:O.fetcher},J={current:void 0},Re=()=>{const M=J.current;if(!(!M||E.current!==M))return M},st={ready:!1,callbacks:[]},z=M=>{if(!st.ready){st.callbacks.push(M);return}const $=J.current;!$||E.current!==$||M()},rt=new uh({devtoolsBridgeFactory:Ih,...ue,initialMessages:D,...typeof O.threadId=="string"&&O.persistence?{persistence:O.persistence,threadId:O.threadId}:{...O.threadId!==void 0&&{threadId:O.threadId}},...O.body!==void 0&&{body:O.body},...O.forwardedProps!==void 0&&{forwardedProps:O.forwardedProps},...O.byok!==void 0&&{byok:O.byok},byokProvider:()=>F.current.byokProvider?.(),...O.initialResumeSnapshot!==void 0&&{initialResumeSnapshot:O.initialResumeSnapshot},...O.context!==void 0&&{context:O.context},devtools:{...O.devtools,framework:"react",hookName:"useChat",outputKind:O.outputSchema?"structured":"chat"},onResponse:M=>{if(Re())return F.current.onResponse?.(M)},onChunk:M=>{z(()=>{F.current.onChunk?.(M)})},onFinish:M=>{z(()=>{F.current.onFinish?.(M)})},onError:M=>{z(()=>{F.current.onError?.(M)})},...O.tools!==void 0&&{tools:O.tools},...O.interrupts!==void 0&&{interrupts:O.interrupts},onCustomEvent:(M,$,ce)=>{z(()=>{F.current.onCustomEvent?.(M,$,ce)})},...e.streamProcessor!==void 0&&{streamProcessor:e.streamProcessor},onMessagesChange:M=>{z(()=>{r(M)})},onLoadingChange:M=>{z(()=>{const $=Re();$&&(o(M),j($))})},onErrorChange:M=>{z(()=>{u(M)})},onStatusChange:M=>{z(()=>{c(M)})},onSubscriptionChange:M=>{z(()=>{d(M)})},onConnectionStatusChange:M=>{z(()=>{p(M)})},onSessionGeneratingChange:M=>{z(()=>{m(M)})},...F.current.queue!==void 0&&{queue:F.current.queue},onQueueChange:M=>{z(()=>{S(M)})},onRunIdChange:M=>{z(()=>{w(M)})},onResumeStateChange:(M,$)=>{z(()=>{R(ce=>({...ce,interrupts:$,pendingInterrupts:$}))})},onInterruptStateChange:(M,$)=>{z(()=>{R(M),F.current.onInterruptStateChange?.(M,$)})}});return J.current=rt,{client:rt,initialization:st}},[n,j]);(0,I.useEffect)(()=>{E.current=A;try{for(;le.callbacks.length>0;){if(E.current!==A){le.callbacks.length=0;break}le.callbacks.shift()?.()}}finally{le.ready=!0}},[A,le]),(0,I.useEffect)(()=>{const D=A.getMessages();D!==y.current&&r(D)},[A]),(0,I.useEffect)(()=>{A.updateOptions({body:e.body})},[A,e.body]),(0,I.useEffect)(()=>{e.forwardedProps!==void 0&&A.updateOptions({forwardedProps:e.forwardedProps})},[A,e.forwardedProps]),(0,I.useEffect)(()=>{e.tools!==void 0&&A.updateOptions({tools:e.tools})},[A,e.tools]),(0,I.useEffect)(()=>{A.updateOptions({context:e.context})},[A,e.context]),(0,I.useEffect)(()=>{e.queue!==void 0&&A.updateOptions({queue:e.queue})},[A,e.queue]),(0,I.useEffect)(()=>{e.live?(A.subscribe(),_.current=!0):_.current&&(A.unsubscribe(),_.current=!1)},[A,e.live]),(0,I.useEffect)(()=>(A.attach(),()=>{A.detach()}),[A]),(0,I.useEffect)(()=>(N.current?.client===A&&(clearTimeout(N.current.timeout),N.current=null),x.current&&(clearTimeout(x.current),x.current=null),A.mountDevtools(),j(A),()=>{x.current=setTimeout(()=>{E.current===A&&(E.current=null),x.current=null},0);const D={client:A,timeout:setTimeout(()=>{F.current.live?A.unsubscribe():A.stop(),A.dispose(),N.current===D&&(N.current=null)},0)};N.current=D}),[A,j]);const Ks=(0,I.useCallback)(async(D,O)=>{try{await A.sendMessage(D,void 0,O)}finally{j(A)}},[A,j]),Qs=(0,I.useCallback)(D=>{A.cancelQueued(D)},[A,j]),Ws=(0,I.useCallback)(async D=>{try{await A.append(D)}finally{j(A)}},[A,j]),Js=(0,I.useCallback)(async()=>{try{await A.reload()}finally{j(A)}},[A,j]),bt=(0,I.useCallback)(()=>{A.stop()},[A]),wt=(0,I.useCallback)(()=>{A.clear(),j(A)},[A,j]),Sn=(0,I.useCallback)(D=>{A.setMessagesManually(D)},[A]),yn=(0,I.useCallback)(async D=>{await A.addToolResult(D)},[A]),Et=(0,I.useCallback)(async D=>{await A.addToolApprovalResponse(D),j(A)},[A,j]),xe=(0,I.useCallback)(async(D,O)=>{const ue=await A.resumeInterrupts(D,O??void 0);return j(A),ue},[A,j]),In=(0,I.useCallback)(D=>{A.resolveInterrupts(D)},[A]),Rn=(0,I.useCallback)(()=>{A.cancelInterrupts()},[A]),tt=(0,I.useCallback)(()=>{A.retryInterrupts()},[A]),nt=(0,I.useCallback)((D,O)=>A.resumeInterruptsUnsafe(D,O),[A]),re=A.getMessages(),W=(0,I.useMemo)(()=>{let D=-1;for(let O=re.length-1;O>=0;O--)if(re[O]?.role==="user"){D=O;break}if(D===-1)return null;for(let O=re.length-1;O>D;O--){const ue=re[O];if(ue?.role!=="assistant")continue;const J=ue.parts.find(Re=>Re.type==="structured-output");if(J)return J}return null},[re]),Tt=(0,I.useMemo)(()=>W?W.partial??W.data??{}:{},[W]),_t=(0,I.useMemo)(()=>!W||W.status!=="complete"?null:W.data,[W]);return{messages:re,sendMessage:Ks,append:Ws,reload:Js,stop:bt,isLoading:i,error:a,status:l,isSubscribed:h,connectionStatus:f,sessionGenerating:g,setMessages:Sn,clear:wt,addToolResult:yn,addToolApprovalResponse:Et,queue:v,cancelQueued:Qs,runId:C,interrupts:b.interrupts,pendingInterrupts:b.pendingInterrupts,interruptErrors:b.interruptErrors,resuming:b.resuming,resolveInterrupts:In,cancelInterrupts:Rn,retryInterrupts:tt,resumeInterruptsUnsafe:nt,resumeInterrupts:xe,partial:Tt,final:_t}}function Wf(e){return(0,I.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>Vu)}var Jf=new Uint8Array(128).fill(128);function be(e,t){return typeof e=="function"?e(t):e}function ee(e,t){return n=>{t.setState(s=>({...s,[e]:be(n,s[e])}))}}function vn(e){return e instanceof Function}function Ch(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function bh(e,t){const n=[],s=r=>{r.forEach(i=>{n.push(i);const o=t(i);o!=null&&o.length&&s(o)})};return s(e),n}function P(e,t,n){let s=[],r;return i=>{let o;n.key&&n.debug&&(o=Date.now());const a=e(i);if(!(a.length!==s.length||a.some((l,c)=>s[c]!==l)))return r;s=a;let u;if(n.key&&n.debug&&(u=Date.now()),r=t(...a),n==null||n.onChange==null||n.onChange(r),n.key&&n.debug&&n!=null&&n.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`,`
|
|
2
5
|
font-size: .6rem;
|
|
3
6
|
font-weight: bold;
|
|
4
|
-
color: hsl(${Math.max(0,Math.min(120-120*h,120))}deg 100% 31%);`,n?.key)}return r}}function L(e,t,n,s){return{debug:()=>{var r;return(r=e?.debugAll)!=null?r:e[t]},key:!1,onChange:s}}function ju(e,t,n,s){const r=()=>{var o;return(o=i.getValue())!=null?o:e.options.renderFallbackValue},i={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(s),renderValue:r,getContext:P(()=>[e,n,t,i],(o,a,u,l)=>({table:o,column:a,row:u,cell:l,getValue:l.getValue,renderValue:l.renderValue}),L(e.options,"debugCells","cell.getContext"))};return e._features.forEach(o=>{o.createCell==null||o.createCell(i,n,t,e)},{}),i}function Gu(e,t,n,s){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:s,depth:n,columnDef:o,columns:[],getFlatColumns:P(()=>[!0],()=>{var h;return[c,...(h=c.columns)==null?void 0:h.flatMap(d=>d.getFlatColumns())]},L(e.options,"debugColumns","column.getFlatColumns")),getLeafColumns:P(()=>[e._getOrderColumnsFn()],h=>{var d;return(d=c.columns)!=null&&d.length?h(c.columns.flatMap(f=>f.getLeafColumns())):[c]},L(e.options,"debugColumns","column.getLeafColumns"))};for(const h of e._features)h.createColumn==null||h.createColumn(c,e);return c}var V="debugHeaders";function Pr(e,t,n){var s;let r={id:(s=n.id)!=null?s:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],o=a=>{a.subHeaders&&a.subHeaders.length&&a.subHeaders.map(o),i.push(a)};return o(r),i},getContext:()=>({table:e,header:r,column:t})};return e._features.forEach(i=>{i.createHeader==null||i.createHeader(r,e)}),r}var Uu={createTable:e=>{e.getHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,s,r)=>{var i,o;const a=(i=s?.map(c=>n.find(h=>h.id===c)).filter(Boolean))!=null?i:[],u=(o=r?.map(c=>n.find(h=>h.id===c)).filter(Boolean))!=null?o:[],l=n.filter(c=>!(s!=null&&s.includes(c.id))&&!(r!=null&&r.includes(c.id)));return Pt(t,[...a,...l,...u],e)},L(e.options,V,"getHeaderGroups")),e.getCenterHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,s,r)=>(n=n.filter(i=>!(s!=null&&s.includes(i.id))&&!(r!=null&&r.includes(i.id))),Pt(t,n,e,"center")),L(e.options,V,"getCenterHeaderGroups")),e.getLeftHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,s)=>{var r;return Pt(t,(r=s?.map(i=>n.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"left")},L(e.options,V,"getLeftHeaderGroups")),e.getRightHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,s)=>{var r;return Pt(t,(r=s?.map(i=>n.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"right")},L(e.options,V,"getRightHeaderGroups")),e.getFooterGroups=P(()=>[e.getHeaderGroups()],t=>[...t].reverse(),L(e.options,V,"getFooterGroups")),e.getLeftFooterGroups=P(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),L(e.options,V,"getLeftFooterGroups")),e.getCenterFooterGroups=P(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),L(e.options,V,"getCenterFooterGroups")),e.getRightFooterGroups=P(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),L(e.options,V,"getRightFooterGroups")),e.getFlatHeaders=P(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),L(e.options,V,"getFlatHeaders")),e.getLeftFlatHeaders=P(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),L(e.options,V,"getLeftFlatHeaders")),e.getCenterFlatHeaders=P(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),L(e.options,V,"getCenterFlatHeaders")),e.getRightFlatHeaders=P(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),L(e.options,V,"getRightFlatHeaders")),e.getCenterLeafHeaders=P(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var s;return!((s=n.subHeaders)!=null&&s.length)}),L(e.options,V,"getCenterLeafHeaders")),e.getLeftLeafHeaders=P(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var s;return!((s=n.subHeaders)!=null&&s.length)}),L(e.options,V,"getLeftLeafHeaders")),e.getRightLeafHeaders=P(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var s;return!((s=n.subHeaders)!=null&&s.length)}),L(e.options,V,"getRightLeafHeaders")),e.getLeafHeaders=P(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,s)=>{var r,i,o,a,u,l;return[...(r=(i=t[0])==null?void 0:i.headers)!=null?r:[],...(o=(a=n[0])==null?void 0:a.headers)!=null?o:[],...(u=(l=s[0])==null?void 0:l.headers)!=null?u:[]].map(c=>c.getLeafHeaders()).flat()},L(e.options,V,"getLeafHeaders"))}};function Pt(e,t,n,s){var r,i;let o=0;const a=function(h,d){d===void 0&&(d=1),o=Math.max(o,d),h.filter(f=>f.getIsVisible()).forEach(f=>{var p;(p=f.columns)!=null&&p.length&&a(f.columns,d+1)},0)};a(e);let u=[];const l=(h,d)=>{const f={depth:d,id:[s,`${d}`].filter(Boolean).join("_"),headers:[]},p=[];h.forEach(g=>{const m=[...p].reverse()[0],v=g.column.depth===f.depth;let S,C=!1;if(v&&g.column.parent?S=g.column.parent:(S=g.column,C=!0),m&&m?.column===S)m.subHeaders.push(g);else{const w=Pr(n,S,{id:[s,d,S.id,g?.id].filter(Boolean).join("_"),isPlaceholder:C,placeholderId:C?`${p.filter(b=>b.column===S).length}`:void 0,depth:d,index:p.length});w.subHeaders.push(g),p.push(w)}f.headers.push(g),g.headerGroup=f}),u.push(f),d>0&&l(p,d-1)};l(t.map((h,d)=>Pr(n,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(v=>{let{colSpan:S,rowSpan:C}=v;f+=S,g.push(C)})):f=1;const m=Math.min(...g);return p=p+m,d.colSpan=f,d.rowSpan=p,{colSpan:f,rowSpan:p}});return c((r=(i=u[0])==null?void 0:i.headers)!=null?r:[]),u}var $u=(e,t,n,s,r,i,o)=>{let a={id:t,index:s,original:n,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,s),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,s),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:()=>Du(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:P(()=>[e.getAllLeafColumns()],u=>u.map(l=>ju(e,a,l,l.id)),L(e.options,"debugRows","getAllCells")),_getAllCellsByColumnId:P(()=>[a.getAllCells()],u=>u.reduce((l,c)=>(l[c.column.id]=c,l),{}),L(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},Bu={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()}}},Co=(e,t,n)=>{var s,r;const i=n==null||(s=n.toString())==null?void 0:s.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(i))};Co.autoRemove=e=>ie(e);var bo=(e,t,n)=>{var s;return!!(!((s=e.getValue(t))==null||(s=s.toString())==null)&&s.includes(n))};bo.autoRemove=e=>ie(e);var wo=(e,t,n)=>{var s;return((s=e.getValue(t))==null||(s=s.toString())==null?void 0:s.toLowerCase())===n?.toLowerCase()};wo.autoRemove=e=>ie(e);var Eo=(e,t,n)=>{var s;return(s=e.getValue(t))==null?void 0:s.includes(n)};Eo.autoRemove=e=>ie(e);var To=(e,t,n)=>!n.some(s=>{var r;return!((r=e.getValue(t))!=null&&r.includes(s))});To.autoRemove=e=>ie(e)||!(e!=null&&e.length);var _o=(e,t,n)=>n.some(s=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(s)});_o.autoRemove=e=>ie(e)||!(e!=null&&e.length);var Ao=(e,t,n)=>e.getValue(t)===n;Ao.autoRemove=e=>ie(e);var Mo=(e,t,n)=>e.getValue(t)==n;Mo.autoRemove=e=>ie(e);var ks=(e,t,n)=>{let[s,r]=n;const i=e.getValue(t);return i>=s&&i<=r};ks.resolveFilterValue=e=>{let[t,n]=e,s=typeof t!="number"?parseFloat(t):t,r=typeof n!="number"?parseFloat(n):n,i=t===null||Number.isNaN(s)?-1/0:s,o=n===null||Number.isNaN(r)?1/0:r;if(i>o){const a=i;i=o,o=a}return[i,o]};ks.autoRemove=e=>ie(e)||ie(e[0])&&ie(e[1]);var ge={includesString:Co,includesStringSensitive:bo,equalsString:wo,arrIncludes:Eo,arrIncludesAll:To,arrIncludesSome:_o,equals:Ao,weakEquals:Mo,inNumberRange:ks};function ie(e){return e==null||e===""}var Hu={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:ee("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],s=n?.getValue(e.id);return typeof s=="string"?ge.includesString:typeof s=="number"?ge.inNumberRange:typeof s=="boolean"||s!==null&&typeof s=="object"?ge.equals:Array.isArray(s)?ge.arrIncludes:ge.weakEquals},e.getFilterFn=()=>{var n,s;return un(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(s=t.options.filterFns)==null?void 0:s[e.columnDef.filterFn])!=null?n:ge[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,s,r;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((s=t.options.enableColumnFilters)!=null?s:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(s=>s.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,s;return(n=(s=t.getState().columnFilters)==null?void 0:s.findIndex(r=>r.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(s=>{const r=e.getFilterFn(),i=s?.find(c=>c.id===e.id),o=Ce(n,i?i.value:void 0);if(Lr(r,o,e)){var a;return(a=s?.filter(c=>c.id!==e.id))!=null?a:[]}const u={id:e.id,value:o};if(i){var l;return(l=s?.map(c=>c.id===e.id?u:c))!=null?l:[]}return s!=null&&s.length?[...s,u]:[u]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),s=r=>{var i;return(i=Ce(t,r))==null?void 0:i.filter(o=>{const a=n.find(u=>u.id===o.id);return!(a&&Lr(a.getFilterFn(),o.value,a))})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(s)},e.resetColumnFilters=t=>{var n,s;e.setColumnFilters(t?[]:(n=(s=e.initialState)==null?void 0:s.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function Lr(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}var zu=(e,t,n)=>n.reduce((s,r)=>{const i=r.getValue(e);return s+(typeof i=="number"?i:0)},0),Vu=(e,t,n)=>{let s;return n.forEach(r=>{const i=r.getValue(e);i!=null&&(s>i||s===void 0&&i>=i)&&(s=i)}),s},qu=(e,t,n)=>{let s;return n.forEach(r=>{const i=r.getValue(e);i!=null&&(s<i||s===void 0&&i>=i)&&(s=i)}),s},Ku=(e,t,n)=>{let s,r;return n.forEach(i=>{const o=i.getValue(e);o!=null&&(s===void 0?o>=o&&(s=r=o):(s>o&&(s=o),r<o&&(r=o)))}),[s,r]},Qu=(e,t)=>{let n=0,s=0;if(t.forEach(r=>{let i=r.getValue(e);i!=null&&(i=+i)>=i&&(++n,s+=i)}),n)return s/n},Wu=(e,t)=>{if(!t.length)return;const n=t.map(i=>i.getValue(e));if(!Nu(n))return;if(n.length===1)return n[0];const s=Math.floor(n.length/2),r=n.sort((i,o)=>i-o);return n.length%2!==0?r[s]:(r[s-1]+r[s])/2},Ju=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),Xu=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,Yu=(e,t)=>t.length,wn={sum:zu,min:Vu,max:qu,extent:Ku,mean:Qu,median:Wu,unique:Ju,uniqueCount:Xu,count:Yu},Zu={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:ee("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(s=>s!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,s;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((s=t.options.enableGrouping)!=null?s:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],s=n?.getValue(e.id);if(typeof s=="number")return wn.sum;if(Object.prototype.toString.call(s)==="[object Date]")return wn.extent},e.getAggregationFn=()=>{var n,s;if(!e)throw new Error;return un(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(s=t.options.aggregationFns)==null?void 0:s[e.columnDef.aggregationFn])!=null?n:wn[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,s;e.setGrouping(t?[]:(n=(s=e.initialState)==null?void 0:s.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const s=t.getColumn(n);return s!=null&&s.columnDef.getGroupingValue?(e._groupingValuesCache[n]=s.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,s)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var r;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((r=n.subRows)!=null&&r.length)}}};function ec(e,t,n){if(!(t!=null&&t.length)||!n)return e;const s=e.filter(r=>!t.includes(r.id));return n==="remove"?s:[...t.map(r=>e.find(i=>i.id===r)).filter(Boolean),...s]}var tc={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:ee("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=P(n=>[ht(t,n)],n=>n.findIndex(s=>s.id===e.id),L(t.options,"debugColumns","getIndex")),e.getIsFirstColumn=n=>{var s;return((s=ht(t,n)[0])==null?void 0:s.id)===e.id},e.getIsLastColumn=n=>{var s;const r=ht(t,n);return((s=r[r.length-1])==null?void 0:s.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=P(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,s)=>r=>{let i=[];if(!(t!=null&&t.length))i=r;else{const o=[...t],a=[...r];for(;a.length&&o.length;){const u=o.shift(),l=a.findIndex(c=>c.id===u);l>-1&&i.push(a.splice(l,1)[0])}i=[...i,...a]}return ec(i,n,s)},L(e.options,"debugTable","_getOrderColumnsFn"))}},En=()=>({left:[],right:[]}),nc={getInitialState:e=>({columnPinning:En(),...e}),getDefaultOptions:e=>({onColumnPinningChange:ee("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const s=e.getLeafColumns().map(r=>r.id).filter(Boolean);t.setColumnPinning(r=>{var i,o;if(n==="right"){var a,u;return{left:((a=r?.left)!=null?a:[]).filter(h=>!(s!=null&&s.includes(h))),right:[...((u=r?.right)!=null?u:[]).filter(h=>!(s!=null&&s.includes(h))),...s]}}if(n==="left"){var l,c;return{left:[...((l=r?.left)!=null?l:[]).filter(h=>!(s!=null&&s.includes(h))),...s],right:((c=r?.right)!=null?c:[]).filter(h=>!(s!=null&&s.includes(h)))}}return{left:((i=r?.left)!=null?i:[]).filter(h=>!(s!=null&&s.includes(h))),right:((o=r?.right)!=null?o:[]).filter(h=>!(s!=null&&s.includes(h)))}})},e.getCanPin=()=>e.getLeafColumns().some(n=>{var s,r,i;return((s=n.columnDef.enablePinning)!=null?s:!0)&&((r=(i=t.options.enableColumnPinning)!=null?i:t.options.enablePinning)!=null?r:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(a=>a.id),{left:s,right:r}=t.getState().columnPinning,i=n.some(a=>s?.includes(a)),o=n.some(a=>r?.includes(a));return i?"left":o?"right":!1},e.getPinnedIndex=()=>{var n,s;const r=e.getIsPinned();return r?(n=(s=t.getState().columnPinning)==null||(s=s[r])==null?void 0:s.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=P(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,s,r)=>{const i=[...s??[],...r??[]];return n.filter(o=>!i.includes(o.column.id))},L(t.options,"debugRows","getCenterVisibleCells")),e.getLeftVisibleCells=P(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,s)=>(s??[]).map(r=>n.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"left"})),L(t.options,"debugRows","getLeftVisibleCells")),e.getRightVisibleCells=P(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,s)=>(s??[]).map(r=>n.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"right"})),L(t.options,"debugRows","getRightVisibleCells"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,s;return e.setColumnPinning(t?En():(n=(s=e.initialState)==null?void 0:s.columnPinning)!=null?n:En())},e.getIsSomeColumnsPinned=t=>{var n;const s=e.getState().columnPinning;if(!t){var r,i;return!!((r=s.left)!=null&&r.length||(i=s.right)!=null&&i.length)}return!!((n=s[t])!=null&&n.length)},e.getLeftLeafColumns=P(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(s=>t.find(r=>r.id===s)).filter(Boolean),L(e.options,"debugColumns","getLeftLeafColumns")),e.getRightLeafColumns=P(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(s=>t.find(r=>r.id===s)).filter(Boolean),L(e.options,"debugColumns","getRightLeafColumns")),e.getCenterLeafColumns=P(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,s)=>{const r=[...n??[],...s??[]];return t.filter(i=>!r.includes(i.id))},L(e.options,"debugColumns","getCenterLeafColumns"))}};function sc(e){return e||(typeof document<"u"?document:null)}var Lt={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},Tn=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),rc={getDefaultColumnDef:()=>Lt,getInitialState:e=>({columnSizing:{},columnSizingInfo:Tn(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:ee("columnSizing",e),onColumnSizingInfoChange:ee("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,s,r;const i=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Lt.minSize,(s=i??e.columnDef.size)!=null?s:Lt.size),(r=e.columnDef.maxSize)!=null?r:Lt.maxSize)},e.getStart=P(n=>[n,ht(t,n),t.getState().columnSizing],(n,s)=>s.slice(0,e.getIndex(n)).reduce((r,i)=>r+i.getSize(),0),L(t.options,"debugColumns","getStart")),e.getAfter=P(n=>[n,ht(t,n),t.getState().columnSizing],(n,s)=>s.slice(e.getIndex(n)+1).reduce((r,i)=>r+i.getSize(),0),L(t.options,"debugColumns","getAfter")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:s,...r}=n;return r})},e.getCanResize=()=>{var n,s;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((s=t.options.enableColumnResizing)!=null?s:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const s=r=>{if(r.subHeaders.length)r.subHeaders.forEach(s);else{var i;n+=(i=r.column.getSize())!=null?i:0}};return s(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const s=t.getColumn(e.column.id),r=s?.getCanResize();return i=>{if(!s||!r||(i.persist==null||i.persist(),_n(i)&&i.touches&&i.touches.length>1))return;const o=e.getSize(),a=e?e.getLeafHeaders().map(v=>[v.column.id,v.column.getSize()]):[[s.id,s.getSize()]],u=_n(i)?Math.round(i.touches[0].clientX):i.clientX,l={},c=(v,S)=>{typeof S=="number"&&(t.setColumnSizingInfo(C=>{var w,b;const R=t.options.columnResizeDirection==="rtl"?-1:1,y=(S-((w=C?.startOffset)!=null?w:0))*R,T=Math.max(y/((b=C?.startSize)!=null?b:0),-.999999);return C.columnSizingStart.forEach(_=>{let[E,x]=_;l[E]=Math.round(Math.max(x+x*T,0)*100)/100}),{...C,deltaOffset:y,deltaPercentage:T}}),(t.options.columnResizeMode==="onChange"||v==="end")&&t.setColumnSizing(C=>({...C,...l})))},h=v=>c("move",v),d=v=>{c("end",v),t.setColumnSizingInfo(S=>({...S,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},f=sc(n),p={moveHandler:v=>h(v.clientX),upHandler:v=>{f?.removeEventListener("mousemove",p.moveHandler),f?.removeEventListener("mouseup",p.upHandler),d(v.clientX)}},g={moveHandler:v=>(v.cancelable&&(v.preventDefault(),v.stopPropagation()),h(v.touches[0].clientX),!1),upHandler:v=>{var S;f?.removeEventListener("touchmove",g.moveHandler),f?.removeEventListener("touchend",g.upHandler),v.cancelable&&(v.preventDefault(),v.stopPropagation()),d((S=v.touches[0])==null?void 0:S.clientX)}},m=ic()?{passive:!1}:!1;_n(i)?(f?.addEventListener("touchmove",g.moveHandler,m),f?.addEventListener("touchend",g.upHandler,m)):(f?.addEventListener("mousemove",p.moveHandler,m),f?.addEventListener("mouseup",p.upHandler,m)),t.setColumnSizingInfo(v=>({...v,startOffset:u,startSize:o,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:s.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?Tn():(n=e.initialState.columnSizingInfo)!=null?n:Tn())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0}}},Ft=null;function ic(){if(typeof Ft=="boolean")return Ft;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ft=e,Ft}function _n(e){return e.type==="touchstart"}var oc={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:ee("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(s=>({...s,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,s;const r=e.columns;return(n=r.length?r.some(i=>i.getIsVisible()):(s=t.getState().columnVisibility)==null?void 0:s[e.id])!=null?n:!0},e.getCanHide=()=>{var n,s;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((s=t.options.enableHiding)!=null?s:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=P(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(s=>s.column.getIsVisible()),L(t.options,"debugRows","_getAllVisibleCells")),e.getVisibleCells=P(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,s,r)=>[...n,...s,...r],L(t.options,"debugRows","getVisibleCells"))},createTable:e=>{const t=(n,s)=>P(()=>[s(),s().filter(r=>r.getIsVisible()).map(r=>r.id).join("_")],r=>r.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),L(e.options,"debugColumns",n));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var s;e.setColumnVisibility(n?{}:(s=e.initialState.columnVisibility)!=null?s:{})},e.toggleAllColumnsVisible=n=>{var s;n=(s=n)!=null?s:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((r,i)=>({...r,[i.id]:n||!(i.getCanHide!=null&&i.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var s;e.toggleAllColumnsVisible((s=n.target)==null?void 0:s.checked)}}};function ht(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}var ac={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()}}},lc={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:ee("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const s=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof s=="string"||typeof s=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,s,r,i;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((s=t.options.enableGlobalFilter)!=null?s:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&((i=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?i:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>ge.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:s}=e.options;return un(s)?s:s==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[s])!=null?t:ge[s]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},uc={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:ee("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var s,r;if(!t){e._queue(()=>{t=!0});return}if((s=(r=e.options.autoResetAll)!=null?r:e.options.autoResetExpanded)!=null?s:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=s=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(s),e.toggleAllRowsExpanded=s=>{s??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=s=>{var r,i;e.setExpanded(s?{}:(r=(i=e.initialState)==null?void 0:i.expanded)!=null?r:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(s=>s.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>s=>{s.persist==null||s.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const s=e.getState().expanded;return s===!0||Object.values(s).some(Boolean)},e.getIsAllRowsExpanded=()=>{const s=e.getState().expanded;return typeof s=="boolean"?s===!0:!(!Object.keys(s).length||e.getRowModel().flatRows.some(r=>!r.getIsExpanded()))},e.getExpandedDepth=()=>{let s=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(r=>{const i=r.split(".");s=Math.max(s,i.length)}),s},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(s=>{var r;const i=s===!0?!0:!!(s!=null&&s[e.id]);let o={};if(s===!0?Object.keys(t.getRowModel().rowsById).forEach(a=>{o[a]=!0}):o=s,n=(r=n)!=null?r:!i,!i&&n)return{...o,[e.id]:!0};if(i&&!n){const{[e.id]:a,...u}=o;return u}return s})},e.getIsExpanded=()=>{var n;const s=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:s===!0||s?.[e.id])},e.getCanExpand=()=>{var n,s,r;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((s=t.options.enableExpanding)!=null?s:!0)&&!!((r=e.subRows)!=null&&r.length)},e.getIsAllParentsExpanded=()=>{let n=!0,s=e;for(;n&&s.parentId;)s=t.getRow(s.parentId,!0),n=s.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},ts=0,ns=10,An=()=>({pageIndex:ts,pageSize:ns}),cc={getInitialState:e=>({...e,pagination:{...An(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:ee("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var s,r;if(!t){e._queue(()=>{t=!0});return}if((s=(r=e.options.autoResetAll)!=null?r:e.options.autoResetPageIndex)!=null?s:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=s=>{const r=i=>Ce(s,i);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(r)},e.resetPagination=s=>{var r;e.setPagination(s?An():(r=e.initialState.pagination)!=null?r:An())},e.setPageIndex=s=>{e.setPagination(r=>{let i=Ce(s,r.pageIndex);const o=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return i=Math.max(0,Math.min(i,o)),{...r,pageIndex:i}})},e.resetPageIndex=s=>{var r,i;e.setPageIndex(s?ts:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageIndex)!=null?r:ts)},e.resetPageSize=s=>{var r,i;e.setPageSize(s?ns:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageSize)!=null?r:ns)},e.setPageSize=s=>{e.setPagination(r=>{const i=Math.max(1,Ce(s,r.pageSize)),o=r.pageSize*r.pageIndex,a=Math.floor(o/i);return{...r,pageIndex:a,pageSize:i}})},e.setPageCount=s=>e.setPagination(r=>{var i;let o=Ce(s,(i=e.options.pageCount)!=null?i:-1);return typeof o=="number"&&(o=Math.max(-1,o)),{...r,pageCount:o}}),e.getPageOptions=P(()=>[e.getPageCount()],s=>{let r=[];return s&&s>0&&(r=[...new Array(s)].fill(null).map((i,o)=>o)),r},L(e.options,"debugTable","getPageOptions")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:s}=e.getState().pagination,r=e.getPageCount();return r===-1?!0:r===0?!1:s<r-1},e.previousPage=()=>e.setPageIndex(s=>s-1),e.nextPage=()=>e.setPageIndex(s=>s+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var s;return(s=e.options.pageCount)!=null?s:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var s;return(s=e.options.rowCount)!=null?s:e.getPrePaginationRowModel().rows.length}}},Mn=()=>({top:[],bottom:[]}),dc={getInitialState:e=>({rowPinning:Mn(),...e}),getDefaultOptions:e=>({onRowPinningChange:ee("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,s,r)=>{const i=s?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(n==="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(n==="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 n;const{enableRowPinning:s,enablePinning:r}=t.options;return typeof s=="function"?s(e):(n=s??r)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:s,bottom:r}=t.getState().rowPinning,i=n.some(a=>s?.includes(a)),o=n.some(a=>r?.includes(a));return i?"top":o?"bottom":!1},e.getPinnedIndex=()=>{var n,s;const r=e.getIsPinned();if(!r)return-1;const i=(n=r==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(o=>{let{id:a}=o;return a});return(s=i?.indexOf(e.id))!=null?s:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,s;return e.setRowPinning(t?Mn():(n=(s=e.initialState)==null?void 0:s.rowPinning)!=null?n:Mn())},e.getIsSomeRowsPinned=t=>{var n;const s=e.getState().rowPinning;if(!t){var r,i;return!!((r=s.top)!=null&&r.length||(i=s.bottom)!=null&&i.length)}return!!((n=s[t])!=null&&n.length)},e._getPinnedRows=(t,n,s)=>{var r;return((r=e.options.keepPinnedRows)==null||r?(n??[]).map(i=>{const o=e.getRow(i,!0);return o.getIsAllParentsExpanded()?o:null}):(n??[]).map(i=>t.find(o=>o.id===i))).filter(Boolean).map(i=>({...i,position:s}))},e.getTopRows=P(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),L(e.options,"debugRows","getTopRows")),e.getBottomRows=P(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),L(e.options,"debugRows","getBottomRows")),e.getCenterRows=P(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,s)=>{const r=new Set([...n??[],...s??[]]);return t.filter(i=>!r.has(i.id))},L(e.options,"debugRows","getCenterRows"))}},hc={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:ee("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const s={...n},r=e.getPreGroupedRowModel().flatRows;return t?r.forEach(i=>{i.getCanSelect()&&(s[i.id]=!0)}):r.forEach(i=>{delete s[i.id]}),s})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const s=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),r={...n};return e.getRowModel().rows.forEach(i=>{ss(r,i.id,s,!0,e)}),r}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=P(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?xn(e,n):{rows:[],flatRows:[],rowsById:{}},L(e.options,"debugTable","getSelectedRowModel")),e.getFilteredSelectedRowModel=P(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?xn(e,n):{rows:[],flatRows:[],rowsById:{}},L(e.options,"debugTable","getFilteredSelectedRowModel")),e.getGroupedSelectedRowModel=P(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?xn(e,n):{rows:[],flatRows:[],rowsById:{}},L(e.options,"debugTable","getGroupedSelectedRowModel")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let s=!!(t.length&&Object.keys(n).length);return s&&t.some(r=>r.getCanSelect()&&!n[r.id])&&(s=!1),s},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(r=>r.getCanSelect()),{rowSelection:n}=e.getState();let s=!!t.length;return s&&t.some(r=>!n[r.id])&&(s=!1),s},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n<e.getFilteredRowModel().flatRows.length},e.getIsSomePageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,s)=>{const r=e.getIsSelected();t.setRowSelection(i=>{var o;if(n=typeof n<"u"?n:!r,e.getCanSelect()&&r===n)return i;const a={...i};return ss(a,e.id,n,(o=s?.selectChildren)!=null?o:!0,t),a})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Ns(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return rs(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return rs(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return s=>{var r;n&&e.toggleSelected((r=s.target)==null?void 0:r.checked)}}}},ss=(e,t,n,s,r)=>{var i;const o=r.getRow(t,!0);n?(o.getCanMultiSelect()||Object.keys(e).forEach(a=>delete e[a]),o.getCanSelect()&&(e[t]=!0)):delete e[t],s&&(i=o.subRows)!=null&&i.length&&o.getCanSelectSubRows()&&o.subRows.forEach(a=>ss(e,a.id,n,s,r))};function xn(e,t){const n=e.getState().rowSelection,s=[],r={},i=function(o,a){return o.map(u=>{var l;const c=Ns(u,n);if(c&&(s.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:s,rowsById:r}}function Ns(e,t){var n;return(n=t[e.id])!=null?n:!1}function rs(e,t,n){var s;if(!((s=e.subRows)!=null&&s.length))return!1;let r=!0,i=!1;return e.subRows.forEach(o=>{if(!(i&&!r)&&(o.getCanSelect()&&(Ns(o,t)?i=!0:r=!1),o.subRows&&o.subRows.length)){const a=rs(o,t);a==="all"?i=!0:(a==="some"&&(i=!0),r=!1)}}),r?"all":i?"some":!1}var is=/([0-9]+)/gm,fc=(e,t,n)=>xo(_e(e.getValue(n)).toLowerCase(),_e(t.getValue(n)).toLowerCase()),pc=(e,t,n)=>xo(_e(e.getValue(n)),_e(t.getValue(n))),gc=(e,t,n)=>Ds(_e(e.getValue(n)).toLowerCase(),_e(t.getValue(n)).toLowerCase()),mc=(e,t,n)=>Ds(_e(e.getValue(n)),_e(t.getValue(n))),vc=(e,t,n)=>{const s=e.getValue(n),r=t.getValue(n);return s>r?1:s<r?-1:0},Sc=(e,t,n)=>Ds(e.getValue(n),t.getValue(n));function Ds(e,t){return e===t?0:e>t?1:-1}function _e(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function xo(e,t){const n=e.split(is).filter(Boolean),s=t.split(is).filter(Boolean);for(;n.length&&s.length;){const r=n.shift(),i=s.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 n.length-s.length}var it={alphanumeric:fc,alphanumericCaseSensitive:pc,text:gc,textCaseSensitive:mc,datetime:vc,basic:Sc},yc={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:ee("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let s=!1;for(const r of n){const i=r?.getValue(e.id);if(Object.prototype.toString.call(i)==="[object Date]")return it.datetime;if(typeof i=="string"&&(s=!0,i.split(is).length>1))return it.alphanumeric}return s?it.text:it.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,s;if(!e)throw new Error;return un(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(s=t.options.sortingFns)==null?void 0:s[e.columnDef.sortingFn])!=null?n:it[e.columnDef.sortingFn]},e.toggleSorting=(n,s)=>{const r=e.getNextSortingOrder(),i=typeof n<"u"&&n!==null;t.setSorting(o=>{const a=o?.find(f=>f.id===e.id),u=o?.findIndex(f=>f.id===e.id);let l=[],c,h=i?n:r==="desc";if(o!=null&&o.length&&e.getCanMultiSort()&&s?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 n,s;return((n=(s=e.columnDef.sortDescFirst)!=null?s:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var s,r;const i=e.getFirstSortDir(),o=e.getIsSorted();return o?o!==i&&((s=t.options.enableSortingRemoval)==null||s)&&(!(n&&(r=t.options.enableMultiRemove)!=null)||r)?!1:o==="desc"?"asc":"desc":i},e.getCanSort=()=>{var n,s;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((s=t.options.enableSorting)!=null?s:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,s;return(n=(s=e.columnDef.enableMultiSort)!=null?s:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const s=(n=t.getState().sorting)==null?void 0:n.find(r=>r.id===e.id);return s?s.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,s;return(n=(s=t.getState().sorting)==null?void 0:s.findIndex(r=>r.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(s=>s.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return s=>{n&&(s.persist==null||s.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(s):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,s;e.setSorting(t?[]:(n=(s=e.initialState)==null?void 0:s.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Ic=[Uu,oc,tc,nc,Bu,Hu,ac,lc,yc,Zu,uc,cc,dc,hc,rc];function Rc(e){var t,n;const s=[...Ic,...(t=e._features)!=null?t:[]];let r={_features:s};const i=r._features.reduce((h,d)=>Object.assign(h,d.getDefaultOptions==null?void 0:d.getDefaultOptions(r)),{}),o=h=>r.options.mergeOptions?r.options.mergeOptions(i,h):{...i,...h};let a={...(n=e.initialState)!=null?n:{}};r._features.forEach(h=>{var d;a=(d=h.getInitialState==null?void 0:h.getInitialState(a))!=null?d:a});const u=[];let l=!1;const c={_features:s,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:P(()=>[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}},L(e,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>r.options.columns,getAllColumns:P(()=>[r._getColumnDefs()],h=>{const d=function(f,p,g){return g===void 0&&(g=0),f.map(m=>{const v=Gu(r,m,g,p),S=m;return v.columns=S.columns?d(S.columns,v,g+1):[],v})};return d(h)},L(e,"debugColumns","getAllColumns")),getAllFlatColumns:P(()=>[r.getAllColumns()],h=>h.flatMap(d=>d.getFlatColumns()),L(e,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:P(()=>[r.getAllFlatColumns()],h=>h.reduce((d,f)=>(d[f.id]=f,d),{}),L(e,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:P(()=>[r.getAllColumns(),r._getOrderColumnsFn()],(h,d)=>d(h.flatMap(f=>f.getLeafColumns())),L(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 Nf(){return e=>P(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},s=function(r,i,o){i===void 0&&(i=0);const a=[];for(let l=0;l<r.length;l++){const c=$u(e,e._getRowId(r[l],l,o),r[l],l,i,void 0,o?.id);if(n.flatRows.push(c),n.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=s(c.originalSubRows,i+1,c))}}return a};return n.rows=s(t),n},L(e.options,"debugTable","getRowModel",()=>e._autoResetPageIndex()))}function Df(){return e=>P(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const s=e.getState().sorting,r=[],i=s.filter(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],m=g.sortUndefined,v=(d=p?.desc)!=null?d:!1;let S=0;if(m){const C=c.getValue(p.id),w=h.getValue(p.id),b=C===void 0,R=w===void 0;if(b||R){if(m==="first")return b?-1:1;if(m==="last")return b?1:-1;S=b&&R?0:b?m:-m}}if(S===0&&(S=g.sortingFn(c,h,p.id)),S!==0)return v&&(S*=-1),g.invertSorting&&(S*=-1),S}return c.index-h.index}),l.forEach(c=>{var h;r.push(c),(h=c.subRows)!=null&&h.length&&(c.subRows=a(c.subRows))}),l};return{rows:a(n.rows),flatRows:r,rowsById:n.rowsById}},L(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function jf(e,t){return e?Cc(e)?I.createElement(e,t):e:null}function Cc(e){return bc(e)||typeof e=="function"||wc(e)}function bc(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function wc(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Gf(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=I.useState(()=>({current:Rc(t)})),[s,r]=I.useState(()=>n.current.initialState);return n.current.setOptions(i=>({...i,...e,state:{...s,...e.state},onStateChange:o=>{r(o),e.onStateChange==null||e.onStateChange(o)}})),n.current}var Ec=Ti(aa(),1);function ze(e,t,n){let s=n.initialDeps??[],r,i=!0;function o(){var a,u,l;let c;n.key&&((a=n.debug)!=null&&a.call(n))&&(c=Date.now());const h=e();if(!(h.length!==s.length||h.some((f,p)=>s[p]!==f)))return r;s=h;let d;if(n.key&&((u=n.debug)!=null&&u.call(n))&&(d=Date.now()),r=t(...h),n.key&&((l=n.debug)!=null&&l.call(n))){const f=Math.round((Date.now()-c)*100)/100,p=Math.round((Date.now()-d)*100)/100,g=p/16,m=(v,S)=>{for(v=String(v);v.length<S;)v=" "+v;return v};console.info(`%c⏱ ${m(p,5)} /${m(f,5)} ms`,`
|
|
7
|
+
color: hsl(${Math.max(0,Math.min(120-120*h,120))}deg 100% 31%);`,n?.key)}return r}}function k(e,t,n,s){return{debug:()=>{var r;return(r=e?.debugAll)!=null?r:e[t]},key:!1,onChange:s}}function wh(e,t,n,s){const r=()=>{var o;return(o=i.getValue())!=null?o:e.options.renderFallbackValue},i={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(s),renderValue:r,getContext:P(()=>[e,n,t,i],(o,a,u,l)=>({table:o,column:a,row:u,cell:l,getValue:l.getValue,renderValue:l.renderValue}),k(e.options,"debugCells","cell.getContext"))};return e._features.forEach(o=>{o.createCell==null||o.createCell(i,n,t,e)},{}),i}function Eh(e,t,n,s){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:s,depth:n,columnDef:o,columns:[],getFlatColumns:P(()=>[!0],()=>{var h;return[c,...(h=c.columns)==null?void 0:h.flatMap(d=>d.getFlatColumns())]},k(e.options,"debugColumns","column.getFlatColumns")),getLeafColumns:P(()=>[e._getOrderColumnsFn()],h=>{var d;return(d=c.columns)!=null&&d.length?h(c.columns.flatMap(f=>f.getLeafColumns())):[c]},k(e.options,"debugColumns","column.getLeafColumns"))};for(const h of e._features)h.createColumn==null||h.createColumn(c,e);return c}var V="debugHeaders";function wi(e,t,n){var s;let r={id:(s=n.id)!=null?s:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],o=a=>{a.subHeaders&&a.subHeaders.length&&a.subHeaders.map(o),i.push(a)};return o(r),i},getContext:()=>({table:e,header:r,column:t})};return e._features.forEach(i=>{i.createHeader==null||i.createHeader(r,e)}),r}var Th={createTable:e=>{e.getHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,s,r)=>{var i,o;const a=(i=s?.map(c=>n.find(h=>h.id===c)).filter(Boolean))!=null?i:[],u=(o=r?.map(c=>n.find(h=>h.id===c)).filter(Boolean))!=null?o:[],l=n.filter(c=>!(s!=null&&s.includes(c.id))&&!(r!=null&&r.includes(c.id)));return Ut(t,[...a,...l,...u],e)},k(e.options,V,"getHeaderGroups")),e.getCenterHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,s,r)=>(n=n.filter(i=>!(s!=null&&s.includes(i.id))&&!(r!=null&&r.includes(i.id))),Ut(t,n,e,"center")),k(e.options,V,"getCenterHeaderGroups")),e.getLeftHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,s)=>{var r;return Ut(t,(r=s?.map(i=>n.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"left")},k(e.options,V,"getLeftHeaderGroups")),e.getRightHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,s)=>{var r;return Ut(t,(r=s?.map(i=>n.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"right")},k(e.options,V,"getRightHeaderGroups")),e.getFooterGroups=P(()=>[e.getHeaderGroups()],t=>[...t].reverse(),k(e.options,V,"getFooterGroups")),e.getLeftFooterGroups=P(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),k(e.options,V,"getLeftFooterGroups")),e.getCenterFooterGroups=P(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),k(e.options,V,"getCenterFooterGroups")),e.getRightFooterGroups=P(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),k(e.options,V,"getRightFooterGroups")),e.getFlatHeaders=P(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),k(e.options,V,"getFlatHeaders")),e.getLeftFlatHeaders=P(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),k(e.options,V,"getLeftFlatHeaders")),e.getCenterFlatHeaders=P(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),k(e.options,V,"getCenterFlatHeaders")),e.getRightFlatHeaders=P(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),k(e.options,V,"getRightFlatHeaders")),e.getCenterLeafHeaders=P(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var s;return!((s=n.subHeaders)!=null&&s.length)}),k(e.options,V,"getCenterLeafHeaders")),e.getLeftLeafHeaders=P(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var s;return!((s=n.subHeaders)!=null&&s.length)}),k(e.options,V,"getLeftLeafHeaders")),e.getRightLeafHeaders=P(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var s;return!((s=n.subHeaders)!=null&&s.length)}),k(e.options,V,"getRightLeafHeaders")),e.getLeafHeaders=P(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,s)=>{var r,i,o,a,u,l;return[...(r=(i=t[0])==null?void 0:i.headers)!=null?r:[],...(o=(a=n[0])==null?void 0:a.headers)!=null?o:[],...(u=(l=s[0])==null?void 0:l.headers)!=null?u:[]].map(c=>c.getLeafHeaders()).flat()},k(e.options,V,"getLeafHeaders"))}};function Ut(e,t,n,s){var r,i;let o=0;const a=function(h,d){d===void 0&&(d=1),o=Math.max(o,d),h.filter(f=>f.getIsVisible()).forEach(f=>{var p;(p=f.columns)!=null&&p.length&&a(f.columns,d+1)},0)};a(e);let u=[];const l=(h,d)=>{const f={depth:d,id:[s,`${d}`].filter(Boolean).join("_"),headers:[]},p=[];h.forEach(g=>{const m=[...p].reverse()[0],v=g.column.depth===f.depth;let S,C=!1;if(v&&g.column.parent?S=g.column.parent:(S=g.column,C=!0),m&&m?.column===S)m.subHeaders.push(g);else{const w=wi(n,S,{id:[s,d,S.id,g?.id].filter(Boolean).join("_"),isPlaceholder:C,placeholderId:C?`${p.filter(b=>b.column===S).length}`:void 0,depth:d,index:p.length});w.subHeaders.push(g),p.push(w)}f.headers.push(g),g.headerGroup=f}),u.push(f),d>0&&l(p,d-1)};l(t.map((h,d)=>wi(n,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(v=>{let{colSpan:S,rowSpan:C}=v;f+=S,g.push(C)})):f=1;const m=Math.min(...g);return p=p+m,d.colSpan=f,d.rowSpan=p,{colSpan:f,rowSpan:p}});return c((r=(i=u[0])==null?void 0:i.headers)!=null?r:[]),u}var _h=(e,t,n,s,r,i,o)=>{let a={id:t,index:s,original:n,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,s),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,s),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:()=>bh(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:P(()=>[e.getAllLeafColumns()],u=>u.map(l=>wh(e,a,l,l.id)),k(e.options,"debugRows","getAllCells")),_getAllCellsByColumnId:P(()=>[a.getAllCells()],u=>u.reduce((l,c)=>(l[c.column.id]=c,l),{}),k(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},Ah={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()}}},na=(e,t,n)=>{var s,r;const i=n==null||(s=n.toString())==null?void 0:s.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(i))};na.autoRemove=e=>ae(e);var sa=(e,t,n)=>{var s;return!!(!((s=e.getValue(t))==null||(s=s.toString())==null)&&s.includes(n))};sa.autoRemove=e=>ae(e);var ra=(e,t,n)=>{var s;return((s=e.getValue(t))==null||(s=s.toString())==null?void 0:s.toLowerCase())===n?.toLowerCase()};ra.autoRemove=e=>ae(e);var ia=(e,t,n)=>{var s;return(s=e.getValue(t))==null?void 0:s.includes(n)};ia.autoRemove=e=>ae(e);var oa=(e,t,n)=>!n.some(s=>{var r;return!((r=e.getValue(t))!=null&&r.includes(s))});oa.autoRemove=e=>ae(e)||!(e!=null&&e.length);var aa=(e,t,n)=>n.some(s=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(s)});aa.autoRemove=e=>ae(e)||!(e!=null&&e.length);var la=(e,t,n)=>e.getValue(t)===n;la.autoRemove=e=>ae(e);var ua=(e,t,n)=>e.getValue(t)==n;ua.autoRemove=e=>ae(e);var zs=(e,t,n)=>{let[s,r]=n;const i=e.getValue(t);return i>=s&&i<=r};zs.resolveFilterValue=e=>{let[t,n]=e,s=typeof t!="number"?parseFloat(t):t,r=typeof n!="number"?parseFloat(n):n,i=t===null||Number.isNaN(s)?-1/0:s,o=n===null||Number.isNaN(r)?1/0:r;if(i>o){const a=i;i=o,o=a}return[i,o]};zs.autoRemove=e=>ae(e)||ae(e[0])&&ae(e[1]);var me={includesString:na,includesStringSensitive:sa,equalsString:ra,arrIncludes:ia,arrIncludesAll:oa,arrIncludesSome:aa,equals:la,weakEquals:ua,inNumberRange:zs};function ae(e){return e==null||e===""}var Mh={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:ee("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],s=n?.getValue(e.id);return typeof s=="string"?me.includesString:typeof s=="number"?me.inNumberRange:typeof s=="boolean"||s!==null&&typeof s=="object"?me.equals:Array.isArray(s)?me.arrIncludes:me.weakEquals},e.getFilterFn=()=>{var n,s;return vn(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(s=t.options.filterFns)==null?void 0:s[e.columnDef.filterFn])!=null?n:me[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,s,r;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((s=t.options.enableColumnFilters)!=null?s:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(s=>s.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,s;return(n=(s=t.getState().columnFilters)==null?void 0:s.findIndex(r=>r.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(s=>{const r=e.getFilterFn(),i=s?.find(c=>c.id===e.id),o=be(n,i?i.value:void 0);if(Ei(r,o,e)){var a;return(a=s?.filter(c=>c.id!==e.id))!=null?a:[]}const u={id:e.id,value:o};if(i){var l;return(l=s?.map(c=>c.id===e.id?u:c))!=null?l:[]}return s!=null&&s.length?[...s,u]:[u]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),s=r=>{var i;return(i=be(t,r))==null?void 0:i.filter(o=>{const a=n.find(u=>u.id===o.id);return!(a&&Ei(a.getFilterFn(),o.value,a))})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(s)},e.resetColumnFilters=t=>{var n,s;e.setColumnFilters(t?[]:(n=(s=e.initialState)==null?void 0:s.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function Ei(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}var xh=(e,t,n)=>n.reduce((s,r)=>{const i=r.getValue(e);return s+(typeof i=="number"?i:0)},0),Oh=(e,t,n)=>{let s;return n.forEach(r=>{const i=r.getValue(e);i!=null&&(s>i||s===void 0&&i>=i)&&(s=i)}),s},Ph=(e,t,n)=>{let s;return n.forEach(r=>{const i=r.getValue(e);i!=null&&(s<i||s===void 0&&i>=i)&&(s=i)}),s},kh=(e,t,n)=>{let s,r;return n.forEach(i=>{const o=i.getValue(e);o!=null&&(s===void 0?o>=o&&(s=r=o):(s>o&&(s=o),r<o&&(r=o)))}),[s,r]},Lh=(e,t)=>{let n=0,s=0;if(t.forEach(r=>{let i=r.getValue(e);i!=null&&(i=+i)>=i&&(++n,s+=i)}),n)return s/n},Fh=(e,t)=>{if(!t.length)return;const n=t.map(i=>i.getValue(e));if(!Ch(n))return;if(n.length===1)return n[0];const s=Math.floor(n.length/2),r=n.sort((i,o)=>i-o);return n.length%2!==0?r[s]:(r[s-1]+r[s])/2},Nh=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),Dh=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,jh=(e,t)=>t.length,jn={sum:xh,min:Oh,max:Ph,extent:kh,mean:Lh,median:Fh,unique:Nh,uniqueCount:Dh,count:jh},Gh={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:ee("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(s=>s!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,s;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((s=t.options.enableGrouping)!=null?s:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],s=n?.getValue(e.id);if(typeof s=="number")return jn.sum;if(Object.prototype.toString.call(s)==="[object Date]")return jn.extent},e.getAggregationFn=()=>{var n,s;if(!e)throw new Error;return vn(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(s=t.options.aggregationFns)==null?void 0:s[e.columnDef.aggregationFn])!=null?n:jn[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,s;e.setGrouping(t?[]:(n=(s=e.initialState)==null?void 0:s.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const s=t.getColumn(n);return s!=null&&s.columnDef.getGroupingValue?(e._groupingValuesCache[n]=s.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,s)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var r;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((r=n.subRows)!=null&&r.length)}}};function $h(e,t,n){if(!(t!=null&&t.length)||!n)return e;const s=e.filter(r=>!t.includes(r.id));return n==="remove"?s:[...t.map(r=>e.find(i=>i.id===r)).filter(Boolean),...s]}var Uh={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:ee("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=P(n=>[pt(t,n)],n=>n.findIndex(s=>s.id===e.id),k(t.options,"debugColumns","getIndex")),e.getIsFirstColumn=n=>{var s;return((s=pt(t,n)[0])==null?void 0:s.id)===e.id},e.getIsLastColumn=n=>{var s;const r=pt(t,n);return((s=r[r.length-1])==null?void 0:s.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=P(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,s)=>r=>{let i=[];if(!(t!=null&&t.length))i=r;else{const o=[...t],a=[...r];for(;a.length&&o.length;){const u=o.shift(),l=a.findIndex(c=>c.id===u);l>-1&&i.push(a.splice(l,1)[0])}i=[...i,...a]}return $h(i,n,s)},k(e.options,"debugTable","_getOrderColumnsFn"))}},Gn=()=>({left:[],right:[]}),Bh={getInitialState:e=>({columnPinning:Gn(),...e}),getDefaultOptions:e=>({onColumnPinningChange:ee("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const s=e.getLeafColumns().map(r=>r.id).filter(Boolean);t.setColumnPinning(r=>{var i,o;if(n==="right"){var a,u;return{left:((a=r?.left)!=null?a:[]).filter(h=>!(s!=null&&s.includes(h))),right:[...((u=r?.right)!=null?u:[]).filter(h=>!(s!=null&&s.includes(h))),...s]}}if(n==="left"){var l,c;return{left:[...((l=r?.left)!=null?l:[]).filter(h=>!(s!=null&&s.includes(h))),...s],right:((c=r?.right)!=null?c:[]).filter(h=>!(s!=null&&s.includes(h)))}}return{left:((i=r?.left)!=null?i:[]).filter(h=>!(s!=null&&s.includes(h))),right:((o=r?.right)!=null?o:[]).filter(h=>!(s!=null&&s.includes(h)))}})},e.getCanPin=()=>e.getLeafColumns().some(n=>{var s,r,i;return((s=n.columnDef.enablePinning)!=null?s:!0)&&((r=(i=t.options.enableColumnPinning)!=null?i:t.options.enablePinning)!=null?r:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(a=>a.id),{left:s,right:r}=t.getState().columnPinning,i=n.some(a=>s?.includes(a)),o=n.some(a=>r?.includes(a));return i?"left":o?"right":!1},e.getPinnedIndex=()=>{var n,s;const r=e.getIsPinned();return r?(n=(s=t.getState().columnPinning)==null||(s=s[r])==null?void 0:s.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=P(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,s,r)=>{const i=[...s??[],...r??[]];return n.filter(o=>!i.includes(o.column.id))},k(t.options,"debugRows","getCenterVisibleCells")),e.getLeftVisibleCells=P(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,s)=>(s??[]).map(r=>n.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"left"})),k(t.options,"debugRows","getLeftVisibleCells")),e.getRightVisibleCells=P(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,s)=>(s??[]).map(r=>n.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"right"})),k(t.options,"debugRows","getRightVisibleCells"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,s;return e.setColumnPinning(t?Gn():(n=(s=e.initialState)==null?void 0:s.columnPinning)!=null?n:Gn())},e.getIsSomeColumnsPinned=t=>{var n;const s=e.getState().columnPinning;if(!t){var r,i;return!!((r=s.left)!=null&&r.length||(i=s.right)!=null&&i.length)}return!!((n=s[t])!=null&&n.length)},e.getLeftLeafColumns=P(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(s=>t.find(r=>r.id===s)).filter(Boolean),k(e.options,"debugColumns","getLeftLeafColumns")),e.getRightLeafColumns=P(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(s=>t.find(r=>r.id===s)).filter(Boolean),k(e.options,"debugColumns","getRightLeafColumns")),e.getCenterLeafColumns=P(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,s)=>{const r=[...n??[],...s??[]];return t.filter(i=>!r.includes(i.id))},k(e.options,"debugColumns","getCenterLeafColumns"))}};function Hh(e){return e||(typeof document<"u"?document:null)}var Bt={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},$n=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),zh={getDefaultColumnDef:()=>Bt,getInitialState:e=>({columnSizing:{},columnSizingInfo:$n(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:ee("columnSizing",e),onColumnSizingInfoChange:ee("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,s,r;const i=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Bt.minSize,(s=i??e.columnDef.size)!=null?s:Bt.size),(r=e.columnDef.maxSize)!=null?r:Bt.maxSize)},e.getStart=P(n=>[n,pt(t,n),t.getState().columnSizing],(n,s)=>s.slice(0,e.getIndex(n)).reduce((r,i)=>r+i.getSize(),0),k(t.options,"debugColumns","getStart")),e.getAfter=P(n=>[n,pt(t,n),t.getState().columnSizing],(n,s)=>s.slice(e.getIndex(n)+1).reduce((r,i)=>r+i.getSize(),0),k(t.options,"debugColumns","getAfter")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:s,...r}=n;return r})},e.getCanResize=()=>{var n,s;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((s=t.options.enableColumnResizing)!=null?s:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const s=r=>{if(r.subHeaders.length)r.subHeaders.forEach(s);else{var i;n+=(i=r.column.getSize())!=null?i:0}};return s(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const s=t.getColumn(e.column.id),r=s?.getCanResize();return i=>{if(!s||!r||(i.persist==null||i.persist(),Un(i)&&i.touches&&i.touches.length>1))return;const o=e.getSize(),a=e?e.getLeafHeaders().map(v=>[v.column.id,v.column.getSize()]):[[s.id,s.getSize()]],u=Un(i)?Math.round(i.touches[0].clientX):i.clientX,l={},c=(v,S)=>{typeof S=="number"&&(t.setColumnSizingInfo(C=>{var w,b;const R=t.options.columnResizeDirection==="rtl"?-1:1,y=(S-((w=C?.startOffset)!=null?w:0))*R,T=Math.max(y/((b=C?.startSize)!=null?b:0),-.999999);return C.columnSizingStart.forEach(_=>{let[E,x]=_;l[E]=Math.round(Math.max(x+x*T,0)*100)/100}),{...C,deltaOffset:y,deltaPercentage:T}}),(t.options.columnResizeMode==="onChange"||v==="end")&&t.setColumnSizing(C=>({...C,...l})))},h=v=>c("move",v),d=v=>{c("end",v),t.setColumnSizingInfo(S=>({...S,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},f=Hh(n),p={moveHandler:v=>h(v.clientX),upHandler:v=>{f?.removeEventListener("mousemove",p.moveHandler),f?.removeEventListener("mouseup",p.upHandler),d(v.clientX)}},g={moveHandler:v=>(v.cancelable&&(v.preventDefault(),v.stopPropagation()),h(v.touches[0].clientX),!1),upHandler:v=>{var S;f?.removeEventListener("touchmove",g.moveHandler),f?.removeEventListener("touchend",g.upHandler),v.cancelable&&(v.preventDefault(),v.stopPropagation()),d((S=v.touches[0])==null?void 0:S.clientX)}},m=Vh()?{passive:!1}:!1;Un(i)?(f?.addEventListener("touchmove",g.moveHandler,m),f?.addEventListener("touchend",g.upHandler,m)):(f?.addEventListener("mousemove",p.moveHandler,m),f?.addEventListener("mouseup",p.upHandler,m)),t.setColumnSizingInfo(v=>({...v,startOffset:u,startSize:o,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:s.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?$n():(n=e.initialState.columnSizingInfo)!=null?n:$n())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((s,r)=>s+r.getSize(),0))!=null?t:0}}},Ht=null;function Vh(){if(typeof Ht=="boolean")return Ht;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Ht=e,Ht}function Un(e){return e.type==="touchstart"}var qh={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:ee("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(s=>({...s,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,s;const r=e.columns;return(n=r.length?r.some(i=>i.getIsVisible()):(s=t.getState().columnVisibility)==null?void 0:s[e.id])!=null?n:!0},e.getCanHide=()=>{var n,s;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((s=t.options.enableHiding)!=null?s:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=P(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(s=>s.column.getIsVisible()),k(t.options,"debugRows","_getAllVisibleCells")),e.getVisibleCells=P(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,s,r)=>[...n,...s,...r],k(t.options,"debugRows","getVisibleCells"))},createTable:e=>{const t=(n,s)=>P(()=>[s(),s().filter(r=>r.getIsVisible()).map(r=>r.id).join("_")],r=>r.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),k(e.options,"debugColumns",n));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var s;e.setColumnVisibility(n?{}:(s=e.initialState.columnVisibility)!=null?s:{})},e.toggleAllColumnsVisible=n=>{var s;n=(s=n)!=null?s:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((r,i)=>({...r,[i.id]:n||!(i.getCanHide!=null&&i.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var s;e.toggleAllColumnsVisible((s=n.target)==null?void 0:s.checked)}}};function pt(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}var Kh={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()}}},Qh={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:ee("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const s=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof s=="string"||typeof s=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,s,r,i;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((s=t.options.enableGlobalFilter)!=null?s:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&((i=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?i:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>me.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:s}=e.options;return vn(s)?s:s==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[s])!=null?t:me[s]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},Wh={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:ee("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var s,r;if(!t){e._queue(()=>{t=!0});return}if((s=(r=e.options.autoResetAll)!=null?r:e.options.autoResetExpanded)!=null?s:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=s=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(s),e.toggleAllRowsExpanded=s=>{s??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=s=>{var r,i;e.setExpanded(s?{}:(r=(i=e.initialState)==null?void 0:i.expanded)!=null?r:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(s=>s.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>s=>{s.persist==null||s.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const s=e.getState().expanded;return s===!0||Object.values(s).some(Boolean)},e.getIsAllRowsExpanded=()=>{const s=e.getState().expanded;return typeof s=="boolean"?s===!0:!(!Object.keys(s).length||e.getRowModel().flatRows.some(r=>!r.getIsExpanded()))},e.getExpandedDepth=()=>{let s=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(r=>{const i=r.split(".");s=Math.max(s,i.length)}),s},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(s=>{var r;const i=s===!0?!0:!!(s!=null&&s[e.id]);let o={};if(s===!0?Object.keys(t.getRowModel().rowsById).forEach(a=>{o[a]=!0}):o=s,n=(r=n)!=null?r:!i,!i&&n)return{...o,[e.id]:!0};if(i&&!n){const{[e.id]:a,...u}=o;return u}return s})},e.getIsExpanded=()=>{var n;const s=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:s===!0||s?.[e.id])},e.getCanExpand=()=>{var n,s,r;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((s=t.options.enableExpanding)!=null?s:!0)&&!!((r=e.subRows)!=null&&r.length)},e.getIsAllParentsExpanded=()=>{let n=!0,s=e;for(;n&&s.parentId;)s=t.getRow(s.parentId,!0),n=s.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},vs=0,Ss=10,Bn=()=>({pageIndex:vs,pageSize:Ss}),Jh={getInitialState:e=>({...e,pagination:{...Bn(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:ee("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var s,r;if(!t){e._queue(()=>{t=!0});return}if((s=(r=e.options.autoResetAll)!=null?r:e.options.autoResetPageIndex)!=null?s:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=s=>{const r=i=>be(s,i);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(r)},e.resetPagination=s=>{var r;e.setPagination(s?Bn():(r=e.initialState.pagination)!=null?r:Bn())},e.setPageIndex=s=>{e.setPagination(r=>{let i=be(s,r.pageIndex);const o=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return i=Math.max(0,Math.min(i,o)),{...r,pageIndex:i}})},e.resetPageIndex=s=>{var r,i;e.setPageIndex(s?vs:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageIndex)!=null?r:vs)},e.resetPageSize=s=>{var r,i;e.setPageSize(s?Ss:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageSize)!=null?r:Ss)},e.setPageSize=s=>{e.setPagination(r=>{const i=Math.max(1,be(s,r.pageSize)),o=r.pageSize*r.pageIndex,a=Math.floor(o/i);return{...r,pageIndex:a,pageSize:i}})},e.setPageCount=s=>e.setPagination(r=>{var i;let o=be(s,(i=e.options.pageCount)!=null?i:-1);return typeof o=="number"&&(o=Math.max(-1,o)),{...r,pageCount:o}}),e.getPageOptions=P(()=>[e.getPageCount()],s=>{let r=[];return s&&s>0&&(r=[...new Array(s)].fill(null).map((i,o)=>o)),r},k(e.options,"debugTable","getPageOptions")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:s}=e.getState().pagination,r=e.getPageCount();return r===-1?!0:r===0?!1:s<r-1},e.previousPage=()=>e.setPageIndex(s=>s-1),e.nextPage=()=>e.setPageIndex(s=>s+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var s;return(s=e.options.pageCount)!=null?s:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var s;return(s=e.options.rowCount)!=null?s:e.getPrePaginationRowModel().rows.length}}},Hn=()=>({top:[],bottom:[]}),Xh={getInitialState:e=>({rowPinning:Hn(),...e}),getDefaultOptions:e=>({onRowPinningChange:ee("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,s,r)=>{const i=s?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(n==="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(n==="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 n;const{enableRowPinning:s,enablePinning:r}=t.options;return typeof s=="function"?s(e):(n=s??r)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:s,bottom:r}=t.getState().rowPinning,i=n.some(a=>s?.includes(a)),o=n.some(a=>r?.includes(a));return i?"top":o?"bottom":!1},e.getPinnedIndex=()=>{var n,s;const r=e.getIsPinned();if(!r)return-1;const i=(n=r==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(o=>{let{id:a}=o;return a});return(s=i?.indexOf(e.id))!=null?s:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,s;return e.setRowPinning(t?Hn():(n=(s=e.initialState)==null?void 0:s.rowPinning)!=null?n:Hn())},e.getIsSomeRowsPinned=t=>{var n;const s=e.getState().rowPinning;if(!t){var r,i;return!!((r=s.top)!=null&&r.length||(i=s.bottom)!=null&&i.length)}return!!((n=s[t])!=null&&n.length)},e._getPinnedRows=(t,n,s)=>{var r;return((r=e.options.keepPinnedRows)==null||r?(n??[]).map(i=>{const o=e.getRow(i,!0);return o.getIsAllParentsExpanded()?o:null}):(n??[]).map(i=>t.find(o=>o.id===i))).filter(Boolean).map(i=>({...i,position:s}))},e.getTopRows=P(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),k(e.options,"debugRows","getTopRows")),e.getBottomRows=P(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),k(e.options,"debugRows","getBottomRows")),e.getCenterRows=P(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,s)=>{const r=new Set([...n??[],...s??[]]);return t.filter(i=>!r.has(i.id))},k(e.options,"debugRows","getCenterRows"))}},Yh={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:ee("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const s={...n},r=e.getPreGroupedRowModel().flatRows;return t?r.forEach(i=>{i.getCanSelect()&&(s[i.id]=!0)}):r.forEach(i=>{delete s[i.id]}),s})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const s=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),r={...n};return e.getRowModel().rows.forEach(i=>{ys(r,i.id,s,!0,e)}),r}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=P(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?zn(e,n):{rows:[],flatRows:[],rowsById:{}},k(e.options,"debugTable","getSelectedRowModel")),e.getFilteredSelectedRowModel=P(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?zn(e,n):{rows:[],flatRows:[],rowsById:{}},k(e.options,"debugTable","getFilteredSelectedRowModel")),e.getGroupedSelectedRowModel=P(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?zn(e,n):{rows:[],flatRows:[],rowsById:{}},k(e.options,"debugTable","getGroupedSelectedRowModel")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let s=!!(t.length&&Object.keys(n).length);return s&&t.some(r=>r.getCanSelect()&&!n[r.id])&&(s=!1),s},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(r=>r.getCanSelect()),{rowSelection:n}=e.getState();let s=!!t.length;return s&&t.some(r=>!n[r.id])&&(s=!1),s},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n<e.getFilteredRowModel().flatRows.length},e.getIsSomePageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,s)=>{const r=e.getIsSelected();t.setRowSelection(i=>{var o;if(n=typeof n<"u"?n:!r,e.getCanSelect()&&r===n)return i;const a={...i};return ys(a,e.id,n,(o=s?.selectChildren)!=null?o:!0,t),a})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Vs(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return Is(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return Is(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return s=>{var r;n&&e.toggleSelected((r=s.target)==null?void 0:r.checked)}}}},ys=(e,t,n,s,r)=>{var i;const o=r.getRow(t,!0);n?(o.getCanMultiSelect()||Object.keys(e).forEach(a=>delete e[a]),o.getCanSelect()&&(e[t]=!0)):delete e[t],s&&(i=o.subRows)!=null&&i.length&&o.getCanSelectSubRows()&&o.subRows.forEach(a=>ys(e,a.id,n,s,r))};function zn(e,t){const n=e.getState().rowSelection,s=[],r={},i=function(o,a){return o.map(u=>{var l;const c=Vs(u,n);if(c&&(s.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:s,rowsById:r}}function Vs(e,t){var n;return(n=t[e.id])!=null?n:!1}function Is(e,t,n){var s;if(!((s=e.subRows)!=null&&s.length))return!1;let r=!0,i=!1;return e.subRows.forEach(o=>{if(!(i&&!r)&&(o.getCanSelect()&&(Vs(o,t)?i=!0:r=!1),o.subRows&&o.subRows.length)){const a=Is(o,t);a==="all"?i=!0:(a==="some"&&(i=!0),r=!1)}}),r?"all":i?"some":!1}var Rs=/([0-9]+)/gm,Zh=(e,t,n)=>ca(Ae(e.getValue(n)).toLowerCase(),Ae(t.getValue(n)).toLowerCase()),ef=(e,t,n)=>ca(Ae(e.getValue(n)),Ae(t.getValue(n))),tf=(e,t,n)=>qs(Ae(e.getValue(n)).toLowerCase(),Ae(t.getValue(n)).toLowerCase()),nf=(e,t,n)=>qs(Ae(e.getValue(n)),Ae(t.getValue(n))),sf=(e,t,n)=>{const s=e.getValue(n),r=t.getValue(n);return s>r?1:s<r?-1:0},rf=(e,t,n)=>qs(e.getValue(n),t.getValue(n));function qs(e,t){return e===t?0:e>t?1:-1}function Ae(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function ca(e,t){const n=e.split(Rs).filter(Boolean),s=t.split(Rs).filter(Boolean);for(;n.length&&s.length;){const r=n.shift(),i=s.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 n.length-s.length}var lt={alphanumeric:Zh,alphanumericCaseSensitive:ef,text:tf,textCaseSensitive:nf,datetime:sf,basic:rf},of={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:ee("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let s=!1;for(const r of n){const i=r?.getValue(e.id);if(Object.prototype.toString.call(i)==="[object Date]")return lt.datetime;if(typeof i=="string"&&(s=!0,i.split(Rs).length>1))return lt.alphanumeric}return s?lt.text:lt.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,s;if(!e)throw new Error;return vn(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(s=t.options.sortingFns)==null?void 0:s[e.columnDef.sortingFn])!=null?n:lt[e.columnDef.sortingFn]},e.toggleSorting=(n,s)=>{const r=e.getNextSortingOrder(),i=typeof n<"u"&&n!==null;t.setSorting(o=>{const a=o?.find(f=>f.id===e.id),u=o?.findIndex(f=>f.id===e.id);let l=[],c,h=i?n:r==="desc";if(o!=null&&o.length&&e.getCanMultiSort()&&s?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 n,s;return((n=(s=e.columnDef.sortDescFirst)!=null?s:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var s,r;const i=e.getFirstSortDir(),o=e.getIsSorted();return o?o!==i&&((s=t.options.enableSortingRemoval)==null||s)&&(!(n&&(r=t.options.enableMultiRemove)!=null)||r)?!1:o==="desc"?"asc":"desc":i},e.getCanSort=()=>{var n,s;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((s=t.options.enableSorting)!=null?s:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,s;return(n=(s=e.columnDef.enableMultiSort)!=null?s:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const s=(n=t.getState().sorting)==null?void 0:n.find(r=>r.id===e.id);return s?s.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,s;return(n=(s=t.getState().sorting)==null?void 0:s.findIndex(r=>r.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(s=>s.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return s=>{n&&(s.persist==null||s.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(s):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,s;e.setSorting(t?[]:(n=(s=e.initialState)==null?void 0:s.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},af=[Th,qh,Uh,Bh,Ah,Mh,Kh,Qh,of,Gh,Wh,Jh,Xh,Yh,zh];function lf(e){var t,n;const s=[...af,...(t=e._features)!=null?t:[]];let r={_features:s};const i=r._features.reduce((h,d)=>Object.assign(h,d.getDefaultOptions==null?void 0:d.getDefaultOptions(r)),{}),o=h=>r.options.mergeOptions?r.options.mergeOptions(i,h):{...i,...h};let a={...(n=e.initialState)!=null?n:{}};r._features.forEach(h=>{var d;a=(d=h.getInitialState==null?void 0:h.getInitialState(a))!=null?d:a});const u=[];let l=!1;const c={_features:s,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=be(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:P(()=>[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}},k(e,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>r.options.columns,getAllColumns:P(()=>[r._getColumnDefs()],h=>{const d=function(f,p,g){return g===void 0&&(g=0),f.map(m=>{const v=Eh(r,m,g,p),S=m;return v.columns=S.columns?d(S.columns,v,g+1):[],v})};return d(h)},k(e,"debugColumns","getAllColumns")),getAllFlatColumns:P(()=>[r.getAllColumns()],h=>h.flatMap(d=>d.getFlatColumns()),k(e,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:P(()=>[r.getAllFlatColumns()],h=>h.reduce((d,f)=>(d[f.id]=f,d),{}),k(e,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:P(()=>[r.getAllColumns(),r._getOrderColumnsFn()],(h,d)=>d(h.flatMap(f=>f.getLeafColumns())),k(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 Xf(){return e=>P(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},s=function(r,i,o){i===void 0&&(i=0);const a=[];for(let l=0;l<r.length;l++){const c=_h(e,e._getRowId(r[l],l,o),r[l],l,i,void 0,o?.id);if(n.flatRows.push(c),n.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=s(c.originalSubRows,i+1,c))}}return a};return n.rows=s(t),n},k(e.options,"debugTable","getRowModel",()=>e._autoResetPageIndex()))}function Yf(){return e=>P(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const s=e.getState().sorting,r=[],i=s.filter(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],m=g.sortUndefined,v=(d=p?.desc)!=null?d:!1;let S=0;if(m){const C=c.getValue(p.id),w=h.getValue(p.id),b=C===void 0,R=w===void 0;if(b||R){if(m==="first")return b?-1:1;if(m==="last")return b?1:-1;S=b&&R?0:b?m:-m}}if(S===0&&(S=g.sortingFn(c,h,p.id)),S!==0)return v&&(S*=-1),g.invertSorting&&(S*=-1),S}return c.index-h.index}),l.forEach(c=>{var h;r.push(c),(h=c.subRows)!=null&&h.length&&(c.subRows=a(c.subRows))}),l};return{rows:a(n.rows),flatRows:r,rowsById:n.rowsById}},k(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function Zf(e,t){return e?uf(e)?I.createElement(e,t):e:null}function uf(e){return cf(e)||typeof e=="function"||df(e)}function cf(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function df(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function ep(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=I.useState(()=>({current:lf(t)})),[s,r]=I.useState(()=>n.current.initialState);return n.current.setOptions(i=>({...i,...e,state:{...s,...e.state},onStateChange:o=>{r(o),e.onStateChange==null||e.onStateChange(o)}})),n.current}var hf=Oi(ha(),1);function qe(e,t,n){let s=n.initialDeps??[],r,i=!0;function o(){var a,u,l;let c;n.key&&((a=n.debug)!=null&&a.call(n))&&(c=Date.now());const h=e();if(!(h.length!==s.length||h.some((f,p)=>s[p]!==f)))return r;s=h;let d;if(n.key&&((u=n.debug)!=null&&u.call(n))&&(d=Date.now()),r=t(...h),n.key&&((l=n.debug)!=null&&l.call(n))){const f=Math.round((Date.now()-c)*100)/100,p=Math.round((Date.now()-d)*100)/100,g=p/16,m=(v,S)=>{for(v=String(v);v.length<S;)v=" "+v;return v};console.info(`%c⏱ ${m(p,5)} /${m(f,5)} ms`,`
|
|
5
8
|
font-size: .6rem;
|
|
6
9
|
font-weight: bold;
|
|
7
|
-
color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(r),i=!1,r}return o.updateDeps=a=>{s=a},o}function Fr(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var Tc=(e,t)=>Math.abs(e-t)<1.01,_c=(e,t,n)=>{let s;return function(...r){e.clearTimeout(s),s=e.setTimeout(()=>t.apply(this,r),n)}},kr=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Ac=e=>e,Mc=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),s=[];for(let r=t;r<=n;r++)s.push(r);return s},xc=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;const r=o=>{const{width:a,height:u}=o;t({width:Math.round(a),height:Math.round(u)})};if(r(kr(n)),!s.ResizeObserver)return()=>{};const i=new s.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(kr(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},Nr={passive:!0},Dr=typeof window>"u"?!0:"onscrollend"in window,Oc=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;let r=0;const i=e.options.useScrollendEvent&&Dr?()=>{}:_c(s,()=>{t(r,!1)},e.options.isScrollingResetDelay),o=c=>()=>{const{horizontal:h,isRtl:d}=e.options;r=h?n.scrollLeft*(d&&-1||1):n.scrollTop,i(),t(r,c)},a=o(!0),u=o(!1);n.addEventListener("scroll",a,Nr);const l=e.options.useScrollendEvent&&Dr;return l&&n.addEventListener("scrollend",u,Nr),()=>{n.removeEventListener("scroll",a),l&&n.removeEventListener("scrollend",u)}},Pc=(e,t,n)=>{if(t?.borderBoxSize){const s=t.borderBoxSize[0];if(s)return Math.round(s[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},Lc=(e,{adjustments:t=0,behavior:n},s)=>{var r,i;const o=e+t;(i=(r=s.scrollElement)==null?void 0:r.scrollTo)==null||i.call(r,{[s.options.horizontal?"left":"top"]:o,behavior:n})},Fc=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,n,s;return((s=(n=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:n.now)==null?void 0:s.call(n))??Date.now()},this.observer=(()=>{let t=null;const n=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(s=>{s.forEach(r=>{const i=()=>{const o=r.target,a=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(a)&&this.resizeItem(a,this.options.measureElement(o,r,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var s;(s=n())==null||s.disconnect(),t=null},observe:s=>{var r;return(r=n())==null?void 0:r.observe(s,{box:"border-box"})},unobserve:s=>{var r;return(r=n())==null?void 0:r.unobserve(s)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([n,s])=>{typeof s>"u"&&delete t[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Ac,rangeExtractor:Mc,onChange:()=>{},measureElement:Pc,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var n,s;(s=(n=this.options).onChange)==null||s.call(n,this,t)},this.maybeNotify=ze(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,r)=>{this.scrollAdjustments=0,this.scrollDirection=r?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=r,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,n)=>{const s=new Map,r=new Map;for(let i=n-1;i>=0;i--){const o=t[i];if(s.has(o.lane))continue;const a=r.get(o.lane);if(a==null||o.end>a.end?r.set(o.lane,o):o.end<a.end&&s.set(o.lane,!0),s.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((i,o)=>i.end===o.end?i.index-o.index:i.end-o.end)[0]:void 0},this.getMeasurementOptions=ze(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,n,s,r,i,o,a)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:n,scrollMargin:s,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a}),{key:!1}),this.getMeasurements=ze(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:n,scrollMargin:s,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,m;const v=a==="estimate"||u.has(f);if(p!==void 0&&this.options.lanes>1){g=p;const b=h[g],R=b!==void 0?c[b]:void 0;m=R?R.end+this.options.gap:n+s}else{const b=this.options.lanes===1?c[d-1]:this.getFurthestMeasurement(c,d);m=b?b.end+this.options.gap:n+s,g=b?b.lane:d%this.options.lanes,this.options.lanes>1&&v&&this.laneAssignments.set(d,g)}const S=u.get(f),C=typeof S=="number"?S:this.options.estimateSize(d),w=m+C;c[d]={index:d,start:m,size:C,end:w,key:f,lane:g},h[g]=d}return this.measurementsCache=c,c},{key:!1,debug:()=>this.options.debug}),this.calculateRange=ze(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,n,s,r)=>this.range=t.length>0&&n>0?kc({measurements:t,outerSize:n,scrollOffset:s,lanes:r}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ze(()=>{let t=null,n=null;const s=this.calculateRange();return s&&(t=s.startIndex,n=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,n]},(t,n,s,r,i)=>r===null||i===null?[]:t({startIndex:r,endIndex:i,overscan:n,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const n=this.options.indexAttribute,s=t.getAttribute(n);return s?parseInt(s,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(s!==void 0&&this.range){const r=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,s-r),o=Math.min(this.options.count-1,s+r);return t>=i&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((i,o)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(o))});return}const n=this.indexFromElement(t),s=this.options.getItemKey(n),r=this.elementsCache.get(s);r!==t&&(r&&this.observer.unobserve(r),this.observer.observe(t),this.elementsCache.set(s,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,n)=>{var s;const r=this.measurementsCache[t];if(!r)return;const i=n-(this.itemSizeCache.get(r.key)??r.size);i!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,i,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,n)),this.notify(!1))},this.getVirtualItems=ze(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,n)=>{const s=[];for(let r=0,i=t.length;r<i;r++){const o=n[t[r]];s.push(o)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const n=this.getMeasurements();if(n.length!==0)return Fr(n[Oo(0,n.length-1,s=>Fr(n[s]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,n,s=0)=>{if(!this.scrollElement)return 0;const r=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=t>=i+r?"end":"start"),n==="center"?t+=(s-r)/2:n==="end"&&(t-=r);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,n="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const s=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[t];if(!i)return;if(n==="auto")if(i.end>=r+s-this.options.scrollPaddingEnd)n="end";else if(i.start<=r+this.options.scrollPaddingStart)n="start";else return[r,n];if(n==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),n];const o=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,n,i.size),n]},this.scrollToOffset=(t,{align:n="start",behavior:s="auto"}={})=>{const r=this.getOffsetForAlignment(t,n),i=this.now();this.scrollState={index:null,align:n,behavior:s,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:n="auto",behavior:s="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const r=this.getOffsetForIndex(t,n);if(!r)return;const[i,o]=r,a=this.now();this.scrollState={index:t,align:o,behavior:s,startedAt:a,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:n="auto"}={})=>{const s=this.getScrollOffset()+t,r=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:r,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const n=this.getMeasurements();let s;if(n.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((t=n[n.length-1])==null?void 0:t.end)??0;else{const r=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&r.some(o=>o===null);){const o=n[i];r[o.lane]===null&&(r[o.lane]=o.end),i--}s=Math.max(...r.filter(o=>o!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:n,behavior:s})=>{this.options.scrollToFn(t,{behavior:s,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const e=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,t=e?e[0]:this.scrollState.lastTargetOffset,n=1,s=t!==this.scrollState.lastTargetOffset;if(!s&&Tc(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=n){this.scrollState=null;return}}else this.scrollState.stableFrames=0,s&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior="auto",this._scrollToOffset(t,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}},Oo=(e,t,n,s)=>{for(;e<=t;){const r=(e+t)/2|0,i=n(r);if(i<s)e=r+1;else if(i>s)t=r-1;else return r}return e>0?e-1:0};function kc({measurements:e,outerSize:t,scrollOffset:n,lanes:s}){const r=e.length-1,i=u=>e[u].start;if(e.length<=s)return{startIndex:0,endIndex:r};let o=Oo(0,r,i,n),a=o;if(s===1)for(;a<r&&e[a].end<n+t;)a++;else if(s>1){const u=Array(s).fill(0);for(;a<r&&u.some(c=>c<n+t);){const c=e[a];u[c.lane]=c.end,a++}const l=Array(s).fill(n+t);for(;o>=0&&l.some(c=>c>=n);){const c=e[o];l[c.lane]=c.start,o--}o=Math.max(0,o-o%s),a=Math.min(r,a+(s-1-a%s))}return{startIndex:o,endIndex:a}}var jr=typeof document<"u"?I.useLayoutEffect:I.useEffect;function Nc({useFlushSync:e=!0,...t}){const n=I.useReducer(()=>({}),{})[1],s={...t,onChange:(i,o)=>{var a;e&&o?(0,Ec.flushSync)(n):n(),(a=t.onChange)==null||a.call(t,i,o)}},[r]=I.useState(()=>new Fc(s));return r.setOptions(s),jr(()=>r._didMount(),[]),jr(()=>r._willUpdate()),r}function Uf(e){return Nc({observeElementRect:xc,observeElementOffset:Oc,scrollToFn:Lc,...e})}var os=class extends Error{missingFeature;constructor(e){super(Dc(e)),this.name="UnsupportedResponseStreamError",this.missingFeature=e}};function Dc(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function jc(e){if(!e.body)throw new os("Response.body");if(typeof e.body.getReader!="function")throw new os("Response.body.getReader");return e.body.getReader()}function Gc(){if(typeof globalThis.TextDecoder!="function")throw new os("TextDecoder");return new globalThis.TextDecoder}function Uc(e){if(!e.startsWith("data:"))return e;const t=e.slice(5);return t.startsWith(" ")?t.slice(1):t}function Gr(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 $c(e){const t=Gr(e.createdAt),n=e.parts.map(i=>{if(i.type!=="tool-result")return i;const o=Gr(i.createdAt),{createdAt:a,...u}=i;return o?{...u,createdAt:o}:u}),{createdAt:s,...r}=e;return t?{...r,parts:n,createdAt:t}:{...r,parts:n}}function Po(e){return e.map($c)}function Ur(e){return Object.keys(e).length>0?e:void 0}function Lo(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)&&"promptTokens"in e}function Bc(e,t){return Lo(e)?e:Array.isArray(e)?$r(e,t):$r(void 0,t)}function $r(e,t){const n=e?.[0];if(n==null&&t==null)return;const{promptTokensDetails:s,completionTokensDetails:r,...i}=t??{},o=Ur({...n?.cachedInputTokens!==void 0?{cachedTokens:n.cachedInputTokens}:{},...s}),a=Ur({...n?.reasoningTokens!==void 0?{reasoningTokens:n.reasoningTokens}:{},...r});return{promptTokens:n?.inputTokens??0,completionTokens:n?.outputTokens??0,totalTokens:n?.totalTokens??0,...i,...o!==void 0?{promptTokensDetails:o}:{},...a!==void 0?{completionTokensDetails:a}:{}}}function Br(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Fo(e,t){if(t==null)return e;if(e==null)return{...t};const n={...e,...t};return Br(e.tanstack)&&Br(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function $(e){if(e==null)return;const t="metadata"in e?e.metadata:void 0,n=(t!=null&&typeof t=="object"&&!Array.isArray(t)?t:e).tanstack;if(!(n==null||typeof n!="object"||Array.isArray(n)))return n}function ko(e,t){const n=e.metadata,s=$(e)??{};return{...e,metadata:{...n??{},tanstack:{...s,...t}}}}var kt=(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})({}),Hc=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 ce(e,t){return e>>>t|e<<32-t}function zc(e){const t=new TextEncoder().encode(e),n=t.length*8,s=t.length+1,r=s+(56-s%64+64)%64+8,i=new Uint8Array(r);i.set(t),i[t.length]=128;const o=new DataView(i.buffer);o.setUint32(r-8,Math.floor(n/4294967296)),o.setUint32(r-4,n>>>0);let a=1779033703,u=3144134277,l=1013904242,c=2773480762,h=1359893119,d=2600822924,f=528734635,p=1541459225;const g=new Uint32Array(64);for(let v=0;v<r;v+=64){for(let E=0;E<16;E++)g[E]=o.getUint32(v+E*4);for(let E=16;E<64;E++){const x=g[E-15]??0,N=g[E-2]??0,k=ce(x,7)^ce(x,18)^x>>>3,j=ce(N,17)^ce(N,19)^N>>>10;g[E]=(g[E-16]??0)+k+(g[E-7]??0)+j>>>0}let S=a,C=u,w=l,b=c,R=h,y=d,T=f,_=p;for(let E=0;E<64;E++){const x=ce(R,6)^ce(R,11)^ce(R,25),N=R&y^~R&T,k=_+x+N+(Hc[E]??0)+(g[E]??0)>>>0,j=(ce(S,2)^ce(S,13)^ce(S,22))+(S&C^S&w^C&w)>>>0;_=T,T=y,y=R,R=b+k>>>0,b=w,w=C,C=S,S=k+j>>>0}a=a+S>>>0,u=u+C>>>0,l=l+w>>>0,c=c+b>>>0,h=h+R>>>0,d=d+y>>>0,f=f+T>>>0,p=p+_>>>0}const m=v=>(v>>>0).toString(16).padStart(8,"0");return m(a)+m(u)+m(l)+m(c)+m(h)+m(d)+m(f)+m(p)}function Vc(e){return`sha256:${zc(e)}`}function as(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!="object")throw new TypeError("Interrupt values must be JSON-compatible.");if(t.has(e))throw new TypeError("Interrupt values must not cycle.");if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError("Interrupt values must use plain JSON objects.");t.add(e);let n;if(Array.isArray(e)){const s=[];for(let r=0;r<e.length;r++)s.push(as(e[r],t));n=`[${s.join(",")}]`}else{const s=e;n=`{${Object.keys(s).sort().map(r=>`${JSON.stringify(r)}:${as(s[r],t)}`).join(",")}}`}return t.delete(e),n}function je(e){return as(e,new WeakSet)}function Ge(e,t=Vc){if(typeof e!="string")throw new TypeError("Interrupt digests require canonical JSON text.");return t(e)}function No(e){e===null||typeof e!="object"||Object.isFrozen(e)||(Object.values(e).forEach(No),Object.freeze(e))}function B(e){const t=JSON.parse(je(e));return No(t),t}function qc(e){const t=[...e].sort((r,i)=>r.interruptId.localeCompare(i.interruptId)),n=B(t),s=je(n);return Object.freeze({resolutions:n,canonicalResolutions:s,fingerprint:Ge(s)})}function Hr(e){const t={};for(const[n,s]of Object.entries(e))n!=="$schema"&&(t[n]=s);return t}function Do(e){return(typeof e=="object"||typeof e=="function")&&e!==null}function It(e){if(!Do(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 Do(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 Kc(e){return Object.keys(e).length>0?e:void 0}function zr(e){if(Array.isArray(e)){const n=e.map(r=>en(r,r.required||[])),s=n.map(r=>r.nullWidening??{});return{schema:n.map(r=>r.schema),itemMap:s.some(r=>Object.keys(r).length>0)?s:void 0}}const t=en(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function en(e,t=[]){const n={...e},s={};if(n.type==="object"&&n.properties){const r={...n.properties},i=Object.keys(r),o={};for(const a of i){const u=r[a];if(!u)continue;const l=!t.includes(a);let c=!1,h;if(u.type==="object"&&u.properties){const d=en(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=zr(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}:{}})}n.properties=r,n.required=i,n.additionalProperties=!1,Object.keys(o).length>0&&(s.properties=o)}if(n.type==="array"&&n.items){const r=zr(n.items);n.items=r.schema,r.itemMap&&(s.items=r.itemMap)}return{schema:n,nullWidening:Kc(s)}}function Qc(e){if(It(e)){const t=Hr(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:Hr(e)}function ls(e,t={}){if(!e)return;const{forStructuredOutput:n=!1}=t;if(!n&&!It(e)&&!Ae(e))return e;const s=Qc(e);return!s||typeof s!="object"||!n?s:en(s,s.required||[]).schema}var Wc=class extends Error{name="StandardSchemaValidationError";issues;constructor(e){super(`Validation failed: ${e.map(t=>t.message||"Validation failed").join(", ")}`),this.issues=e}};function Jc(e,t){if(!Ae(e))return t;const n=e["~standard"].validate(t);if(n instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!n.issues)return n.value;throw new Wc(n.issues)}var Xc=new Set(["$schema","$id","$ref","$defs","type","properties","required","additionalProperties","items","oneOf","anyOf","allOf","enum","const","format","minimum","maximum","minLength","maxLength","pattern"]);function jo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function js(e){return jo(e)&&Object.keys(e).some(t=>Xc.has(t))}function Yc(e){return Ae(e)||It(e)||js(e)}function Zc(e){if(!jo(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>n==="approve"||n==="reject")&&t.every(n=>Yc(e[n]))}function ed(e){const t={};for(const[n,s]of Object.entries(e))t[n]=s;return t}function at(e){if(Ae(e)){const t=It(e)?ed(e["~standard"].jsonSchema.input({target:"draft-2020-12"})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(js(e))return{source:e,jsonSchema:e};throw new TypeError("Expected a supported SchemaInput.")}function Vr(e){const t={approved:{const:e.approved}},n=["approved"];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push("payload")),{type:"object",properties:t,required:n,additionalProperties:!1}}function td(e,t){const n=t===void 0?null:at(t);let s=null,r=null;if(e!==void 0)if(Ae(e)||js(e))s=at(e),r=s;else if(Zc(e))s=e.approve===void 0?null:at(e.approve),r=e.reject===void 0?null:at(e.reject);else throw new TypeError("approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.");const i={oneOf:[Vr({approved:!0,payload:s,inputSchema:n}),Vr({approved:!1,payload:r,inputSchema:null})]},o=je(i),a=je({approve:s?.jsonSchema??null,reject:r?.jsonSchema??null});return{branches:{approve:s,reject:r},responseSchema:i,responseSchemaHash:Ge(o),approvalSchemaHash:Ge(a)}}function qr(e){if(e===void 0)return Ge("undefined");const t=at(e).jsonSchema??{standardValidator:"unserialized"};return Ge(je(t))}var cn="tanstack:interruptBinding",Go=cn;function tn(e){return e&&typeof e=="object"?e:null}function K(e,t){return typeof e[t]=="string"?e[t]:void 0}function nd(e){const t=e.v;return t===void 0?!0:t===1}function Uo(e){const t=tn(e.metadata),n=t?tn(t[Go]):null;if(!n||K(n,"interruptId")!==e.id||!nd(n))return;const s=K(n,"kind"),r=K(n,"interruptId"),i=K(n,"responseSchemaHash"),o=K(n,"expiresAt");if(!r||i===""||o!==void 0&&!Number.isFinite(Date.parse(o)))return;const a=1;if(s==="generic"){const c=K(n,"definitionId"),h=K(n,"key"),d=n.batchIndex,f=K(n,"payloadSchemaHash");return(c!==void 0||h!==void 0||d!==void 0||f!==void 0)&&(!c||!h||typeof d!="number"||!Number.isInteger(d)||d<0)?void 0:{v:a,kind:s,interruptId:r,...i?{responseSchemaHash:i}:{},...o?{expiresAt:o}:{},...c?{definitionId:c}:{},...h?{key:h}:{},...typeof d=="number"?{batchIndex:d}:{},...f?{payloadSchemaHash:f}:{}}}if(!i)return;const u=K(n,"toolName"),l=K(n,"toolCallId");if(!(!u||!l)){if(s==="client-tool-execution"){const c=K(n,"outputSchemaHash");return c?{v:a,kind:s,interruptId:r,toolName:u,toolCallId:l,outputSchemaHash:c,responseSchemaHash:i,...o?{expiresAt:o}:{}}:void 0}if(s==="tool-approval"){const c=K(n,"inputSchemaHash"),h=K(n,"approvalSchemaHash");return!c||!h?void 0:{v:a,kind:s,interruptId:r,toolName:u,toolCallId:l,originalArgs:n.originalArgs,inputSchemaHash:c,approvalSchemaHash:h,responseSchemaHash:i,...o?{expiresAt:o}:{}}}}}function sd(e){const t=Uo(e);if(!t)return;const n=tn(e.metadata),s=n?tn(n[Go]):null;if(!s)return;const r=K(s,"interruptedRunId"),i=s.generation;if(!(!r||typeof i!="number"||!Number.isInteger(i)||i<0))return{...t,interruptedRunId:r,generation:i}}var rd="tanstack:interruptPayload";function id(e,t){if(!It(e))throw new TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{const n=e["~standard"].jsonSchema.input({target:"draft-07"});if(n===void 0)throw new TypeError("The exported schema is undefined.");if(typeof n=="function")throw new TypeError("The exported schema must not be a function.");if(Array.isArray(n))throw new TypeError("The exported schema must be a plain JSON object.");if(!n||typeof n!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(n)))throw new TypeError("The exported schema must be a plain JSON object.");const s={};for(const[r,i]of Object.entries(n))r!=="$schema"&&(s[r]=i);return{json:s,canonicalJson:je(s)}}catch(n){throw new TypeError(`${t} could not export compatible JSON Schema: ${n instanceof Error?n.message:String(n)}`)}}function od(e){return Ge(id(e,"Interrupt schema").canonicalJson)}var ad="tanstack:interruptContinuation";function ld(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ud(e){return{[ad]:e}}function cd(e){const t=Uo(e);if(t?.kind!=="generic"||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;const n=ld(e.metadata)?e.metadata:void 0,s=n!==void 0&&Object.prototype.hasOwnProperty.call(n,"tanstack:interruptPayload");return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??"",...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{},...t.responseSchemaHash!==void 0?{responseSchemaHash:t.responseSchemaHash}:{},...t.payloadSchemaHash!==void 0?{payloadSchemaHash:t.payloadSchemaHash}:{},...s?{payload:n[rd]}:{}}}var dd=new Set(["text","image","audio","video","document"]);function hd(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.type!="string"||!dd.has(t.type))return!1;if(t.type==="text")return typeof t.content=="string";const n=t.source;if(typeof n!="object"||n===null)return!1;const s=n;return typeof s.value!="string"?!1:s.type==="data"?typeof s.mimeType=="string":s.type==="url"}function us(e){return Array.isArray(e)&&e.length>0&&e.every(hd)}function Gs(e){return typeof e=="string"||us(e)?e:JSON.stringify(e)}function fd(e){const t=e?.metadata;return typeof t=="object"&&t!==null&&t.providerExecuted===!0?t:null}function $o(e){return fd(e)!==null}function On(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pd(e){return e.type==="text"||e.type==="image"||e.type==="audio"||e.type==="video"||e.type==="document"}function gd(e){try{return JSON.stringify(e)??""}catch{return""}}function Kr(e){return typeof e=="string"&&e!==""?e:void 0}function md(e){if("encryptedValue"in e){const t=Kr(e.encryptedValue);if(t!==void 0)return t}return Kr($(e)?.signature)}function Bo(e){return e.length===0?null:e.every(t=>t.type==="text")?e.map(t=>t.content).join("")||null:e}function Ho(e){return e==null?"":typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.content).join("")}function vd(e){return Array.isArray(e)?e:Ho(e)}function Sd(e){if(!("role"in e)||e.role!=="tool")return e;const t=e,n=$(t)?.toolResult;if(!On(n)||"content"in n&&!us(n.content))return e;const s={...e};if("id"in n||Reflect.deleteProperty(s,"id"),"createdAt"in n||Reflect.deleteProperty(s,"createdAt"),typeof n.id=="string"&&Reflect.set(s,"id",n.id),typeof n.createdAt=="string"){const i=ne(n.createdAt);i&&Reflect.set(s,"createdAt",i)}us(n.content)&&Reflect.set(s,"content",n.content);const r=Reflect.get(t,"metadata");if(On(r)){const i=r.tanstack;if(On(i)){const{toolResult:o,...a}=i,u={...r};Object.keys(a).length?u.tanstack=a:delete u.tanstack,Object.keys(u).length?Reflect.set(s,"metadata",u):Reflect.deleteProperty(s,"metadata")}}return s}function ne(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 zo(e){if(e.type!=="tool-result")return e;const t=ne(e.createdAt),{createdAt:n,...s}=e;return t===void 0?s:{...s,createdAt:t}}function Vo(e){return ne($(e)?.createdAt)}function cs(e){const t=ne(e.createdAt);return t!==void 0?{createdAt:t}:{}}function dn(e){return e.name!==void 0?{name:e.name}:{}}function hn(e){if(e==null||typeof e!="object"||Array.isArray(e)||!("type"in e)||e.type!=="ui-resource"||!("toolCallId"in e)||typeof e.toolCallId!="string"||!("toolName"in e)||typeof e.toolName!="string"||!("resource"in e)||e.resource==null||typeof e.resource!="object"||Array.isArray(e.resource))return!1;const t=e.resource;return"uri"in t&&typeof t.uri=="string"&&"mimeType"in t&&typeof t.mimeType=="string"}function Qr(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function qo(e,t){if(t.length===0)return e;const n=new Set(e.parts.filter(hn).map(r=>Qr(r))),s=t.filter(r=>!n.has(Qr(r)));return s.length===0?e:{...e,parts:[...e.parts,...s]}}function yd(e){const t=e.parts.filter(hn),n=e.metadata??{},s=$(e),r={};s?.model!==void 0&&(r.model=s.model),s?.signature!==void 0&&(r.signature=s.signature),t.length>0&&(r.uiResources=t);const i={...n};return Object.keys(r).length>0?i.tanstack=r:delete i.tanstack,Object.keys(i).length>0?i:void 0}function Id(e){return e.role==="system"?[]:e.role!=="assistant"?[Rd(e)]:bd(e)}function Rd(e){const t=[];for(const n of e.parts)pd(n)&&t.push(n);return{id:e.id,role:e.role,content:Bo(t),...dn(e),...cs(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function Wr(){return{contentParts:[],toolCalls:[]}}function Cd(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 bd(e){const t=[];let n=Wr(),s=[];const r=new Set,i={id:e.id,...dn(e),...cs(e)},o=yd(e),a={...i,...o!==void 0&&{metadata:o}};function u(l=!1){const c=Bo(n.contentParts),h=c!==null,d=n.toolCalls.length>0,f=s.length>0;(l||h||d||f)&&(t.push({...a,role:"assistant",content:c,...d&&{toolCalls:n.toolCalls},...f&&{thinking:s},...n.structuredOutput&&{structuredOutput:n.structuredOutput}}),s=[]),n=Wr()}for(const l of e.parts)switch(l.type){case"text":case"image":case"audio":case"video":case"document":n.contentParts.push(l);break;case"tool-call":Cd(l)&&n.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},...cs(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)&&(n.toolCalls.some($o)&&u(),s.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?gd(l.data):"";c!==""&&(n.contentParts.push({type:"text",content:c}),n.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:Gs(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 nn(e,t){const n=[],s=ne(e.createdAt);if(e.role==="assistant"&&e.thinking?.length)for(const a of e.thinking)!a.content&&!a.signature||n.push({type:"thinking",content:a.content,...a.signature&&{signature:a.signature}});const r=e.structuredOutput??Ko($(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&&n.push({type:"text",content:u})}n.push(r)}else if(e.role==="tool"&&e.toolCallId)n.push({type:"tool-result",toolCallId:e.toolCallId,content:vd(e.content),state:e.error===void 0?"complete":"error",...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name},...e.metadata!==void 0&&{metadata:e.metadata},...s!==void 0&&{createdAt:s},...e.error!==void 0&&{error:e.error}});else if(Array.isArray(e.content))for(const a of e.content)n.push(a);else{const a=Ho(e.content);a&&n.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}n.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:n,...dn(e),...s!==void 0&&{createdAt:s},...e.metadata!==void 0&&{metadata:e.metadata}},o=$(e)?.uiResources;return qo(i,Array.isArray(o)?o.filter(hn):[])}function wd(e){if("parts"in e)return Oe(e,{...e,id:e.id||Ne()});const t=e.id||Ne();switch(e.role){case"user":return Oe(e,{id:t,role:"user",parts:Ed(e.content)});case"assistant":{const n=$(e),s=n?.toolCallMetadata,r=Ko(n?.structuredOutput),i=e.toolCalls?.map(o=>{const a=s!=null&&typeof s=="object"?s[o.id]:void 0;return a!==void 0?{...o,metadata:a}:o});return Oe(e,nn({role:"assistant",content:e.content??null,...dn(e),...i&&{toolCalls:i},...r&&{structuredOutput:r}},t))}case"tool":{e=Sd(e);const n=ne("createdAt"in e?e.createdAt:void 0)??Vo(e);return Oe(e,nn({role:"tool",content:e.content,toolCallId:e.toolCallId,..."name"in e&&typeof e.name=="string"?{name:e.name}:{},..."id"in e&&typeof e.id=="string"?{id:e.id}:{},..."metadata"in e&&e.metadata!=null?{metadata:e.metadata}:{},...n!==void 0?{createdAt:n}:{},...e.error!==void 0&&{error:e.error}},t))}case"system":case"developer":return Oe(e,{id:t,role:"system",parts:e.content?[{type:"text",content:e.content}]:[]});case"reasoning":{const n=md(e),s=typeof e.content=="string"?e.content:"";return Oe(e,{id:t,role:"assistant",parts:s||n!==void 0?[{type:"thinking",content:s,...n!==void 0?{signature:n}:{}}]:[]})}default:return Oe(e,{id:t,role:"assistant",parts:[]})}}function Oe(e,t){const n=t.parts.map(l=>zo(l));n!==t.parts&&(t={...t,parts:n});const s="name"in e&&typeof e.name=="string"?e.name:void 0;let r=s!==void 0?{...t,name:s}:t,i;if("metadata"in e){const l=e.metadata;l!=null&&typeof l=="object"&&!Array.isArray(l)&&(i=l,r={...r,metadata:i})}const o=ne(r.createdAt)??(i!==void 0?Vo(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=$(i)?.uiResources,u=Array.isArray(a)?a.filter(hn):[];return qo(r,u)}function Ko(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 Ed(e){if(typeof e=="string")return e?[{type:"text",content:e}]:[];const t=[];for(const n of e)n.type==="text"?t.push({type:"text",content:n.text}):n.type!=="binary"&&t.push(n);return t}function Td(e,t){if("parts"in e){const n=e.parts.map(s=>zo(s));return{...e,parts:n,id:e.id||t(),createdAt:ne(e.createdAt)??new Date}}else return{...nn(e,t()),createdAt:ne(e.createdAt)??new Date}}function Ne(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function Jr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pn(e,t,n,s,r=!1){const i=Jr(e)?e:{},o=Jr(i.tanstack)?{...i.tanstack}:{};r&&delete o.uiResources;const a=ne(t),u={...n!==void 0?{id:n}:{},...a&&{createdAt:a.toISOString()},...Array.isArray(s)&&{content:s}},l={...i,tanstack:{...o,toolResult:u}};return Object.keys(l).length?l:void 0}function _d(e,t){const n=[],s=new Set(e.flatMap(o=>"id"in o&&o.id&&o.role!=="tool"?[o.id]:[])),r=t?.includeSnapshotStructuredOutput??!1,i=new Set;for(const o of e)o.role==="assistant"&&o.id!==void 0&&i.add(o.id);for(const o of e){if(!("parts"in o)&&o.role==="tool"&&o.toolCallId){const d=Fn(kd(o.id,o.toolCallId,i),s),f=Pn(o.metadata,o.createdAt,o.id,o.content);n.push({role:"tool",id:d,...o.name!==void 0&&{name:o.name},toolCallId:o.toolCallId,content:typeof o.content=="string"?o.content:JSON.stringify(o.content),...o.error!==void 0&&{error:o.error},...f!==void 0&&{metadata:f}});continue}const a="parts"in o?o:nn(o,o.id),u=a.parts;if(s.add(a.id),o.role==="system"){n.push(Ln(a,"system",{content:u.length>0?ds(u):o.content??""},u,r));continue}if(o.role==="user"){n.push(Ln(a,"user",{content:u.length>0?Od(u):o.content??""},u,r));continue}for(const d of u)if(d.type==="thinking"){const f={role:"reasoning",id:Qo(Fd(a.id,d),s),content:d.content};d.signature&&(f.encryptedValue=d.signature),n.push(f)}const l=ds(u),c=Ld(u);n.push(Ln(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=Fn(d.id??hs(d.toolCallId),s),p=Pn(d.metadata,d.createdAt,d.id,d.content,!0);n.push({role:"tool",id:f,toolCallId:d.toolCallId,...d.name!==void 0&&{name:d.name},content:typeof d.content=="string"?d.content:JSON.stringify(d.content),...d.error!==void 0&&{error:d.error},...p!==void 0&&{metadata:p}})}else if(d.type==="tool-call"){const f=d.approval?.approved;if(h.has(d.id)||d.output===void 0&&(d.state!=="approval-responded"||f===void 0))continue;const p=d.output!==void 0?Gs(d.output):JSON.stringify({approved:f,...f&&{pendingExecution:!0},message:f?"User approved this action":"User denied this action"}),g=typeof p=="string"?p:JSON.stringify(p);n.push({role:"tool",id:Fn(hs(d.id),s),toolCallId:d.id,content:g,metadata:Pn(void 0,void 0,void 0,p)})}}return n}function Ln(e,t,n,s,r){const i=Ad(e,s,r),o={id:e.id,...e.name!==void 0&&{name:e.name},...i!==void 0&&{metadata:i}};return t==="system"?{...o,role:t,content:String(n.content??"")}:t==="user"?{...o,role:t,content:n.content??""}:{...o,role:t,...typeof n.content=="string"&&{content:n.content},...n.toolCalls!==void 0&&{toolCalls:n.toolCalls}}}function Ad(e,t,n){const s={...e.metadata??{}},r=$(e),i={};r?.model!==void 0&&(i.model=r.model),r?.signature!==void 0&&(i.signature=r.signature);const o=ne(e.createdAt);o!==void 0&&(i.createdAt=o.toISOString());const a=Md(t,n);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?s.tanstack=i:delete s.tanstack,Object.keys(s).length>0?s:void 0}function Md(e,t){for(const n of e)if(n.type==="structured-output"&&(t||n.status!=="complete"))return xd(n,t)}function xd(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 ds(e){const t=[];for(const n of e)n.type==="text"?t.push(n.content):n.type==="structured-output"&&n.status==="complete"&&n.raw!==""&&t.push(n.raw);return t.join("")}function Od(e){if(!e.some(n=>n.type==="image"||n.type==="audio"||n.type==="video"||n.type==="document"))return ds(e);const t=[];for(const n of e)n.type==="text"?t.push({type:"text",text:n.content}):(n.type==="image"||n.type==="audio"||n.type==="video"||n.type==="document")&&t.push(n);return t}function Pd(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 Ld(e){const t=[];for(const n of e)if(n.type==="tool-call"){const s=Pd(n.metadata);t.push({id:n.id,type:"function",function:{name:n.name,arguments:n.arguments},...s!==void 0?{encryptedValue:s}:{}})}return t.length>0?t:void 0}function Fd(e,t){return`${e}-reasoning-${t.id??Nd(t.content)}`}function hs(e){return`tool-${e}`}function Fn(e,t){return Qo(e,t)}function Qo(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}-${n}`);)n++;const s=`${e}-${n}`;return t.add(s),s}function kd(e,t,n){const s=hs(t);return e===void 0||n.has(e)?s:e}function Nd(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function Dd(e){if((e.type===kt.RUN_FINISHED||e.type===kt.RUN_ERROR)&&(Array.isArray(e.usage)||Lo(e.usage))){const t=Bc(e.usage,$(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===kt.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===kt.TOOL_CALL_END&&e.input===void 0){const t=$(e)?.input;t!==void 0&&(e.input=t)}return e}function Wo(e){Dd(e);const t=$(e),n=e;if(t==null)return n;for(const[s,r]of Object.entries(t))s==="usage"||s==="interruptErrors"||n[s]===void 0&&r!==void 0&&(n[s]=r);return t.interruptErrors!==void 0&&(n["tanstack:interruptErrors"]=t.interruptErrors),n}function Xr(e){return typeof e=="string"&&e!==""?e:void 0}function Jo(e){if("runId"in e){const t=Xr(e.runId);if(t!==void 0)return t}return Xr($(e)?.runId)}var Yr=Xe((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),jd=Xe((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]})),n=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 s=Yr();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return s.Allow}}),n(Yr(),e);var r=class extends Error{};e.PartialJSON=r;var i=class extends Error{};e.MalformedJSON=i;function o(l,c=s.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=b=>{throw new r(`${b} at position ${d}`)},p=b=>{throw new i(`${b} at position ${d}`)},g=()=>(w(),d>=h&&f("Unexpected end of input"),l[d]==='"'?m():l[d]==="{"?v():l[d]==="["?S():l.substring(d,d+4)==="null"||s.Allow.NULL&c&&h-d<4&&"null".startsWith(l.substring(d))?(d+=4,null):l.substring(d,d+4)==="true"||s.Allow.BOOL&c&&h-d<4&&"true".startsWith(l.substring(d))?(d+=4,!0):l.substring(d,d+5)==="false"||s.Allow.BOOL&c&&h-d<5&&"false".startsWith(l.substring(d))?(d+=5,!1):l.substring(d,d+8)==="Infinity"||s.Allow.INFINITY&c&&h-d<8&&"Infinity".startsWith(l.substring(d))?(d+=8,1/0):l.substring(d,d+9)==="-Infinity"||s.Allow._INFINITY&c&&1<h-d&&h-d<9&&"-Infinity".startsWith(l.substring(d))?(d+=9,-1/0):l.substring(d,d+3)==="NaN"||s.Allow.NAN&c&&h-d<3&&"NaN".startsWith(l.substring(d))?(d+=3,NaN):C()),m=()=>{const b=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(b,++d-Number(R)))}catch(y){p(String(y))}else if(s.Allow.STR&c)try{return JSON.parse(l.substring(b,d-Number(R))+'"')}catch{return JSON.parse(l.substring(b,l.lastIndexOf("\\"))+'"')}f("Unterminated string literal")},v=()=>{d++,w();const b={};try{for(;l[d]!=="}";){if(w(),d>=h&&s.Allow.OBJ&c)return b;const R=m();w(),d++;try{b[R]=g()}catch(y){if(s.Allow.OBJ&c)return b;throw y}w(),l[d]===","&&d++}}catch{if(s.Allow.OBJ&c)return b;f("Expected '}' at end of object")}return d++,b},S=()=>{d++;const b=[];try{for(;l[d]!=="]";)b.push(g()),w(),l[d]===","&&d++}catch{if(s.Allow.ARR&c)return b;f("Expected ']' at end of array")}return d++,b},C=()=>{if(d===0){l==="-"&&p("Not sure what '-' is");try{return JSON.parse(l)}catch(R){if(s.Allow.NUM&c)try{return JSON.parse(l.substring(0,l.lastIndexOf("e")))}catch{}p(String(R))}}const b=d;for(l[d]==="-"&&d++;l[d]&&",]}".indexOf(l[d])===-1;)d++;d==h&&!(s.Allow.NUM&c)&&f("Unterminated number literal");try{return JSON.parse(l.substring(b,d))}catch{l.substring(b,d)==="-"&&f("Not sure what '-' is");try{return JSON.parse(l.substring(b,l.lastIndexOf("e")))}catch(y){p(String(y))}}},w=()=>{for(;d<h&&`
|
|
8
|
-
\r `.includes(l[d]);)d++};return g()},u=o;e.parse=u})),Gd=jd(),Ud=class{parse(e){if(!(!e||e.trim()===""))try{return(0,Gd.parse)(e)}catch{return}}},Xo=new Ud;function $d(e){return Xo.parse(e)}var Bd=class{shouldEmit(e,t){return!0}};function Hd(e){const t=new Error(e.message||e.error?.message||"An error occurred"),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}function zd(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type==="text"?r[r.length-1]={type:"text",content:n}:r.push({type:"text",content:n}),{...s,parts:r}})}function Nt(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.find(l=>l.type==="tool-call"&&l.id===n.id),o=n.metadata??i?.metadata,a=n.input??i?.input,u={type:"tool-call",id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...a!==void 0&&{input:a},...o!==void 0&&{metadata:o}};return i?r[r.indexOf(i)]=u:r.push(u),{...s,parts:r}})}function Zr(e,t,n,s,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===n),l={type:"tool-result",toolCallId:n,content:s,state:r,...i&&{error:i}};return u>=0?a[u]=l:a.push(l),{...o,parts:a}})}function ei(e,t,n,s){return e.map(r=>{if(r.id!==t)return r;const i=[...r.parts],o=i.find(a=>a.type==="tool-call"&&a.id===n);if(o){const a=i.indexOf(o);i[a]={...o,state:"approval-requested",approval:{id:s,needsApproval:!0}}}return{...r,parts:i}})}function ti(e,t,n,s,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}:n,state:s??(r?"error":"complete")}}return{...i,parts:o}})}function Vd(e,t,n){return e.map(s=>{const r=[...s.parts],i=r.find(o=>o.type==="tool-call"&&o.approval?.id===t);if(i&&i.approval){const o=r.indexOf(i);r[o]={...i,approval:{...i.approval,approved:n},state:"approval-responded"}}return{...s,parts:r}})}function qd(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.findIndex(h=>h.type==="structured-output"),o=i>=0?r[i]:null,a=(o?.raw??"")+n,u=$d(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),{...s,parts:r}})}function Kd(e,t,n,s,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(h=>h.type==="structured-output"),u=a>=0?o[a].raw:"";let l=s||u;if(l===""&&n!==void 0)try{l=JSON.stringify(n)}catch{}const c={type:"structured-output",status:"complete",data:n,partial:n,raw:l,...r!==void 0?{reasoning:r}:{}};return a>=0?o[a]=c:o.push(c),{...i,parts:o}})}function ni(e,t,n){return e.map(s=>{if(s.id!==t)return s;const r=[...s.parts],i=r.findIndex(a=>a.type==="structured-output");if(i<0)return r.push({type:"structured-output",status:"error",raw:"",errorMessage:n}),{...s,parts:r};const o=r[i];return o.status==="complete"?s:(r[i]={...o,status:"error",errorMessage:n},{...s,parts:r})})}function kn(e,t,n,s,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(l=>l.type==="thinking"&&l.stepId===n),u={type:"thinking",content:s,stepId:n,...r&&{signature:r}};return a>=0?o[a]=u:o.push(u),{...i,parts:o}})}var Qd=12;function Wd(e){return e.some(t=>{const n=t.metadata;if(!n||typeof n!="object"||Array.isArray(n))return!1;const s=n[cn];return s!==null&&typeof s=="object"&&!Array.isArray(s)&&s.kind==="generic"})}var Jd=class Yo{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 Bd,this.events=t.events||{},this.jsonParser=t.jsonParser||Xo,this.recordingEnabled=t.recording??!1,t.initialMessages&&(this.messages=[...t.initialMessages])}setMessages(t){this.messages=[...t],this.emitMessagesChange()}addUserMessage(t,n,s){const r=typeof t=="string"?[{type:"text",content:t}]:t.map(o=>o),i={id:n??Ne(),role:"user",parts:r,createdAt:new Date,...s!=null?{metadata:s}:{}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(t){this.prepareAssistantMessage();const{messageId:n}=this.ensureAssistantMessage(t);return this.pendingManualMessageId=n,n}getCurrentAssistantMessageId(){let t=null;for(const[n,s]of this.messageStates)s.role==="assistant"&&(t=n);return t}addToolResult(t,n,s){const r=this.messages.find(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=ti(this.messages,t,n,s?"error":void 0,s);const o=Gs(n),a=s?"error":"complete";i=Zr(i,r.id,t,o,a,s),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(t,n){this.messages=Vd(this.messages,t,n),this.emitMessagesChange()}toModelMessages(){const t=[];for(const n of this.messages)t.push(...Id(n));return t}getMessages(){return this.messages}areAllToolsComplete(){const t=this.messages.findLast(r=>r.role==="assistant");if(!t)return!0;const n=t.parts.filter(r=>r.type==="tool-call");if(n.length===0)return!0;const s=new Set(t.parts.filter(r=>r.type==="tool-result").map(r=>r.toolCallId));return n.every(r=>r.state==="complete"||r.state==="approval-responded"||r.output!==void 0&&!r.approval||s.has(r.id)||$o(r))}removeMessagesAfter(t){const n=new Set(this.messages.slice(0,t+1).map(s=>s.id));for(const s of this.structuredMessageIds)n.has(s)||this.structuredMessageIds.delete(s);for(const s of this.structuredOutputUpdateBatches.keys())n.has(s)||this.structuredOutputUpdateBatches.delete(s);for(const s of this.messageStates.keys())n.has(s)||this.messageStates.delete(s);for(const[s,r]of this.toolCallToMessage)n.has(r)||this.toolCallToMessage.delete(s);for(const s of this.activeMessageIds)n.has(s)||this.activeMessageIds.delete(s);this.messages=this.messages.slice(0,t+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(t){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(const n of t)this.processChunk(n);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(t){switch(this.recording&&this.recording.chunks.push({chunk:t,timestamp:Date.now(),index:this.recording.chunks.length}),t.type){case"TEXT_MESSAGE_START":this.handleTextMessageStartEvent(t);break;case"TEXT_MESSAGE_CONTENT":this.handleTextMessageContentEvent(t);break;case"TEXT_MESSAGE_END":this.handleTextMessageEndEvent(t);break;case"TOOL_CALL_START":this.handleToolCallStartEvent(t);break;case"TOOL_CALL_ARGS":this.handleToolCallArgsEvent(t);break;case"TOOL_CALL_END":this.handleToolCallEndEvent(t);break;case"RUN_FINISHED":this.handleRunFinishedEvent(t);break;case"RUN_ERROR":this.handleRunErrorEvent(t);break;case"STEP_FINISHED":this.handleStepFinishedEvent(t);break;case"MESSAGES_SNAPSHOT":this.handleMessagesSnapshotEvent(t);break;case"CUSTOM":this.handleCustomEvent(t);break;case"RUN_STARTED":this.handleRunStartedEvent(t);break;case"REASONING_START":case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"REASONING_MESSAGE_CONTENT":this.handleReasoningMessageContentEvent(t);break;case"REASONING_ENCRYPTED_VALUE":this.handleReasoningEncryptedValueEvent(t);break;case"TOOL_CALL_RESULT":this.handleToolCallResultEvent(t);break;case"STEP_STARTED":this.handleStepStartedEvent(t)}}createMessageState(t,n){const s={id:t,role:n,totalTextContent:"",currentSegmentText:"",lastEmittedText:"",hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(t,s),s}getMessageState(t){return this.messageStates.get(t)}consumePendingThinkingStep(t){if(!this.pendingThinkingStepId)return;const n=this.pendingThinkingStepId;t.currentThinkingStepId=n,t.thinkingSteps.has(n)||(t.thinkingSteps.set(n,""),t.thinkingStepOrder.push(n)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){const t=Array.from(this.activeMessageIds).reverse();for(const n of t){const s=this.messageStates.get(n);if(s&&s.role==="assistant")return n}for(const[n,s]of[...this.messageStates].reverse())if(s.role==="assistant")return n;return null}resumeAssistantState(t,n){this.activeMessageIds.add(t),(n.isComplete||this.isDone)&&(n.isComplete=!1,this.isDone=!1)}ensureAssistantMessage(t){if(t){const o=this.getMessageState(t);if(o)return this.resumeAssistantState(t,o),{messageId:t,state:o}}const n=this.getActiveAssistantMessageId();if(n){const o=this.getMessageState(n);if(o)return this.resumeAssistantState(n,o),{messageId:n,state:o}}if(t){const o=this.messages.find(a=>a.id===t);if(o){const a=this.createMessageState(t,o.role);this.activeMessageIds.add(t);const 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 s=t||Ne(),r={id:s,role:"assistant",parts:[],createdAt:new Date};this.messages=[...this.messages,r];const i=this.createMessageState(s,"assistant");return this.activeMessageIds.add(s),this.pendingManualMessageId=s,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:s,state:i}}mergeMessageMetadata(t,n){if(n==null||typeof n!="object"||Array.isArray(n))return;const s=this.messages.find(c=>c.id===t);if(!s)return;const r=n,i=$(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=Fo(s.metadata,o),u=ne($(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:n,role:s}=t,r=s==="user"||s==="system"?s:"assistant";if(this.pendingManualMessageId){const o=this.pendingManualMessageId;if(this.pendingManualMessageId=null,o!==n){this.messages=this.messages.map(l=>l.id===o?{...l,id:n}:l);const u=this.messageStates.get(o);u&&(u.id=n,this.messageStates.delete(o),this.messageStates.set(n,u)),this.activeMessageIds.delete(o),this.activeMessageIds.add(n);for(const[l,c]of this.toolCallToMessage)c===o&&this.toolCallToMessage.set(l,n)}let a=this.messageStates.get(n);a?a.hasToolCallsSinceTextStart&&(a.currentSegmentText!==a.lastEmittedText&&this.emitTextUpdateForMessage(n),a.currentSegmentText="",a.lastEmittedText="",a.hasToolCallsSinceTextStart=!1):(a=this.createMessageState(n,r),this.activeMessageIds.add(n)),this.mergeMessageMetadata(n,t.metadata),this.emitMessagesChange();return}if(this.messages.find(o=>o.id===n)){this.activeMessageIds.add(n);const o=this.messageStates.get(n);o?o.hasToolCallsSinceTextStart&&(o.currentSegmentText!==o.lastEmittedText&&this.emitTextUpdateForMessage(n),o.currentSegmentText="",o.lastEmittedText="",o.hasToolCallsSinceTextStart=!1):this.createMessageState(n,r),this.mergeMessageMetadata(n,t.metadata);return}const i={id:n,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(n,r),this.activeMessageIds.add(n),this.mergeMessageMetadata(n,t.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(t){const{messageId:n}=t;this.mergeMessageMetadata(n,t.metadata);const s=this.getMessageState(n);s&&(s.isComplete||s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(n))}handleMessagesSnapshotEvent(t){this.resetStreamState();const n=this.messages,s=new Map(n.map(i=>[i.id,i])),r=this.mergeReasoningFanOut(t.messages.map(wd));this.messages=this.reconcileSnapshotToolCalls(r,n).map(i=>{if(i.metadata!=null)return i;const o=s.get(i.id);return o?.metadata==null?i:{...i,metadata:o.metadata}}),this.emitMessagesChange()}mergeReasoningFanOut(t){const n=[];let s=[];const r=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=()=>{n.push(...s),s=[]};for(const u of t){if(i(u)){s.push(u);continue}if(u.role==="assistant"&&s.length>0&&!o(u)){n.push({...u,parts:[...s.flatMap(r),...u.parts]}),s=[];continue}a(),n.push(u)}return a(),n}reconcileSnapshotToolCalls(t,n){const s=new Map;for(const o of n)for(const a of o.parts)a.type==="tool-call"&&s.set(a.id,a);const r=new Set;for(const o of t)for(const a of o.parts)a.type==="tool-call"&&r.add(a.id);const i=[];for(const o of t){const a=o.parts.filter(h=>h.type==="tool-result"),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=s.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,s)}enrichSnapshotToolCallsFromResults(t,n){const s=new Map;for(const r of t)for(const i of r.parts)i.type==="tool-result"&&s.set(i.toolCallId,i);return t.map(r=>{const i=r.parts.map(o=>{if(o.type!=="tool-call")return o;const a=n.get(o.id),u=s.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:n,state:s}=this.ensureAssistantMessage(t.messageId);if(this.mergeMessageMetadata(n,t.metadata),this.structuredMessageIds.has(n)){const c=t.delta||"";c!==""&&(this.messages=qd(this.messages,n,c),s.totalTextContent+=c,this.queueStructuredOutputUpdate(n,c),this.emitMessagesChange());return}const r=s.currentSegmentText;s.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(t,r)&&(r!==s.lastEmittedText&&this.emitTextUpdateForMessage(n),s.currentSegmentText="",s.lastEmittedText="",s.hasToolCallsSinceTextStart=!1),s.hasToolCallsSinceTextStart=!1;const i=s.currentSegmentText,o=t.delta||"",a=o!==""?i+o:i,u=a.slice(i.length);s.currentSegmentText=a,s.totalTextContent+=u;const l=t.delta||"";this.chunkStrategy.shouldEmit(l,s.currentSegmentText)&&s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(n)}handleToolCallStartEvent(t){const n=t.parentMessageId??this.getActiveAssistantMessageId(),{messageId:s,state:r}=this.ensureAssistantMessage(n??void 0);r.hasToolCallsSinceTextStart=!0;const i=t.toolCallId;if(!r.toolCalls.get(i)){const o="awaiting-input",a=t.toolCallName,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,s),this.messages=Nt(this.messages,s,{id:t.toolCallId,name:a,arguments:"",state:o,...u!==void 0&&{metadata:u}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(s,t.toolCallId,o,"")}}handleToolCallArgsEvent(t){const n=t.toolCallId,s=this.toolCallToMessage.get(n);if(!s)return;const r=this.getMessageState(s);if(!r)return;const i=r.toolCalls.get(n);if(!i)return;const o=i.state==="awaiting-input";i.arguments+=t.delta||"",o&&t.delta&&(i.state="input-streaming"),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=Nt(this.messages,s,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(s,i.id,i.state,i.arguments)}handleToolCallEndEvent(t){const n=this.toolCallToMessage.get(t.toolCallId);if(!n)return;const s=this.getMessageState(n);if(!s)return;const r=t.input!==void 0?t.input:$(t)?.input,i=s.toolCalls.get(t.toolCallId);if(i&&i.state!=="input-complete"){if(r!==void 0&&!i.arguments)try{i.arguments=JSON.stringify(r)}catch{}const o=s.toolCallOrder.indexOf(t.toolCallId);this.completeToolCall(n,o,i),r!==void 0&&(i.parsedArguments=r,this.messages=Nt(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:"input-complete",input:r,...i.metadata!==void 0&&{metadata:i.metadata}}),this.emitMessagesChange())}}extractToolResultError(t){return t&&typeof t=="object"&&"error"in t&&typeof t.error=="string"?t.error:typeof t=="string"?t:"Tool execution failed"}handleToolCallResultEvent(t){const n=this.toolCallToMessage.get(t.toolCallId)??this.messages.find(o=>o.parts.some(a=>a.type==="tool-call"&&a.id===t.toolCallId))?.id;if(!n)return;const s=t.state==="output-error"||$(t)?.state==="output-error";let r;try{r=JSON.parse(t.content)}catch{r=t.content}this.messages=ti(this.messages,t.toolCallId,r,s?"error":void 0);const i=s?"error":"complete";this.messages=Zr(this.messages,n,t.toolCallId,t.content,i,i==="error"?this.extractToolResultError(r):void 0),this.emitMessagesChange()}handleRunStartedEvent(t){this.activeRuns.add(t.runId)}handleRunFinishedEvent(t){const n=t;if(this.finishReason=n.finishReason!==void 0?n.finishReason:$(t)?.finishReason??null,this.activeRuns.delete(t.runId),t.outcome?.type==="interrupt"&&this.handleInterrupts(t.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason==="tool_calls"&&t.outcome?.type!=="interrupt")return;this.isDone=!0,this.finalizeStream()}}handleInterrupts(t){const n=Wd(t);for(const s of t){const r=s.metadata&&typeof s.metadata=="object"?s.metadata:{},i=typeof r.kind=="string"?r.kind:void 0,o=s.toolCallId;if(!o)continue;const a=typeof r.toolName=="string"?r.toolName:this.findToolCallName(o),u=Object.hasOwn(r,"input")?r.input:{};if(i==="approval"||s.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=ei(this.messages,l,o,s.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:o,toolName:a,input:u,approvalId:s.id});continue}if(i==="client_tool"||s.reason==="client_tool_input"){if(n)continue;this.events.onToolCall?.({toolCallId:o,toolName:a,input:u})}}}findToolCallName(t){for(const n of this.messageStates.values()){const s=n.toolCalls.get(t);if(s)return s.name}return""}handleRunErrorEvent(t){this.hasError=!0;const n=Jo(t);n?this.activeRuns.delete(n):this.activeRuns.clear();const{messageId:s}=this.ensureAssistantMessage(),r=t.message||"An error occurred";t.message||console.error("[StreamProcessor] RUN_ERROR with no message; original chunk:",t),this.structuredMessageIds.has(s)&&(this.flushStructuredOutputUpdate(s),this.messages=ni(this.messages,s,r),this.structuredMessageIds.delete(s),this.emitStructuredOutputChange(s,"error"),this.emitMessagesChange()),this.events.onError?.(Hd(t))}handleStepStartedEvent(t){const n=t.stepName||Ne(),s=this.getActiveAssistantMessageId();if(s){const r=this.getMessageState(s);if(r){r.currentThinkingStepId=n,r.thinkingSteps.has(n)||(r.thinkingSteps.set(n,""),r.thinkingStepOrder.push(n)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=n}handleStepFinishedEvent(t){const n=t,s=n.signature;if(!s)return;const{messageId:r,state:i}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),o=i.currentThinkingStepId??n.stepId;if(!o)return;const a=i.thinkingSteps.get(o);a!==void 0&&(i.thinkingStepSignatures.set(o,s),this.messages=kn(this.messages,r,o,a,s),this.emitMessagesChange())}handleReasoningMessageContentEvent(t){const{messageId:n,state:s}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);s.hasSeenReasoningEvents=!0;const r=t.delta||"";this.consumePendingThinkingStep(s);const i=s.currentThinkingStepId??t.messageId;s.thinkingSteps.has(i)||(s.thinkingSteps.set(i,""),s.thinkingStepOrder.push(i),s.currentThinkingStepId=i);const o=(s.thinkingSteps.get(i)??"")+r;s.thinkingSteps.set(i,o),this.messages=kn(this.messages,n,i,o,s.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(n,i,o)}handleReasoningEncryptedValueEvent(t){const n=t.encryptedValue;if(typeof n!="string"||n==="")return;if(t.subtype==="tool-call"){this.attachToolCallSignature(t.entityId,n);return}const{messageId:s,state:r}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),i=r.currentThinkingStepId??t.entityId;r.thinkingStepSignatures.set(i,n);const o=r.thinkingSteps.get(i)??"";r.thinkingSteps.has(i)||(r.thinkingSteps.set(i,o),r.thinkingStepOrder.push(i)),this.messages=kn(this.messages,s,i,o,n),this.emitMessagesChange()}attachToolCallSignature(t,n){this.messages=this.messages.map(s=>{let r=!1;const i=s.parts.map(o=>o.type!=="tool-call"||o.id!==t?o:(r=!0,{...o,metadata:{...o.metadata!=null&&typeof o.metadata=="object"?o.metadata:{},thoughtSignature:n}}));return r?{...s,parts:i}:s});for(const s of this.messageStates.values()){const r=s.toolCalls.get(t);r&&(r.metadata={...r.metadata??{},thoughtSignature:n})}this.emitMessagesChange()}handleCustomEvent(t){const n=this.getActiveAssistantMessageId();if(t.name==="structured-output.start"&&t.value){const s=t.value,{messageId:r}=this.ensureAssistantMessage(s.messageId??n??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:"start",messageId:r,status:"streaming",raw:""}));return}if(t.name==="structured-output.complete"&&t.value){const s=t.value,{messageId:r}=this.ensureAssistantMessage(s.messageId??n??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=Kd(this.messages,r,s.object,s.raw??"",s.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,"complete"),this.emitMessagesChange())}if(t.name==="tool-input-available"&&t.value){const{toolCallId:s,toolName:r,input:i}=t.value;this.events.onToolCall?.({toolCallId:s,toolName:r,input:i});return}if(t.name==="approval-requested"&&t.value){const{toolCallId:s,toolName:r,input:i,approval:o}=t.value,a=n??this.toolCallToMessage.get(s);a&&(this.messages=ei(this.messages,a,s,o.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:s,toolName:r,input:i,approvalId:o.id});return}if(t.name==="ui-resource"&&t.value){const s=t.value,r=this.toolCallToMessage.get(s.toolCallId)??n;if(r){const i={type:"ui-resource",resource:s.resource,toolCallId:s.toolCallId,toolName:s.toolName,...s.serverId!==void 0&&{serverId:s.serverId},...s.meta!==void 0&&{meta:s.meta}};this.messages=this.messages.map(o=>o.id===r?{...o,parts:[...o.parts,i]}:o),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${s.toolCallId}" (toolName "${s.toolName}")`);return}if(this.events.onCustomEvent){const s=t.value&&typeof t.value=="object"?t.value.toolCallId:void 0;this.events.onCustomEvent(t.name,t.value,{toolCallId:s})}}isNewTextSegment(t,n){return!0}completeAllToolCalls(){for(const t of this.activeMessageIds)this.completeAllToolCallsForMessage(t)}completeAllToolCallsForMessage(t){const n=this.getMessageState(t);n&&n.toolCalls.forEach((s,r)=>{if(s.state!=="input-complete"){const i=n.toolCallOrder.indexOf(r);this.completeToolCall(t,i,s)}})}completeToolCall(t,n,s){s.state="input-complete";let r=!1;try{s.parsedArguments=JSON.parse(s.arguments),r=!0}catch{s.parsedArguments=void 0}this.isToolCallPartErrored(s.id)||this.isToolCallPartAwaitingUserAction(s.id)||(this.messages=Nt(this.messages,t,{id:s.id,name:s.name,arguments:s.arguments,state:"input-complete",...r&&{input:s.parsedArguments},...s.metadata!==void 0&&{metadata:s.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(t,s.id,"input-complete",s.arguments))}isToolCallPartAwaitingUserAction(t){return this.messages.some(n=>n.parts?.some(s=>s.type==="tool-call"&&s.id===t&&(s.state==="approval-requested"||s.state==="approval-responded")))}isToolCallPartErrored(t){return this.messages.some(n=>n.parts?.some(s=>s.type==="tool-call"&&s.id===t&&s.state==="error"))}emitTextUpdateForMessage(t){const n=this.getMessageState(t);n&&(n.lastEmittedText=n.currentSegmentText,this.messages=zd(this.messages,t,n.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(t,n.currentSegmentText))}queueStructuredOutputUpdate(t,n){const s=this.structuredOutputUpdateBatches.get(t),r={delta:`${s?.delta??""}${n}`,chunkCount:(s?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(t,r),r.chunkCount>=Qd&&this.flushStructuredOutputUpdate(t)}flushStructuredOutputUpdate(t){const n=this.structuredOutputUpdateBatches.get(t);!n||n.chunkCount===0||(this.structuredOutputUpdateBatches.delete(t),this.emitStructuredOutputChange(t,"update",n.delta))}emitStructuredOutputChange(t,n,s){const r=this.messages.find(i=>i.id===t)?.parts.find(i=>i.type==="structured-output");r&&this.events.onStructuredOutputChange?.({phase:n,messageId:t,status:r.status,raw:r.raw,...r.partial!==void 0?{partial:r.partial}:{},...r.data!==void 0?{data:r.data}:{},...r.reasoning!==void 0?{reasoning:r.reasoning}:{},...r.errorMessage!==void 0?{errorMessage:r.errorMessage}:{},...s!==void 0?{delta:s}:{}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;let t;for(const n of this.activeMessageIds){const s=this.getMessageState(n);if(!s)continue;this.completeAllToolCallsForMessage(n),s.currentSegmentText!==s.lastEmittedText&&this.emitTextUpdateForMessage(n),s.isComplete=!0;const r=this.messages.find(i=>i.id===n);r&&r.role==="assistant"&&(t=r)}for(const n of this.structuredMessageIds)this.flushStructuredOutputUpdate(n),this.messages=ni(this.messages,n,"Stream ended without structured-output.complete"),this.emitStructuredOutputChange(n,"error");if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),t&&!this.hasError&&this.isWhitespaceOnlyMessage(t)){this.messages=this.messages.filter(n=>n.id!==t.id),this.emitMessagesChange();return}t&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(t))}getCompletedToolCalls(){const t=[];for(const n of this.messageStates.values())for(const s of n.toolCalls.values())s.state==="input-complete"&&t.push({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments},...s.metadata!==void 0&&{metadata:s.metadata}});return t}getResult(){const t=this.getCompletedToolCalls();let n="",s="";for(const r of this.messageStates.values()){n+=r.totalTextContent;for(const i of r.thinkingStepOrder)s+=r.thinkingSteps.get(i)??""}return{content:n,thinking:s||void 0,toolCalls:t.length>0?t:void 0,finishReason:this.finishReason}}getState(){let t="",n="";const s=new Map,r=[];for(const i of this.messageStates.values()){t+=i.totalTextContent;for(const o of i.thinkingStepOrder)n+=i.thinkingSteps.get(o)??"";for(const[o,a]of i.toolCalls)s.set(o,a);r.push(...i.toolCallOrder)}return{content:t,thinking:n,toolCalls:s,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:"1.0",timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.streamEndEmitted=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(t){return t.parts.length===0?!1:t.parts.every(n=>n.type==="text"&&n.content.trim()==="")}static async replay(t,n){return new Yo(n).process(Xd(t))}};function Xd(e){return{async*[Symbol.asyncIterator](){for(const{chunk:t}of e.chunks)yield t}}}var fs=(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})({}),Yd=/^[a-z][a-z0-9-]{0,63}$/;function ps(e){return typeof e=="string"&&Yd.test(e)}function Zd(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"||!ps(t.provider)||!("message"in t)||typeof t.message!="string")}var gs=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name="ByokMissingError",this.provider=e}},si=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}},Zo=class extends Error{constructor(){super("BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider."),this.name="ByokUnresolvedProviderError"}},ea=new WeakMap;function te(e){return ea.get(e)??Jo(e)}var ta=class extends Error{constructor(){super("Stream ended with unterminated trailing data — connection was likely cut short."),this.name="StreamTruncatedError"}},Us=class extends Error{constructor(e){super("Stream response body read failed",{cause:e}),this.name="StreamReadError"}},eh=class extends Error{constructor(){super("Durable run ended without a terminal event and could not resume — the run did not complete."),this.name="DurableStreamIncompleteError"}},th=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name="StreamReconnectLimitError"}};function nh(e){const t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw new Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function sh(e){const t=nh(e),n=new Set;let s,r=0;return{get lastEventId(){return s},note(i){return i===void 0?"new":i===""?(s=void 0,n.clear(),"reset"):n.has(i)?"duplicate":(n.add(i),s=i,"new")},async waitBeforeReconnect(i,o){if(i)r=0;else if(r+=1,r>t.maxAttempts)throw new th(t.maxAttempts);await rh(t.delayMs,o)}}}function rh(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{const s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}function ri(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Dt(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 ot(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((n,s)=>{t[s]=n}),t}return e}var ih="X-Run-Id";function oh(e){return e===void 0?{}:{[ih]:e}}function $s(e,t){const n=e.indexOf("#"),s=n===-1?"":e.slice(n),r=n===-1?e:e.slice(0,n),i=r.indexOf("?"),o=i===-1?r:r.slice(0,i),a=new URLSearchParams(i===-1?"":r.slice(i+1));for(const[l,c]of Object.entries(t))a.set(l,c);const u=a.toString();return`${o}${u.length===0?"":`?${u}`}${s}`}async function*ah(e,t){try{const n=Gc();let s="";for(;!t?.aborted;){let r;try{r=await e.read()}catch(u){if(t?.aborted)return;throw new Us(u)}const{done:i,value:o}=r;if(i)break;s+=n.decode(o,{stream:!0});const a=s.split(`
|
|
9
|
-
`);s=a.pop()||"";for(const u of a){const l=u.endsWith("\r")?u.slice(0,-1):u;l.trim()&&(yield l)}}if(s+=n.decode(),s.trim()&&!t?.aborted)throw new ta}finally{e.releaseLock()}}function lh(e){return Wo(e)}function uh(e){const t=$(e)?.model;if(typeof t=="string")return t;const n="usage"in e?e.usage:void 0;if(Array.isArray(n)){const s=n[0]?.model;if(typeof s=="string")return s}}async function*ch(e,t){let n,s,r,i;for await(const o of e){if(o==="id"||o.startsWith("id:")){const h=o==="id"?"":o.slice(3);i=h.startsWith(" ")?h.slice(1):h;continue}if(o.startsWith(":")||o.startsWith("event:")||o.startsWith("retry:"))continue;const a=Uc(o);if(a==="[DONE]"){yield{chunk:ko({type:fs.RUN_FINISHED,threadId:n??t?.threadId??"",runId:s??t?.runId??"",timestamp:Date.now()},{finishReason:"stop",...r!==void 0?{model:r}:{}})};return}const u=lh(JSON.parse(a));"threadId"in u&&typeof u.threadId=="string"&&(n=u.threadId),"runId"in u&&typeof u.runId=="string"&&(s=u.runId);const l=uh(u);l!==void 0&&(r=l);const c=i;i=void 0,yield{chunk:u,...c!==void 0?{id:c}:{}}}}async function Bs(e){if(!e.ok){if(e.status===401){const t=await e.clone().json().catch(()=>null);if(Zd(t))throw new gs(t.error.provider)}throw new Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}async function dh(e,t,n,s,r){const i=await e($s(t,{threadId:r}),{method:"GET",headers:{Accept:"application/json",...n},credentials:s});await Bs(i);const o=await i.json(),a=o.activeRun&&typeof o.activeRun.runId=="string"?{runId:o.activeRun.runId}:null,u=o.interrupts&&typeof o.interrupts.runId=="string"&&Array.isArray(o.interrupts.pending)&&o.interrupts.pending.length>0?{runId:o.interrupts.runId,pending:o.interrupts.pending}:null;return{messages:Array.isArray(o.messages)?Po(o.messages):[],activeRun:a,interrupts:u}}async function hh(e,t,n,s,r){const i=await e($s(t,{threadId:r}),{method:"GET",headers:{Accept:"application/json",...n},credentials:s});await Bs(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*ms(e,t,n){await Bs(e),yield*ch(ah(jc(e),t),n)}async function*fh(e,t){for await(const{chunk:n}of ms(e,t))yield n}function ii(e,t,n,s){return async function*(r,i){let o;try{o=await e(t,{...n,headers:{...n.headers,...r},...i?{signal:i}:{}})}catch(a){throw new Us(a)}yield*s(o,i)}}async function*oi(e,t,n){const s=sh(n);for(;;){if(t?.aborted)return;const r=s.lastEventId!==void 0?{"Last-Event-ID":s.lastEventId}:{};let i=!1,o=!1;try{for await(const{chunk:a,id:u}of e(r,t))s.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 ta||a instanceof Us)&&s.lastEventId!==void 0){await s.waitBeforeReconnect(o,t);continue}throw a}if(t?.aborted||i)return;if(s.lastEventId!==void 0){if(o){await s.waitBeforeReconnect(!0,t);continue}throw new eh}return}}function ai(e){if(!e)throw new Error("Connection adapter is required");const t="connect"in e,n="subscribe"in e,s="send"in e;if(t&&(n||s))throw new Error("Connection adapter must provide either connect or both subscribe and send, not both modes");if(n&&s){const u=e.joinRun?.bind(e),l=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...u?{joinRun:u}:{},...l?{hydrate:l}:{}}}if(!t)throw new Error("Connection adapter must provide either connect or both subscribe and send");let r=[],i=[];function o(u,l){l&&ea.set(u,l);const c=i.shift();c?c(u):r.push(u)}async function a(u){const l=()=>r.length===0&&(i.length>0||u?.aborted);for(let h=0;h<16&&!u?.aborted;h++){if(l())return;await Promise.resolve()}let c=0;for(;!u?.aborted;)if(l()||(await new Promise(h=>setTimeout(h,0)),c++,i.length===0&&c>=32))return}return{subscribe(u){const l=r.splice(0),c=[];return r=l,i=c,(async function*(){for(;!u?.aborted;){let h;const d=l.shift();d!==void 0?h=d:h=await new Promise(f=>{const p=()=>f(null);c.push(g=>{u?.removeEventListener("abort",p),f(g)}),u?.addEventListener("abort",p,{once:!0})}),h!==null&&(yield h)}})()},async send(u,l,c,h){let d=!1,f,p;try{const g=e.connect(u,l,c,h);for await(const m of g)"threadId"in m&&typeof m.threadId=="string"&&(f=m.threadId),"runId"in m&&typeof m.runId=="string"&&(p=m.runId),(m.type==="RUN_FINISHED"||m.type==="RUN_ERROR")&&(d=!0),o(m,h?.runId);!c?.aborted&&!d&&o(ko({type:fs.RUN_FINISHED,threadId:Dt(f??h?.threadId,"threadId"),runId:Dt(p??h?.runId,"runId"),timestamp:Date.now()},{finishReason:"stop",model:"connect-wrapper"}),h?.runId)}catch(g){if(!c?.aborted&&!d)try{const m=g instanceof Error?g.message:"Unknown error in connect()";o({type:fs.RUN_ERROR,threadId:Dt(f??h?.threadId,"threadId"),runId:Dt(p??h?.runId,"runId"),timestamp:Date.now(),message:m},h?.runId)}catch{}throw g}await a(c)},...typeof e.joinRun=="function"?{joinRun:(u,l)=>e.joinRun(u,l)}:{},...(()=>{const u=e.hydrate;return typeof u=="function"?{hydrate:l=>u(l)}:{}})()}}function ph(e,t,n,s){const r=_d(e),i={...s.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??ri("thread"),runId:n?.runId??ri("run"),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:r,tools:n?.clientTools??[],context:[],forwardedProps:i,data:{...i}}}function $f(e,t={}){return{async*connect(n,s,r,i){const o=typeof e=="function"?e():e,a=typeof t=="function"?await t():t,u={"Content-Type":"application/json",...ot(a.headers),...ot(i?.headers),...oh(i?.runId)},l=ph(n,s,i,a),c=a.fetchClient??fetch,h=r||a.signal;yield*oi(ii(c,o,{method:"POST",headers:u,body:JSON.stringify(l),credentials:a.credentials||"same-origin"},(d,f)=>ms(d,f,{...i?.threadId!==void 0?{threadId:i.threadId}:{},...i?.runId!==void 0?{runId:i.runId}:{}})),h,a.reconnect)},async*joinRun(n,s){const r=typeof e=="function"?e():e,i=typeof t=="function"?await t():t,o=$s(r,{offset:"-1",runId:n}),a={...ot(i.headers)},u=i.fetchClient??fetch,l=s||i.signal;yield*oi(ii(u,o,{method:"GET",headers:a,credentials:i.credentials||"same-origin"},(c,h)=>ms(c,h,{runId:n})),l,i.reconnect)},async hydrate(n){const s=typeof e=="function"?e():e,r=typeof t=="function"?await t():t;return dh(r.fetchClient??fetch,s,ot(r.headers),r.credentials||"same-origin",n)},async hydrateGeneration(n){const s=typeof e=="function"?e():e,r=typeof t=="function"?await t():t;return hh(r.fetchClient??fetch,s,ot(r.headers),r.credentials||"same-origin",n)}}}function gh(e){return{async*connect(t,n,s,r){if(!s)throw new Error("fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.");if(!r)throw new Error("fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.");const i=await e({messages:t,data:n,threadId:r.threadId,runId:r.runId,...r.parentRunId!==void 0?{parentRunId:r.parentRunId}:{},...r.resume!==void 0?{resume:r.resume}:{}},{signal:s,headers:r.headers});i instanceof Response?yield*fh(i,s):yield*mh(i,s)}}}async function*mh(e,t){if(t.aborted)return;const n=e[Symbol.asyncIterator](),s=new Promise(r=>{t.addEventListener("abort",()=>r({done:!0,value:void 0}),{once:!0})});try{for(;;){const r=await Promise.race([n.next(),s]);if(r.done)return;yield r.value}}finally{await n.return?.()}}function pe(e){return e.resumable}function Nn(e,t){const n=cd(e.descriptor);return n?{...t,metadata:ud(n)}:t}function vh(e){return"cancel"in e&&"clearResolution"in e}var Sh=new Set(["invalid-payload","invalid-edited-args","invalid-tool-output","invalid-response-schema","unknown-interrupt","expired","stale","conflict","legacy-unsupported"]),yh=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 oe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function na(e){return oe(e)&&e.kind==="approval"&&typeof e.toolName=="string"&&"input"in e}function sa(e){return oe(e)&&e.kind==="client_tool"&&typeof e.toolName=="string"&&"input"in e}function Ih(e){return na(e.metadata)||sa(e.metadata)}function li(e){return sd(e)}function Rh(e){if(!oe(e.metadata))return!1;const t=e.metadata[cn];return!oe(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 Ch(e){if(!oe(e.metadata))return!1;const t=e.metadata[cn];return!oe(t)||t.kind!=="generic"?!1:"definitionId"in t||"key"in t||"batchIndex"in t||"payloadSchemaHash"in t}function bh(e){return e.metadata?.["tanstack:interruptPayload"]}function wh(e){return e==="tanstack:client_tool_execution"||e==="client_tool_input"}function lt(e){if(e.responseSchema!==void 0)try{return Ge(je(e.responseSchema))}catch{return}}function ui(e){if(e!==void 0)try{return od(e)}catch{return}}function Pe(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"then"in e&&typeof e.then=="function"}function jt(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(Ae(e)){const s=e["~standard"].validate(t),r=i=>i.issues?{code:n,message:i.issues[0]?.message??"Schema validation failed."}:{valid:!0,payload:i.value};return Pe(s)?Promise.resolve(s).then(r):r(s)}return{valid:!0,payload:t}}function Eh(e){for(const t of Sh)if(t===e)return!0;return!1}function Th(e){for(const t of yh)if(t===e)return!0;return!1}function ci(e){if(!oe(e))return!1;const t=e.scope,n=e.code;return typeof n=="string"&&typeof e.message=="string"&&typeof e.retryable=="boolean"&&typeof e.threadId=="string"&&typeof e.interruptedRunId=="string"&&typeof e.generation=="number"?t==="item"?Eh(n)&&typeof e.interruptId=="string"&&(e.source==="client"||e.source==="server"):t==="batch"&&Th(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(s=>typeof s=="string")&&(e.source==="client"||e.source==="server"||e.source==="transport"):!1}function _h(e){return ci(e)?[e]:!oe(e)||!Array.isArray(e.errors)?[]:e.errors.every(ci)?e.errors:[]}function ra(e,t){if(e.length!==t.length)return!1;const n=[...e].sort(),s=[...t].sort();return n.every((r,i)=>r===s[i])}function di(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&ra(e.interruptIds,t.interruptIds)}function Ah(e,t,n){const s=n.filter(a=>a.source!=="transport"),r=a=>t.includes(a)&&s.some(u=>di(a,u)),i=e.filter(a=>!r(a)),o=t.filter(a=>!s.some(u=>di(a,u)));return Object.freeze({rootErrors:Object.freeze([...i,...n]),submissionRootErrors:Object.freeze([...o,...s])})}function Mh(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;const n=t.resolutions.map(s=>s.interruptId);return e.scope==="item"?n.includes(e.interruptId):ra(e.interruptIds,n)}function Dn(e,t,n){const s=lt(e)??n?.responseSchemaHash;return B({v:1,kind:"generic",interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...s!==void 0?{responseSchemaHash:s}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}})}function xh(e,t){const n=B(e.descriptor),s=e.error===void 0?Object.freeze([]):Object.freeze([B(e.error)]),r=s[0];return{id:n.id,interruptId:n.id,reason:n.reason,...n.message!==void 0?{message:n.message}:{},...n.responseSchema!==void 0?{responseSchema:n.responseSchema}:{},...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{},...n.metadata!==void 0?{metadata:n.metadata}:{},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:s,...r!==void 0?{error:r}:{},canResolve:e.canResolve}}var Oh=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;const t=new Map;for(const n of e.interrupts??[]){if(t.has(n.id))throw new Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t="live"){this.activeSubmissionOperation=void 0,this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:B(e.interrupts)};const n=new Map;for(const s of e.interrupts){const r=li(s);r?.kind==="generic"&&r.definitionId!==void 0&&r.key!==void 0&&r.batchIndex!==void 0&&n.set(r.batchIndex,(n.get(r.batchIndex)??0)+1)}this.items=e.interrupts.map(s=>this.hydrateInterrupt(s,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind==="generic"&&e.definition!==void 0)}reset(e){this.activeSubmissionOperation=void 0,this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??"live")}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e=="boolean"){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(const e of this.items)pe(e)&&(e.validationGeneration++,e.resolution=Object.freeze(Nn(e,{interruptId:e.descriptor.id,status:"cancelled"})),e.status="staged",e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw new Error("Interrupt submission is already active.");const e=this.retrySubmission;if(!e){this.addRootError("transport","There is no retryable interrupt submission.",!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){const n=this.items.find(s=>s.kind==="client-tool-execution"&&s.binding?.kind==="client-tool-execution"&&s.binding.toolCallId===e||s.kind==="generic"&&wh(s.descriptor.reason)&&s.descriptor.toolCallId===e&&sa(s.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){const n=this.items.find(s=>s.descriptor.id===e&&(s.kind==="tool-approval"||s.kind==="generic"&&s.descriptor.reason==="approval_required"&&na(s.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){const s=B(e),r=li(s),i=r===void 0&&Ih(s);if(r===void 0&&!i)return Rh(s)?{descriptor:s,binding:Dn(s,t,void 0),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","The interrupt binding is invalid or incomplete."),validationGeneration:0}:{descriptor:s,binding:void 0,kind:"unbound",status:"pending",canResolve:!1,resumable:!1,validationGeneration:0};const o=r!==void 0&&r.interruptId===s.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&<(s)===r.responseSchemaHash,a=r!==void 0&&r.interruptId===s.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&r.responseSchemaHash===(lt(s)??r.responseSchemaHash);if(r!==void 0&&Ch(s)&&(!a||r.kind!=="generic"||r.definitionId===void 0||r.key===void 0||r.batchIndex===void 0))return{descriptor:s,binding:Dn(s,t,r),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","The interrupt binding does not match this interrupted run."),validationGeneration:0};if(a&&r.kind==="tool-approval"){const l=this.tools?.find(c=>c.name===r.toolName);if(l?.needsApproval===!0&&s.toolCallId===r.toolCallId)try{const c=td(l.approvalSchema,l.inputSchema);if(qr(l.inputSchema)===r.inputSchemaHash&&c.approvalSchemaHash===r.approvalSchemaHash&&c.responseSchemaHash===r.responseSchemaHash)return{descriptor:s,binding:B(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&&s.toolCallId===r.toolCallId&&qr(l.outputSchema)===r.outputSchemaHash)return{descriptor:s,binding:B(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&&n.get(r.batchIndex)!==1)return{descriptor:s,binding:B(r),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(s.id,"stale","Generic interrupt batch contains a duplicate batchIndex."),validationGeneration:0};if(o&&r.kind==="generic"&&r.definitionId!==void 0&&r.key!==void 0&&r.batchIndex!==void 0&&r.key.length>0&&n.get(r.batchIndex)===1){const l=this.interruptDefinitions.get(r.definitionId);if(l!==void 0&&ui(l.responseSchema)===r.responseSchemaHash&&(l.payloadSchema===void 0?r.payloadSchemaHash===void 0:r.payloadSchemaHash===ui(l.payloadSchema))){const c=bh(s);return{descriptor:s,binding:B(r),definition:l,kind:"generic",status:"pending",canResolve:!0,resumable:!0,...c===void 0?{}:{payload:B(c)},validationGeneration:0}}}const u=i||r!==void 0&&r.interruptId===s.id&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation&&(r.kind!=="generic"||lt(s)===void 0||r.responseSchemaHash===lt(s));return{descriptor:s,binding:Dn(s,t,r),kind:"generic",status:"pending",canResolve:u,resumable:u,validationGeneration:0}}buildSnapshot(e){const t=this.requireHydration(),n=this.items.filter(s=>s.kind!=="client-tool-execution"&&s.status!=="submitting").map(s=>{const r=xh(s,t);if(s.kind==="unbound"||s.binding===void 0){const a={...r,kind:"unbound",canResolve:!1};return Object.freeze(a)}if(s.kind==="tool-approval"&&s.binding.kind==="tool-approval"){const a=B(s.binding),u={...r,kind:"tool-approval",binding:a,toolName:s.binding.toolName,toolCallId:s.binding.toolCallId,originalArgs:B(s.binding.originalArgs),cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:(l,c)=>{const h=oe(c)?c:void 0;this.resolveItem(s.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=s.binding.kind==="generic"?B(s.binding):B({v:1,kind:"generic",interruptId:s.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof s.binding.responseSchemaHash=="string"?{responseSchemaHash:s.binding.responseSchemaHash}:{}});if(s.definition!==void 0&&s.binding.kind==="generic"){const a={...r,kind:"generic",definitionId:s.definition.id,key:s.binding.key??"",payload:s.payload,binding:i,cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:u=>this.resolveItem(s.descriptor.id,u,e)};return Object.freeze(a)}const o={...r,kind:"generic",binding:i,cancel:()=>this.cancelItem(s.descriptor.id,e),clearResolution:()=>this.clearItem(s.descriptor.id,e),resolveInterrupt:a=>this.resolveItem(s.descriptor.id,a,e)};return Object.freeze(o)});return Object.freeze(n)}publish(e="live"){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,n){this.assertItemMutable(n);const s=this.findItem(e);if(this.invalidateRetry(),!s.canResolve){s.status="error",s.error=this.itemError(e,"invalid-response-schema","The interrupt response schema is invalid and cannot be resolved."),n||this.publish();return}const r=++s.validationGeneration,i=this.validateCandidate(s,t);if(Pe(i)){s.status="validating",s.error=void 0,n||this.publish(),Promise.resolve(i).then(o=>{r===s.validationGeneration&&this.applyValidation(s,o,n)}).catch(o=>{r===s.validationGeneration&&this.applyValidation(s,{code:this.validationCode(s),message:o instanceof Error?o.message:String(o)},n)});return}this.applyValidation(s,i,n)}cancelItem(e,t){this.assertItemMutable(t);const n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(Nn(n,{interruptId:e,status:"cancelled"})),n.status="staged",n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);const n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status="pending",t||this.publish()}maybeSubmit(){const e=this.items.some(i=>i.kind==="generic"),t=this.items.filter(i=>pe(i)&&!(e&&i.kind==="client-tool-execution"));if(t.length===0||t.some(i=>i.resolution===void 0||i.status!=="staged"))return;const n=this.requireHydration(),s=qc(t.map(i=>i.resolution).filter(i=>i!==void 0)),r=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:s.resolutions,canonicalResolutions:s.canonicalResolutions,fingerprint:s.fingerprint});this.submitBatch(r)}applyValidation(e,t,n){if(!("valid"in t)){e.status="error";const s=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=s,e.kind==="client-tool-execution"&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(r=>!(r.code==="item-validation-failed"&&r.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:"batch",code:"item-validation-failed",message:s.message,source:"client",retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:s.threadId,interruptedRunId:s.interruptedRunId,generation:s.generation})])),n||this.publish();return}e.resolution=B(Nn(e,{interruptId:e.descriptor.id,status:"resolved",payload:t.payload})),e.status="staged",e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind==="generic"){const n=jt(e.definition?.responseSchema??e.descriptor.responseSchema,t,"invalid-payload");if(e.definition===void 0)return n;const s=r=>"valid"in r?{valid:!0,payload:t}:r;return Pe(n)?Promise.resolve(n).then(s):s(n)}return e.kind==="client-tool-execution"?jt(e.tool?.outputSchema,t,"invalid-tool-output"):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!oe(t)||typeof t.approved!="boolean")return{code:"invalid-payload",message:"Tool approval resolutions require an approved boolean."};const n=t.approved,s=t.editedArgs;if(!n&&s!==void 0)return{code:"invalid-edited-args",message:"Rejected tool approvals cannot edit tool arguments."};if(n&&s!==void 0){const r=jt(e.tool?.inputSchema,s,"invalid-edited-args");return Pe(r)?Promise.resolve(r).then(i=>"valid"in i?this.validateApprovalPayload(e,t,i.payload):i):"valid"in r?this.validateApprovalPayload(e,t,r.payload):r}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){const s=t.approved===!0,r=this.approvalBranchSchema(e.tool,s),i=t.payload;if(r===void 0&&i!==void 0)return{code:"invalid-payload",message:"This approval branch does not accept a payload."};if(r!==void 0&&i===void 0)return{code:"invalid-payload",message:"This approval branch requires a payload."};const o=jt(r,i,"invalid-payload"),a=u=>"valid"in u?{valid:!0,payload:{approved:s,...n!==void 0?{editedArgs:n}:{},...r!==void 0?{payload:u.payload}:{}}}:u;return Pe(o)?Promise.resolve(o).then(a):a(o)}approvalBranchSchema(e,t){const n=e?.approvalSchema;return!oe(n)||!("approve"in n||"reject"in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind==="client-tool-execution"?"invalid-tool-output":"invalid-payload"}resolveBooleanBulk(e){const t=this.items.filter(n=>pe(n)&&n.kind!=="client-tool-execution");if(!t.every(n=>n.kind==="tool-approval"&&this.approvalBranchSchema(n.tool,e)===void 0)||t.length===0){this.addRootError("unsupported-bulk-operation","Boolean bulk resolution requires payloadless tool approvals.",!1);return}this.invalidateRetry();for(const n of t)n.validationGeneration++,n.resolution=B({interruptId:n.descriptor.id,status:"resolved",payload:{approved:e}}),n.status="staged",n.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){const t=this.items.map(i=>({status:i.status,...i.resolution!==void 0?{resolution:i.resolution}:{},...i.error!==void 0?{error:i.error}:{},validationGeneration:i.validationGeneration})),n={active:!0};this.activeTransaction=n;const s=this.buildSnapshot(n).filter(vh);let r;try{for(const i of s){const o=e(i);if(o!==void 0){r={code:Pe(o)?"async-resolver":"inactive-transaction",message:Pe(o)?"Interrupt transaction resolvers must be synchronous.":"Interrupt transaction resolvers must return literal undefined."};break}}r===void 0&&this.items.some(i=>pe(i)&&i.kind!=="client-tool-execution"&&(i.resolution===void 0||i.status!=="staged"))&&(r={code:"incomplete-batch",message:"Interrupt transaction did not resolve every item."})}catch(i){r={code:"item-validation-failed",message:i instanceof Error?i.message:String(i)}}finally{n.active=!1,this.activeTransaction=void 0}if(r){this.restoreCheckpoints(t),this.addRootError(r.code,r.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,n)=>{const s=e[n];s&&(t.status=s.status,t.resolution=s.resolution,t.error=s.error,t.validationGeneration=s.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active)throw new Error("Interrupt transaction is inactive.");if(this.activeTransaction&&e!==this.activeTransaction)throw new Error("Interrupt transaction is inactive.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}assertRootMutable(){if(this.activeTransaction)throw new Error("Interrupt transaction is already active.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){const t={submission:e};this.activeSubmissionOperation=t,this.resuming=!0,this.retrySubmission=void 0;for(const n of this.items)pe(n)&&(n.status="submitting");this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){const n=_h(e);if(n.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 s=n.filter(u=>Mh(u,t));s.length!==n.length&&this.addRootError("protocol","Interrupt submission errors did not match the active batch.",!1);let r=!1,i=!1;const o=[];for(const u of s)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=B(u))}else o.push(B(u));const a=Ah(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,n,s="client"){const r=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:"batch",code:e,message:t,source:s,retryable:n,interruptIds:Object.freeze(this.items.filter(pe).map(i=>i.descriptor.id)),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})]),this.publish()}findItem(e){const t=this.items.find(n=>n.descriptor.id===e);if(!t)throw new Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw new Error("InterruptManager is not hydrated.");return this.hydration}itemError(e,t,n,s){const r=this.requireHydration();return Object.freeze({scope:"item",interruptId:e,code:t,message:n,...s!==void 0?{path:Object.freeze([...s])}:{},source:"client",retryable:!1,threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})}};function Ph(e,...t){const n=e?.();if(ps(n))return n;for(const s of t)if(ps(s))return s}async function Lh(e,t){if(!t)throw new Zo;return await e.prepare(t),e.headers(t)}function Fh(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():Math.random().toString(36).slice(2)}var Gt;function hi(){return Gt!==void 0||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__=Fh()),Gt=globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__),Gt}var kh=0;function de(e){return e==null||e===""?"missing":`value-${encodeURIComponent(String(e))}`}function vs(e){const t=e.runtimeId??hi(),n=e.eventId&&e.eventId.length>0?e.eventId:[e.source,e.eventType,de(t),de(e.clientId),de(e.requestId),de(e.streamId),de(e.hookId),de(e.threadId),de(e.runId),de(e.messageId),de(e.toolCallId),de(e.sequence),e.timestamp,hi(),kh++].join(":");return{...e,runtimeId:t,eventId:n}}var Nh=class{#t=!0;#e;#n;#s;#i;#r;#o;#a;#f=0;#l=5;#c=!1;#d=!1;#u=null;#h=()=>{this.debugLog("Connected to event bus"),this.#r=!0,this.#c=!1,this.debugLog("Emitting queued events",this.#i),this.#i.forEach(e=>this.emitEventToBus(e)),this.#i=[],this.stopConnectLoop(),this.#n().removeEventListener("tanstack-connect-success",this.#h)};#p=()=>{if(this.#f<this.#l){this.#f++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#n().removeEventListener("tanstack-connect",this.#p),this.#d=!0,this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};#g=()=>{this.#c||(this.#c=!0,this.#n().addEventListener("tanstack-connect-success",this.#h),this.#p())};constructor({pluginId:e,debug:t=!1,enabled:n=!0,reconnectEveryMs:s=300}){this.#e=e,this.#t=n,this.#n=this.getGlobalTarget,this.#s=t,this.debugLog(" Initializing event subscription for plugin",this.#e),this.#i=[],this.#r=!1,this.#d=!1,this.#o=null,this.#a=s}startConnectLoop(){this.#o!==null||this.#r||(this.debugLog(`Starting connect loop (every ${this.#a}ms)`),this.#o=setInterval(this.#p,this.#a))}stopConnectLoop(){this.#c=!1,this.#o!==null&&(clearInterval(this.#o),this.#o=null,this.#i=[],this.debugLog("Stopped connect loop"))}debugLog(...e){this.#s&&console.log(`🌴 [tanstack-devtools:${this.#e}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;const e=typeof EventTarget<"u"?new EventTarget:void 0;return typeof e>"u"||typeof e.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog("Using new EventTarget as fallback"),e)}getPluginId(){return this.#e}dispatchCustomEventShim(e,t){try{const n=new Event(e,{detail:t});this.#n().dispatchEvent(n)}catch{this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(e,t){try{this.#n().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog("Emitting event to client bus",e),this.dispatchCustomEvent("tanstack-dispatch-event",e)}createEventPayload(e,t){return{type:`${this.#e}:${e}`,payload:t,pluginId:this.#e}}emit(e,t){if(!this.#t){this.debugLog("Event bus client is disabled, not emitting event",e,t);return}if(this.#u&&(this.debugLog("Emitting event to internal event target",e,t),this.#u.dispatchEvent(new CustomEvent(`${this.#e}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#d){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.#c&&(this.#g(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,n){const s=n?.withEventTarget??!1,r=`${this.#e}:${e}`;if(s&&(this.#u||(this.#u=new EventTarget),this.#u.addEventListener(r,o=>{t(o.detail)})),!this.#t)return this.debugLog("Event bus client is disabled, not registering event",r),()=>{};const i=o=>{this.debugLog("Received event from bus",o.detail),t(o.detail)};return this.#n().addEventListener(r,i),this.debugLog("Registered event to bus",r),()=>{s&&this.#u?.removeEventListener(r,i),this.#n().removeEventListener(r,i)}}onAll(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=n=>{const s=n.detail;e(s)};return this.#n().addEventListener("tanstack-devtools-global",t),()=>this.#n().removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=n=>{const s=n.detail;this.#e&&s.pluginId!==this.#e||e(s)};return this.#n().addEventListener("tanstack-devtools-global",t),()=>this.#n().removeEventListener("tanstack-devtools-global",t)}},Dh=class extends Nh{constructor(){super({pluginId:"tanstack-ai-devtools"})}},fi=Symbol.for("tanstack.ai.devtools.eventClient");function jh(){const e=globalThis,t=e[fi];if(t)return t;const n=new Dh;return e[fi]=n,n}var yt=jh();function Y(e,t){yt.emit(e,t)}var ia=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent("client:created",{initialMessageCount:e})}loadingChanged(e){this.emitEvent("client:loading:changed",{isLoading:e})}errorChanged(e){this.emitEvent("client:error:changed",{error:e})}textUpdated(e,t,n,s){this.emitEvent("text:chunk:content",{streamId:e,messageId:t,content:n,...s})}toolCallStateChanged(e,t,n,s,r,i,o){this.emitEvent("tools:call:updated",{streamId:e,messageId:t,toolCallId:n,toolName:s,state:r,arguments:i,...o})}thinkingUpdated(e,t,n,s,r){this.emitEvent("text:chunk:thinking",{streamId:e,messageId:t,content:n,delta:s,...r})}structuredOutputChanged(e,t,n,s,r){this.emitEvent(e,{streamId:t,messageId:n,...s,...r})}approvalRequested(e,t,n,s,r,i,o){this.emitEvent("tools:approval:requested",{streamId:e,messageId:t,toolCallId:n,toolName:s,input:r,approvalId:i,...o})}messageAppended(e,t,n){const s=e.parts.filter(r=>r.type==="text").map(r=>r.content).join(" ");this.emitEvent("text:message:created",{streamId:t,messageId:e.id,role:e.role,content:s,parts:e.parts,...n})}messageSent(e,t){const n=typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.content).join("");this.emitEvent("text:message:created",{messageId:e,role:"user",content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent("text:message:user",{messageId:e,role:"user",content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent("client:reloaded",{fromMessageIndex:e})}stopped(){this.emitEvent("client:stopped")}messagesCleared(){this.emitEvent("client:messages:cleared")}toolResultAdded(e,t,n,s,r){this.emitEvent("tools:result:added",{toolCallId:e,toolName:t,output:n,state:s,...r})}toolApprovalResponded(e,t,n,s){this.emitEvent("tools:approval:responded",{approvalId:e,toolCallId:t,approved:n,...s})}toolFixtureApplied(e){this.emitEvent("devtools:tool-fixture:applied",{...e})}},Gh=class extends ia{emitEvent(e,t){const n=Date.now(),s=e.startsWith("text:")||e.startsWith("tools:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",r=e.startsWith("client:")||e.startsWith("tools:")||e.startsWith("text:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",i=s?"user-visible":"client-state",o={hookId:this.clientId,...typeof t?.threadId=="string"?{threadId:t.threadId}:{},...typeof t?.runId=="string"?{runId:t.runId}:{},...typeof t?.streamId=="string"?{streamId:t.streamId}:{},...typeof t?.messageId=="string"?{messageId:t.messageId}:{},...typeof t?.toolCallId=="string"?{toolCallId:t.toolCallId}:{}};if(r){const a=vs({eventType:e,clientId:this.clientId,...o,source:"client",visibility:i,timestamp:n});yt.emit(e,{...t,...a})}else{const a=vs({eventType:e,source:"client",visibility:"client-state",timestamp:n});yt.emit(e,{...t,...a})}}},Uh=class extends ia{emitEvent(){}},$h=class{events;constructor(e){this.events=new Uh(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,s){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return""}observeChunk(e){}recordMemoryState(e){}recordCompactionEvent(e,t){}recordCompactionState(e){}recordSkillsState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Bh=e=>new $h(e);function pi(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}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 Hh(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var zh=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,s){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=s}writeState(){const e=[...this.lastMessages];if(e.length===0&&!this.lastResume){const s=this.generation;this.runOperation(()=>{if(s===this.generation)return this.adapter.removeItem(this.id)});return}const t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}readInitial(){try{const e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(pi).catch(()=>{});const t=pi(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;const t=this.messagesGeneration;e.then(n=>{!n||this.messagesGeneration!==t||(this.lastResume=n.resume??null,this.lastMessages=n.messages,this.applyMessages(n.messages),n.resume&&this.applyResume&&this.applyResume(n.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;const e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){const t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{const t=e();if(t instanceof Promise){this.queuePending=!0;const n=t.catch(()=>{});this.queue=n,n.finally(()=>{this.queue===n&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){const t=te(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const n=gi(e);if(n&&this.clearedToolCallIds.has(n))return!0;const s=Hh(e);if(s&&this.clearedMessageIds.has(s))return n&&this.clearedToolCallIds.add(n),!0;const r=mi(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=mi(e);t&&this.clearedMessageIds.add(t);const n=gi(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return te(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 vi(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function Si(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function Vh(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var qh=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=te(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const n=vi(e);if(n&&this.clearedToolCallIds.has(n))return!0;const s=Vh(e);if(s&&this.clearedMessageIds.has(s))return n&&this.clearedToolCallIds.add(n),!0;const r=Si(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=Si(e);t&&this.clearedMessageIds.add(t);const n=vi(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return te(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 Kh(e){const t=new Set;for(const n of e??[]){if(t.has(n.id))throw new Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function yi(e){const{connection:t,fetcher:n}=e;if(t&&n)throw new Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return gh(n);throw new Error("ChatClient: either `connection` or `fetcher` is required.")}function Ii(e){return"connect"in e}function Qh(e){if(e.type!=="RUN_FINISHED"||e.outcome?.type==="interrupt")return!1;const t=e;return t.finishReason!==void 0?t.finishReason==="tool_calls":$(e)?.finishReason==="tool_calls"}function Ri(e){const t={whenBusy:"queue",drain:"fifo",onOverflow:"reject"};if(!e)return t;if(typeof e=="string")return{...t,whenBusy:e};if(typeof e=="function")return{...t,strategy:e};const n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new Error("ChatClient: queue.maxSize must be a non-negative integer");return{whenBusy:e.whenBusy??"queue",drain:e.drain??"fifo",onOverflow:e.onOverflow??"reject",...n!==void 0?{maxSize:n}:{}}}function Wh(e){const t=e.at(-1)?.body,n=[];for(const i of e){if(typeof i.content!="string")break;n.push(i.content)}if(n.length===e.length)return{content:n.join(`
|
|
10
|
-
`),...t!==void 0?{body:t}:{}};const s=[];let r;for(const i of e){if(typeof i.content=="string"){s.push({type:"text",content:i.content});continue}typeof i.content.content=="string"?s.push({type:"text",content:i.content.content}):s.push(...i.content.content),r=Fo(r,i.content.metadata)}return{content:{content:s,...r!==void 0?{metadata:r}:{}},...t!==void 0?{body:t}:{}}}function Jh(e){if(!(e===null||typeof e!="object"||Array.isArray(e))&&!(!("approved"in e)||typeof e.approved!="boolean"))return e.approved}function Xh(e){const t=e;if(t===null||typeof t!="object"||!("resumeState"in t))return;const n=t.resumeState;if(!(n===null||typeof n!="object"||!("threadId"in n)||typeof n.threadId!="string"||n.threadId.length===0||!("runId"in n)||typeof n.runId!="string"||n.runId.length===0))return{threadId:n.threadId,runId:n.runId}}var Yh=2e3,Zh=new Set(["TEXT_MESSAGE_START","TEXT_MESSAGE_CONTENT","TOOL_CALL_START","MESSAGES_SNAPSHOT"]),ef=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new qh;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status="ready";connectionStatus="disconnected";abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;connectionDrainsOnSend=!1;errorReportedGeneration=null;streamGeneration=0;continuationGeneration=0;streamContinuationGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){Kh(e.interrupts),this.threadId=e.threadId||"",this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1}else if(e.persistence){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new zh(e.persistence,e.threadId,a=>this.processor.setMessages(a),a=>this.applyPersistedResume(a))}this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=Ri(e.queue);const n=yi(e);if(this.connectionDrainsOnSend=Ii(n),this.connection=ai(n),this.clientToolsRef={current:new Map},e.tools)for(const a of e.tools)this.clientToolsRef.current.set(a.name,a);this.devtoolsBridge=(e.devtoolsBridgeFactory??Bh)(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 Oh({...e.tools!==void 0?{tools:e.tools}:{},...e.interrupts!==void 0?{interrupts:e.interrupts}:{},submit:a=>this.submitInterruptBatch(a),onChange:a=>this.notifyResumeStateChange(a)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);const s=this.persistor?.readInitial(),r=s instanceof Promise?void 0:s,i=r?r.messages:e.initialMessages;let o=null;if(r?.resume){const a=r.resume;Array.isArray(a.pendingInterrupts)&&a.pendingInterrupts.length>0?this.applyResumeSnapshot(a):a.resumeState.runId&&(o=a.resumeState.runId)}if(!o&&e.initialResumeSnapshot){const a=e.initialResumeSnapshot;!(Array.isArray(a.pendingInterrupts)&&a.pendingInterrupts.length>0)&&a.resumeState.runId&&(o=a.resumeState.runId)}this.processor=new Jd({...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(s),this.rejoinRunId=o,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){const t=Xh(e);if(t===void 0){this.interruptManager.reset({source:"hydrate"});return}this.lastResume=t;const n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:"hydrate"});return}const s=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:s,interrupts:n},"hydrate")}applyPersistedResume(e){this.applyResumeSnapshot(e);const t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){const e=this.connection.hydrate;e&&(this.isLoading||this.abortController||this.disposed||(async()=>{let t;try{t=await e(this.threadId)}catch{return}this.disposed||!this.tailing||this.isLoading||this.abortController||(t.messages.length>0&&this.processor.setMessages(Po(t.messages)),t.interrupts&&t.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId))})())}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||(this.threadId=this.generateUniqueId("thread")),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!=="RUN_ERROR")return;const t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=te(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),te(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type==="RUN_STARTED"){const r=te(e)??e.runId;this.activeResumeThreadId="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=r,this.activeRunIds.add(r),this.clearedStreamTracker.onRunStarted(r),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:r});return}if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const n=te(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type==="RUN_ERROR"&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);const s=e.type==="RUN_FINISHED"&&Qh(e);t?.resolveProcessing!==!1&&!s&&this.resolveProcessing()}observeInterruptState(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR"||this.activeInterruptSubmission&&e.type==="RUN_ERROR")return;const t=te(e),n="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId;if(e.type==="RUN_FINISHED"&&e.outcome?.type==="interrupt"){const l=this.currentRunId??t??this.activeResumeRunId??"";this.lastResume={threadId:n??this.threadId,runId:l},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:l,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},"live");return}const s=e.type==="RUN_ERROR"&&!t,r=!!(t&&this.lastResume?.runId===t),i=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),a=this.isLoading&&e.type==="RUN_FINISHED"&&!t,u=!!(this.activeInterruptSubmission&&this.isLoading&&e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt");if(s||r||i||o||a||u){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange("live")}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e=="boolean"){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){const n=t??this.lastResume;return n?this.resumeInterruptsUnsafeForGeneration(e,n,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,n){return n!==this.continuationGeneration?Promise.resolve(!1):this.isLoading?new Promise((s,r)=>{this.queuePostStreamAction(async()=>{try{s(await this.resumeInterruptsUnsafeForGeneration(e,t,n))}catch(i){r(i)}})}):(this.pendingResumeThreadId=t.threadId,this.pendingResumeParentRunId=t.runId,this.pendingResumeItems=[...e],this.streamResponse())}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){const t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(const r of e.resolutions){const i=Jh(r.payload);if(i===void 0)continue;const o=r.interruptId;this.processor.addToolApprovalResponse(o,i)}const n=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},t).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(t!==this.continuationGeneration)return;const s=this.takeInterruptSubmissionFailure();if(s!==void 0)throw{errors:s.errors};if(!n)throw new Error("Interrupt continuation could not be started.");this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){const e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(const n of e){const s=n.metadata?.["tanstack:interruptBinding"];if(s===null||typeof s!="object"||!("generation"in s)||typeof s.generation!="number"||!Number.isInteger(s.generation)||s.generation<0||t!==void 0&&t!==s.generation)return 0;t=s.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){const t=this.getResumeState(),n=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}const t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){const t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??"useChat",outputKind:e?.outputKind??"chat",...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:n=>{this.processor.setMessages(n)},addToolResult:(n,s,r)=>{this.processor.addToolResult(n,s,r)},generateId:n=>this.generateUniqueId(n)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){const t=this.processor.getMessages();for(const n of t)if(n.parts.find(s=>s.type==="tool-call"&&s.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus("ready")}reportStreamError(e){const t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status==="submitted"||this.status==="streaming")&&this.setStatus("error"),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;const e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(t=>{t instanceof Error&&t.name!=="AbortError"&&(this.setConnectionStatus("error"),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(t)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!=="error"&&this.setConnectionStatus("disconnected")))})}async consumeSubscription(e){const t=this.connection.subscribe(e);for await(const n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}resumeInFlightRun(e){const t=this.connection.joinRun;if(!t)return;const n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus("streaming"),(async()=>{let s=!1,r=!1,i=!1;const o=setTimeout(()=>{r||n.abort()},Yh);try{for await(const a of t(e,n.signal)){if(n.signal.aborted)break;r||(r=!0,clearTimeout(o)),!s&&Zh.has(a.type)&&(s=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(a){const 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===n&&(this.abortController=null,this.setIsLoading(!1),this.status==="streaming"&&this.setStatus("ready"),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){const e=this.processor.getMessages(),t=e[e.length-1];t&&t.role==="assistant"&&this.processor.setMessages(e.slice(0,-1))}async processIncomingChunk(e,t){if(e=Wo(e),e.type==="RUN_ERROR"&&this.isActiveInterruptSubmissionFailure(e)){const n=$(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(n)?n:[]}}if(this.connectionStatus==="connecting"&&this.setConnectionStatus("connected"),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR")&&(te(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>"u"||!document.hidden)&&await new Promise(n=>setTimeout(n,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){const t=this.activeInterruptSubmission,n=$(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;const s=te(e);return s!==void 0&&s!==this.currentRunId||typeof e.threadId=="string"&&e.threadId!==t.threadId?!1:n.every(r=>r==null||typeof r!="object"||typeof r.threadId!="string"||typeof r.interruptedRunId!="string"||typeof r.generation!="number"?!1:r.threadId===t.threadId&&r.interruptedRunId===t.interruptedRunId&&r.generation===t.generation)}resolveJoinedRun(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=te(e);if(t===void 0)return;const n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),typeof e=="string"&&!e.trim())return;if(this.hasBlockingInterrupts())throw new Error("ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.");const s={...t,...n?.body};if(this.isSendBusy()){const{action:r,id:i}=this.decideWhenBusy(e,n);if(r==="drop")return;if(r==="queue"){this.enqueueMessage(e,s,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,s)}finally{this.sendInFlight=!1}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}hasBlockingInterrupts(){return this.activeInterruptSubmission!==void 0||this.hasPendingInterrupts()}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?"streaming":this.messageQueueDraining?"draining":"sendInFlight"}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{const n=this.normalizeMessageInput(e);this.pendingMessageBody=t;const s=this.processor.addUserMessage(n.content,n.id,n.metadata);return this.events.messageSent(s.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){const n=this.generateUniqueId("queued");if(t?.whenBusy)return{action:t.whenBusy,id:n};const{strategy:s,whenBusy:r}=this.queueConfig;if(s){const{action:i}=s({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:i,id:n}}return{action:r,id:n}}enqueueMessage(e,t,n){const{maxSize:s,onOverflow:r}=this.queueConfig;if(s!==void 0&&this.messageQueue.length>=s){if(r==="reject"||s===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId("queued"),content:e,createdAt:Date.now(),...t!==void 0?{body:t}:{}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e=="string"?{content:e.trim()}:{content:e.content,id:e.id,...e.metadata!==void 0?{metadata:e.metadata}:{}}}async append(e){if(this.mountDevtools(),this.hasBlockingInterrupts())throw new Error("ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.");const t=Td(e,Ne);if(t.role==="system")return;const n=t;this.events.messageAppended(n);const s=this.processor.getMessages();if(this.processor.setMessages([...s,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;const e=++this.streamGeneration;this.streamContinuationGeneration=this.continuationGeneration;const t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,s=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;const r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(r),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=r,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus("submitted"),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;const i=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,a=null,u=!1;try{const l=this.processor.getMessages(),c=new Map(this.clientToolsRef.current),h=this.context;if(await this.callbacksRef.current.onResponse(),i.aborted)return!1;const d={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId("stream"),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=c,this.activeContext=h,this.processor.prepareAssistantMessage(),this.ensureSubscription();const f=this.waitForProcessing();let p;if(this.byok){const m=Ph(this.byokProvider,d.provider);p=await Lh(this.byok,m)}const g={threadId:t??this.threadId,runId:r,...n!==null?{parentRunId:n}:{},clientTools:Array.from(c.values()).map(m=>({name:m.name,description:m.description,parameters:m.inputSchema?ls(m.inputSchema):{type:"object"}})),forwardedProps:{...d},...s?{resume:s}:{},...p?{headers:p}:{}};if(this.devtoolsBridge.beginRun(g.runId,g.threadId),a=g.runId,this.devtoolsBridge.emitRunLifecycle("run:created",g.runId,"created"),this.devtoolsBridge.emitRunLifecycle("run:started",g.runId,"started"),this.devtoolsBridge.emitSnapshot(),await this.connection.send(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 gs&&this.byok?.request(c.provider,"missing"),c instanceof si&&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 gs||c instanceof si||c instanceof Zo))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.status!=="ready"&&this.setStatus("ready"),this.messageQueueDraining||await this.drainQueue()):this.flushQueue())}return o}subscribe(e){const t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus("connecting"),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected")}async reload(){const e=this.processor.getMessages();if(e.length===0)return;const t=e.findLastIndex(n=>n.role==="user");t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){this.continuationGeneration++;const e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),this.lastResume=null,this.activeInterruptSubmission=void 0,this.interruptManager.reset(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){const e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.discardPendingSends(),this.persistor?.remove(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){const t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t,this.streamContinuationGeneration)}async addToolResultForClientTool(e,t,n,s){if(t&&e.state!=="output-error")try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(r){e={...e,output:null,state:"output-error",errorText:r.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||"output-available",s),n===this.continuationGeneration&&(this.processor.addToolResult(e.toolCallId,e.output,e.state==="output-error"?e.errorText||"Tool execution failed":void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state==="output-error"?{error:e.errorText||"Tool execution failed"}:e.output))){if(this.isLoading){this.queuePostStreamAction(()=>n===this.continuationGeneration?this.checkForContinuation():Promise.resolve());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&Ae(e.outputSchema)?Jc(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;const t=this.processor.getMessages();let n;for(const s of t){const r=s.parts.find(i=>i.type==="tool-call"&&i.approval?.id===e.id);if(r){n=r.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){const t=this.continuationGeneration;this.postStreamActions.push(async()=>{t===this.continuationGeneration&&await e()})}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.streamContinuationGeneration===this.continuationGeneration&&!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;const e=this.processor.getMessages().findLast(t=>t.role==="assistant");return!e||!e.parts.some(t=>t.type==="tool-call")?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain==="batch"){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.splice(0);this.emitQueueChange();const t=Wh(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){const t=this.messageQueue.findIndex(n=>n.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){const t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected");const n=yi({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=Ii(n),this.connection=ai(n),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),e.byok!==void 0&&(this.byok=e.byok),e.byokProvider!==void 0&&(this.byokProvider=e.byokProvider),"context"in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(const t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=Ri(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 Ci(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 bi(e){if(!Array.isArray(e))return;const t=[];for(const n of e)!n||typeof n!="object"||!("role"in n)||!("tokens"in n)||!("text"in n)||typeof n.role!="string"||typeof n.tokens!="number"||typeof n.text!="string"||t.push({role:n.role,tokens:n.tokens,text:n.text});return t}function tf(e){if(!e||typeof e!="object"||!("before"in e)||!("after"in e)||!("messagesBefore"in e)||!("messagesAfter"in e)||typeof e.before!="number"||typeof e.after!="number"||typeof e.messagesBefore!="number"||typeof e.messagesAfter!="number")return null;const t="reusedCheckpoint"in e&&e.reusedCheckpoint===!0,n="maxTokens"in e&&typeof e.maxTokens=="number"?e.maxTokens:void 0,s="strategyKey"in e&&typeof e.strategyKey=="string"?e.strategyKey:void 0,r="dropped"in e?bi(e.dropped):void 0,i="result"in e?bi(e.result):void 0;return{before:e.before,after:e.after,messagesBefore:e.messagesBefore,messagesAfter:e.messagesAfter,reusedCheckpoint:t,...n!==void 0?{maxTokens:n}:{},...s?{strategyKey:s}:{},...r?{dropped:r}:{},...i?{result:i}:{}}}var wi=Symbol.for("tanstack.ai.devtools.activeBridgeByHookId");function jn(){const e=globalThis,t=e[wi];if(t)return t;const n=new Map;return e[wi]=n,n}function nf(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 sf=class{options;unsubscribers=[];disposed=!1;superseded=!1;registered=!1;constructor(e){this.options=e}emitRegistered(){this.prepareForMountEmit()&&(this.registered=!0,Y("hook:registered",{...this.createEnvelope("hook:registered"),...this.createMetadataPayload(),lifecycle:"mounted"}))}emitUpdated(){this.prepareForEmit()&&Y("hook:updated",{...this.createEnvelope("hook:updated"),...this.createMetadataPayload(),lifecycle:"active"})}emitSnapshot(){this.prepareForEmit()&&Y("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?ls(t.inputSchema):{type:"object"},outputSchema:t.outputSchema?ls(t.outputSchema):void 0,needsApproval:t.needsApproval,metadata:t.metadata})):[];Y("tools:registered",{...this.createEnvelope("tools:registered"),...this.createMetadataPayload(),tools:e})}emitRunLifecycle(e,t,n,s={}){this.prepareForEmit()&&Y(e,{...this.createEnvelope(e,"client-state",{runId:t}),runId:t,status:n,...s.error?{error:s.error}:{}})}deactivate(){const e=jn();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(jn().get(this.options.hookId)!==this){this.deactivate();return}const e={...this.createEnvelope("hook:unregistered"),...this.createMetadataPayload(),reason:"disposed"};Y("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=jn(),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(yt.on("devtools:request-state",n=>{this.handleRequestState(n)})),this.options.applyToolFixture&&this.unsubscribers.push(yt.on("devtools:tool-fixture:apply",n=>{this.handleToolFixtureApply(n)})))}handleRequestState(e){if(this.disposed||this.superseded)return;const t=e.payload.targetHookId;t&&t!==this.options.hookId||(this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot(),this.onReplayState())}onReplayState(){}async handleToolFixtureApply(e){const t=e.payload;this.matchesFixtureTarget(t)&&await this.options.applyToolFixture?.(t)}matchesFixtureTarget(e){return!e.hookId&&!e.threadId?!1:e.hookId?e.hookId===this.options.hookId:!(e.threadId&&(!this.options.threadId||e.threadId!==this.options.threadId))}createEnvelope(e,t="client-state",n={}){return vs({eventType:e,source:"client",visibility:t,clientId:this.options.clientId,hookId:this.options.hookId,...this.options.threadId?{threadId:this.options.threadId}:{},...n.runId?{runId:n.runId}:{},timestamp:Date.now()})}createMetadataPayload(){return{hookId:this.options.hookId,hookName:this.options.metadata.hookName,...this.options.metadata.name?{displayName:this.options.metadata.name}:{},...this.options.metadata.outputKind?{outputKind:this.options.metadata.outputKind}:{},...this.options.metadata.framework?{framework:this.options.metadata.framework}:{}}}},rf=class extends sf{events;chatOptions;currentRunId=null;currentRunThreadId=null;currentStreamId=null;lastStreamId=null;lastRunEventContext;lastMemoryStateValue=null;lastCompactionEvents=[];lastSkillsStateValue=null;constructor(e){super(nf(e,{getSnapshot:e.getSnapshot,applyToolFixture:t=>this.applyFixture(t)})),this.chatOptions=e,this.events=new df(()=>e.clientId,this)}setCurrentStreamId(e){this.currentStreamId=e,e&&(this.lastStreamId=e)}recordStreamId(e){e&&(this.lastStreamId=e)}mountWithTools(e){this.events.clientCreated(e),this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot()}notifyToolsChanged(){this.emitToolsRegistered(),this.emitSnapshot()}getCurrentStreamId(){return this.currentStreamId}getLastStreamId(){return this.lastStreamId}resolveStreamId(){return this.currentStreamId??this.lastStreamId??this.chatOptions.generateId("stream")}beginRun(e,t){this.currentRunId=e,this.currentRunThreadId=t,this.lastRunEventContext={runId:e,threadId:t}}observeChunk(e){if(e.type==="RUN_STARTED"){this.beginRun(e.runId,e.threadId);return}if(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR"){const t=(e.type==="RUN_FINISHED",e.runId);if(!t||t===this.currentRunId){const n=this.getCurrentRunEventContext();n&&(this.lastRunEventContext=n),this.currentRunId=null,this.currentRunThreadId=null}}}recordMemoryState(e){this.lastMemoryStateValue=e,this.emitMemoryState(e)}recordSkillsState(e){this.lastSkillsStateValue=e,this.emitSkillsState(e)}emitMemoryState(e){if(!e||typeof e!="object")return;const t=e,n=t.scope,s=t.adapter;if(!n||typeof s!="string")return;const r=this.currentRunId?{runId:this.currentRunId}:{};Y("memory:retrieve:started",{...this.createEnvelope("memory:retrieve:started","client-state",r),scope:n,adapter:s,query:t.query??""}),t.recall&&Y("memory:retrieve:completed",{...this.createEnvelope("memory:retrieve:completed","client-state",r),scope:n,adapter:s,fragmentCount:t.recall.fragmentCount??0,hasTools:!!t.recall.hasTools,systemPromptChars:t.recall.systemPromptChars??0,durationMs:t.recall.durationMs??0}),t.snapshot&&Y("memory:snapshot",{...this.createEnvelope("memory:snapshot","client-state",r),scope:n,adapter:s,takenAt:t.snapshot.takenAt,data:t.snapshot.data,facts:t.snapshot.facts??[]})}recordCompactionEvent(e,t){this.lastCompactionEvents.push({eventType:e,value:t}),this.lastCompactionEvents.length>60&&this.lastCompactionEvents.splice(0,this.lastCompactionEvents.length-60),this.emitCompactionEvent(e,t)}recordCompactionState(e){this.recordCompactionEvent("compaction:state",e)}emitCompactionEvent(e,t){const n=this.currentRunId?{runId:this.currentRunId}:{};if(e==="compaction:started"){const s=Ci(t);Y("compaction:started",{...this.createEnvelope("compaction:started","client-state",n),...s});return}if(e==="compaction:ended"){const s=Ci(t);Y("compaction:ended",{...this.createEnvelope("compaction:ended","client-state",n),...s});return}if(e==="compaction:state"){const s=tf(t);if(!s)return;Y("compaction:state",{...this.createEnvelope("compaction:state","client-state",n),...s})}}emitSkillsState(e){if(!e||typeof e!="object")return;const t=e,n=Array.isArray(t.catalog)?t.catalog:[],s=Array.isArray(t.activated)?t.activated:[],r=this.currentRunId?{runId:this.currentRunId}:{};Y("skills:snapshot",{...this.createEnvelope("skills:snapshot","client-state",r),catalog:n,activated:s})}onReplayState(){this.lastMemoryStateValue!=null&&this.emitMemoryState(this.lastMemoryStateValue);for(const e of this.lastCompactionEvents)this.emitCompactionEvent(e.eventType,e.value);this.lastSkillsStateValue!=null&&this.emitSkillsState(this.lastSkillsStateValue)}getCurrentRunEventContext(){if(this.currentRunId)return{threadId:this.currentRunThreadId??this.chatOptions.threadId??"",runId:this.currentRunId}}getCurrentOrLastRunEventContext(){return this.getCurrentRunEventContext()??this.lastRunEventContext}findToolCallContext(e){const t={toolCallId:e},n=this.getCurrentRunEventContext();return n?{threadId:n.threadId,runId:n.runId,toolCallId:e}:this.chatOptions.threadId?{threadId:this.chatOptions.threadId,toolCallId:e}:t}async applyFixture(e){const t=this.chatOptions.getMessages(),n=e.threadId??this.chatOptions.threadId??"";if(e.execute){await this.executeFixture(e,t,n);return}const{message:s,toolCallId:r}=this.createReplayMessageFromFixture(e,t),i=s.id;this.events.messageAppended(s,void 0,{threadId:n,toolCallId:r,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,s]),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:n,...e.runId?{runId:e.runId}:{},toolName:e.toolName,input:e.input,output:e.output,messageId:i,toolCallId:r,...e.execute!==void 0?{execute:e.execute}:{},...e.message?{message:e.message}:{},...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}async executeFixture(e,t,n){const s=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i={id:r,role:"assistant",parts:[{type:"tool-call",id:s,name:e.toolName,arguments:Gn(e.input),input:e.input,state:"input-complete"}],createdAt:new Date};this.events.messageAppended(i,void 0,{threadId:n,toolCallId:s,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,i]),this.emitSnapshot();const o=this.findClientTool(e.toolName)?.execute;if(!o){console.warn(`[ai-devtools] tool fixture "${e.toolName}" requested execute=true but no client tool implementation is registered; replaying saved output instead.`),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:s,threadId:n,output:e.output,errorText:e.errorText});return}let a;try{a=await o(e.input)}catch(u){console.error(`[ai-devtools] tool fixture "${e.toolName}" execute threw`,u),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:s,threadId:n,output:null,errorText:u instanceof Error?`${u.name}: ${u.message}`:`Tool execution failed: ${String(u)}`});return}this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:s,threadId:n,output:a})}addToolResultForFixture(e){const t=e.errorText?"output-error":"output-available";this.events.toolResultAdded(e.toolCallId,e.fixture.toolName,e.output,t,{threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolCallId:e.toolCallId}),this.chatOptions.addToolResult(e.toolCallId,e.output,e.errorText),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolName:e.fixture.toolName,input:e.fixture.input,output:e.output,execute:!0,messageId:e.messageId,toolCallId:e.toolCallId,...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}createReplayMessageFromFixture(e,t){const n=this.cloneFixtureSourceMessage(e,t);if(n)return n;const s=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i=e.errorText?"error":"complete";return{toolCallId:s,message:{id:r,role:"assistant",parts:[{type:"tool-call",id:s,name:e.toolName,arguments:Gn(e.input),input:e.input,state:"input-complete",output:e.output},{type:"tool-result",toolCallId:s,content:Gn(e.output),state:i,...e.errorText?{error:e.errorText}:{}}],createdAt:new Date}}}cloneFixtureSourceMessage(e,t){const n=e.message;if(!n||!Array.isArray(n.parts))return;const s=this.createFixtureToolCallIdMap(n.parts,t),r=n.parts.map(a=>af(a,s)).filter(a=>!!a),i=e.toolCallId?s.get(e.toolCallId):void 0;if(uf(r,{...i?{mappedToolCallId:i}:{},output:e.output}),r.length===0)return;const o=(e.toolCallId?s.get(e.toolCallId):void 0)??lf(r);if(o)return{toolCallId:o,message:{id:this.resolveFixtureMessageId(n.id,t),role:n.role,parts:r,createdAt:new Date}}}createFixtureToolCallIdMap(e,t){const n=new Map;for(const s of e)!oa(s)||s.type!=="tool-call"||typeof s.id=="string"&&n.set(s.id,this.resolveFixtureToolCallId(s.id,t));return n}resolveFixtureMessageId(e,t){return e&&!t.some(n=>n.id===e)?e:this.chatOptions.generateId("fixture-msg")}resolveFixtureToolCallId(e,t){return e&&!cf(t,e)?e:this.chatOptions.generateId("fixture-tool-call")}findClientTool(e){const t=this.chatOptions.getTools?.();if(t){for(const n of t)if(n.name===e)return n}}};function oa(e){return typeof e=="object"&&e!==null}function Gn(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 of(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 af(e,t){if(!oa(e)||typeof e.type!="string")return;const n={...e};return e.type==="tool-call"&&typeof e.id=="string"&&(n.id=t.get(e.id)??e.id),e.type==="tool-result"&&typeof e.toolCallId=="string"&&(n.toolCallId=t.get(e.toolCallId)??e.toolCallId),n}function lf(e){const t=e.find(n=>n.type==="tool-call");return t?.type==="tool-call"?t.id:void 0}function uf(e,t){for(const n of e){if(n.type!=="tool-result")continue;const s=e.find(r=>r.type==="tool-call"&&r.id===n.toolCallId&&r.output===void 0);s&&(s.output=Array.isArray(n.content)?n.content:of(n.content))}if(t.mappedToolCallId&&t.output!==void 0){const n=e.find(s=>s.type==="tool-call"&&s.id===t.mappedToolCallId&&s.output===void 0);n&&(n.output=t.output)}}function cf(e,t){return e.some(n=>n.parts.some(s=>s.type==="tool-call"?s.id===t:s.type==="tool-result"?s.toolCallId===t:!1))}var df=class extends Gh{getClientId;helper;constructor(e,t){super(e()),this.getClientId=e,this.helper=t}emitEvent(e,t){this.clientId=this.getClientId(),super.emitEvent(e,t)}afterEmit(e){e&&this.helper.recordStreamId(e),this.helper.emitSnapshot()}textUpdated(e,t,n,s){super.textUpdated(e,t,n,s??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}thinkingUpdated(e,t,n,s,r){super.thinkingUpdated(e,t,n,s,r??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}messageAppended(e,t,n){super.messageAppended(e,t,n??this.helper.getCurrentRunEventContext()),this.afterEmit(t)}toolCallStateChanged(e,t,n,s,r,i,o){super.toolCallStateChanged(e,t,n,s,r,i,o??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}structuredOutputChanged(e,t,n,s,r){super.structuredOutputChanged(e,t,n,s,r??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(t)}approvalRequested(e,t,n,s,r,i,o){super.approvalRequested(e,t,n,s,r,i,o??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(e)}toolResultAdded(e,t,n,s,r){super.toolResultAdded(e,t,n,s,r??this.helper.getCurrentRunEventContext()),this.afterEmit()}toolApprovalResponded(e,t,n,s){super.toolApprovalResponded(e,t,n,s??this.helper.getCurrentRunEventContext()),this.afterEmit()}clientCreated(e){super.clientCreated(e),this.afterEmit()}loadingChanged(e){super.loadingChanged(e),this.afterEmit()}errorChanged(e){super.errorChanged(e),this.afterEmit()}reloaded(e){super.reloaded(e),this.afterEmit()}stopped(){super.stopped(),this.afterEmit()}messagesCleared(){super.messagesCleared(),this.afterEmit()}messageSent(e,t){super.messageSent(e,t),this.afterEmit()}toolFixtureApplied(e){super.toolFixtureApplied(e),this.afterEmit()}};function hf(e){return new rf(e)}var Ei=Object.freeze([]),ff=Object.freeze([]);function Bf(e){const t=(0,I.useId)(),n=e.threadId??t,[s,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,m]=(0,I.useState)(!1),[v,S]=(0,I.useState)([]),[C,w]=(0,I.useState)(null),[b,R]=(0,I.useState)(()=>({interrupts:Ei,pendingInterrupts:Ei,interruptErrors:ff,resuming:!1})),y=(0,I.useRef)(e.initialMessages||[]),T=(0,I.useRef)(!0),_=(0,I.useRef)(!1),E=(0,I.useRef)(null),x=(0,I.useRef)(null),N=(0,I.useRef)(null);y.current=s;const k=(0,I.useRef)(e);k.current=e;const j=(0,I.useCallback)(D=>{D&&(w(D.getCurrentRunId()),R(D.getInterruptState()))},[]),{client:A,initialization:ae}=(0,I.useMemo)(()=>{const D=e.initialMessages||[];T.current=!1;const O=k.current,le=O.connection?{connection:O.connection}:{fetcher:O.fetcher},J={current:void 0},Ie=()=>{const M=J.current;if(!(!M||E.current!==M))return M},tt={ready:!1,callbacks:[]},z=M=>{if(!tt.ready){tt.callbacks.push(M);return}const U=J.current;!U||E.current!==U||M()},nt=new ef({devtoolsBridgeFactory:hf,...le,initialMessages:D,...typeof O.threadId=="string"&&O.persistence?{persistence:O.persistence,threadId:O.threadId}:{...O.threadId!==void 0&&{threadId:O.threadId}},...O.body!==void 0&&{body:O.body},...O.forwardedProps!==void 0&&{forwardedProps:O.forwardedProps},...O.byok!==void 0&&{byok:O.byok},byokProvider:()=>k.current.byokProvider?.(),...O.initialResumeSnapshot!==void 0&&{initialResumeSnapshot:O.initialResumeSnapshot},...O.context!==void 0&&{context:O.context},devtools:{...O.devtools,framework:"react",hookName:"useChat",outputKind:O.outputSchema?"structured":"chat"},onResponse:M=>{if(Ie())return k.current.onResponse?.(M)},onChunk:M=>{z(()=>{k.current.onChunk?.(M)})},onFinish:M=>{z(()=>{k.current.onFinish?.(M)})},onError:M=>{z(()=>{k.current.onError?.(M)})},...O.tools!==void 0&&{tools:O.tools},...O.interrupts!==void 0&&{interrupts:O.interrupts},onCustomEvent:(M,U,ue)=>{z(()=>{k.current.onCustomEvent?.(M,U,ue)})},...e.streamProcessor!==void 0&&{streamProcessor:e.streamProcessor},onMessagesChange:M=>{z(()=>{r(M)})},onLoadingChange:M=>{z(()=>{const U=Ie();U&&(o(M),j(U))})},onErrorChange:M=>{z(()=>{u(M)})},onStatusChange:M=>{z(()=>{c(M)})},onSubscriptionChange:M=>{z(()=>{d(M)})},onConnectionStatusChange:M=>{z(()=>{p(M)})},onSessionGeneratingChange:M=>{z(()=>{m(M)})},...k.current.queue!==void 0&&{queue:k.current.queue},onQueueChange:M=>{z(()=>{S(M)})},onRunIdChange:M=>{z(()=>{w(M)})},onResumeStateChange:(M,U)=>{z(()=>{R(ue=>({...ue,interrupts:U,pendingInterrupts:U}))})},onInterruptStateChange:(M,U)=>{z(()=>{R(M),k.current.onInterruptStateChange?.(M,U)})}});return J.current=nt,{client:nt,initialization:tt}},[n,j]);(0,I.useEffect)(()=>{E.current=A;try{for(;ae.callbacks.length>0;){if(E.current!==A){ae.callbacks.length=0;break}ae.callbacks.shift()?.()}}finally{ae.ready=!0}},[A,ae]),(0,I.useEffect)(()=>{const D=A.getMessages();D!==y.current&&r(D)},[A]),(0,I.useEffect)(()=>{A.updateOptions({body:e.body})},[A,e.body]),(0,I.useEffect)(()=>{e.forwardedProps!==void 0&&A.updateOptions({forwardedProps:e.forwardedProps})},[A,e.forwardedProps]),(0,I.useEffect)(()=>{e.tools!==void 0&&A.updateOptions({tools:e.tools})},[A,e.tools]),(0,I.useEffect)(()=>{A.updateOptions({context:e.context})},[A,e.context]),(0,I.useEffect)(()=>{e.queue!==void 0&&A.updateOptions({queue:e.queue})},[A,e.queue]),(0,I.useEffect)(()=>{e.live?(A.subscribe(),_.current=!0):_.current&&(A.unsubscribe(),_.current=!1)},[A,e.live]),(0,I.useEffect)(()=>(A.attach(),()=>{A.detach()}),[A]),(0,I.useEffect)(()=>(N.current?.client===A&&(clearTimeout(N.current.timeout),N.current=null),x.current&&(clearTimeout(x.current),x.current=null),A.mountDevtools(),j(A),()=>{x.current=setTimeout(()=>{E.current===A&&(E.current=null),x.current=null},0);const D={client:A,timeout:setTimeout(()=>{k.current.live?A.unsubscribe():A.stop(),A.dispose(),N.current===D&&(N.current=null)},0)};N.current=D}),[A,j]);const Hs=(0,I.useCallback)(async(D,O)=>{try{await A.sendMessage(D,void 0,O)}finally{j(A)}},[A,j]),zs=(0,I.useCallback)(D=>{A.cancelQueued(D)},[A,j]),Vs=(0,I.useCallback)(async D=>{try{await A.append(D)}finally{j(A)}},[A,j]),qs=(0,I.useCallback)(async()=>{try{await A.reload()}finally{j(A)}},[A,j]),Rt=(0,I.useCallback)(()=>{A.stop()},[A]),Ct=(0,I.useCallback)(()=>{A.clear(),j(A)},[A,j]),fn=(0,I.useCallback)(D=>{A.setMessagesManually(D)},[A]),pn=(0,I.useCallback)(async D=>{await A.addToolResult(D)},[A]),bt=(0,I.useCallback)(async D=>{await A.addToolApprovalResponse(D),j(A)},[A,j]),Me=(0,I.useCallback)(async(D,O)=>{const le=await A.resumeInterrupts(D,O??void 0);return j(A),le},[A,j]),gn=(0,I.useCallback)(D=>{A.resolveInterrupts(D)},[A]),mn=(0,I.useCallback)(()=>{A.cancelInterrupts()},[A]),Ze=(0,I.useCallback)(()=>{A.retryInterrupts()},[A]),et=(0,I.useCallback)((D,O)=>A.resumeInterruptsUnsafe(D,O),[A]),re=A.getMessages(),W=(0,I.useMemo)(()=>{let D=-1;for(let O=re.length-1;O>=0;O--)if(re[O]?.role==="user"){D=O;break}if(D===-1)return null;for(let O=re.length-1;O>D;O--){const le=re[O];if(le?.role!=="assistant")continue;const J=le.parts.find(Ie=>Ie.type==="structured-output");if(J)return J}return null},[re]),wt=(0,I.useMemo)(()=>W?W.partial??W.data??{}:{},[W]),Et=(0,I.useMemo)(()=>!W||W.status!=="complete"?null:W.data,[W]);return{messages:re,sendMessage:Hs,append:Vs,reload:qs,stop:Rt,isLoading:i,error:a,status:l,isSubscribed:h,connectionStatus:f,sessionGenerating:g,setMessages:fn,clear:Ct,addToolResult:pn,addToolApprovalResponse:bt,queue:v,cancelQueued:zs,runId:C,interrupts:b.interrupts,pendingInterrupts:b.pendingInterrupts,interruptErrors:b.interruptErrors,resuming:b.resuming,resolveInterrupts:gn,cancelInterrupts:mn,retryInterrupts:Ze,resumeInterruptsUnsafe:et,resumeInterrupts:Me,partial:wt,final:Et}}var Hf=new Uint8Array(128).fill(128);export{ji as C,wf as S,Cf as T,Fs as _,Gf as a,_f as b,kf as c,Mu as d,Pf as f,Mf as g,vo as h,jf as i,Ff as l,xf as m,$f as n,Nf as o,Of as p,Uf as r,Df as s,Bf as t,Lf as u,po as v,bf as w,Tf as x,Af as y};
|
|
10
|
+
color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(r),i=!1,r}return o.updateDeps=a=>{s=a},o}function Ti(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var ff=(e,t)=>Math.abs(e-t)<1.01,pf=(e,t,n)=>{let s;return function(...r){e.clearTimeout(s),s=e.setTimeout(()=>t.apply(this,r),n)}},_i=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},gf=e=>e,mf=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),s=[];for(let r=t;r<=n;r++)s.push(r);return s},vf=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;const r=o=>{const{width:a,height:u}=o;t({width:Math.round(a),height:Math.round(u)})};if(r(_i(n)),!s.ResizeObserver)return()=>{};const i=new s.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(_i(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},Ai={passive:!0},Mi=typeof window>"u"?!0:"onscrollend"in window,Sf=(e,t)=>{const n=e.scrollElement;if(!n)return;const s=e.targetWindow;if(!s)return;let r=0;const i=e.options.useScrollendEvent&&Mi?()=>{}:pf(s,()=>{t(r,!1)},e.options.isScrollingResetDelay),o=c=>()=>{const{horizontal:h,isRtl:d}=e.options;r=h?n.scrollLeft*(d&&-1||1):n.scrollTop,i(),t(r,c)},a=o(!0),u=o(!1);n.addEventListener("scroll",a,Ai);const l=e.options.useScrollendEvent&&Mi;return l&&n.addEventListener("scrollend",u,Ai),()=>{n.removeEventListener("scroll",a),l&&n.removeEventListener("scrollend",u)}},yf=(e,t,n)=>{if(t?.borderBoxSize){const s=t.borderBoxSize[0];if(s)return Math.round(s[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},If=(e,{adjustments:t=0,behavior:n},s)=>{var r,i;const o=e+t;(i=(r=s.scrollElement)==null?void 0:r.scrollTo)==null||i.call(r,{[s.options.horizontal?"left":"top"]:o,behavior:n})},Rf=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,n,s;return((s=(n=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:n.now)==null?void 0:s.call(n))??Date.now()},this.observer=(()=>{let t=null;const n=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(s=>{s.forEach(r=>{const i=()=>{const o=r.target,a=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(a)&&this.resizeItem(a,this.options.measureElement(o,r,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var s;(s=n())==null||s.disconnect(),t=null},observe:s=>{var r;return(r=n())==null?void 0:r.observe(s,{box:"border-box"})},unobserve:s=>{var r;return(r=n())==null?void 0:r.unobserve(s)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([n,s])=>{typeof s>"u"&&delete t[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:gf,rangeExtractor:mf,onChange:()=>{},measureElement:yf,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var n,s;(s=(n=this.options).onChange)==null||s.call(n,this,t)},this.maybeNotify=qe(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,r)=>{this.scrollAdjustments=0,this.scrollDirection=r?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=r,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,n)=>{const s=new Map,r=new Map;for(let i=n-1;i>=0;i--){const o=t[i];if(s.has(o.lane))continue;const a=r.get(o.lane);if(a==null||o.end>a.end?r.set(o.lane,o):o.end<a.end&&s.set(o.lane,!0),s.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((i,o)=>i.end===o.end?i.index-o.index:i.end-o.end)[0]:void 0},this.getMeasurementOptions=qe(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,n,s,r,i,o,a)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:n,scrollMargin:s,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a}),{key:!1}),this.getMeasurements=qe(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:n,scrollMargin:s,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,m;const v=a==="estimate"||u.has(f);if(p!==void 0&&this.options.lanes>1){g=p;const b=h[g],R=b!==void 0?c[b]:void 0;m=R?R.end+this.options.gap:n+s}else{const b=this.options.lanes===1?c[d-1]:this.getFurthestMeasurement(c,d);m=b?b.end+this.options.gap:n+s,g=b?b.lane:d%this.options.lanes,this.options.lanes>1&&v&&this.laneAssignments.set(d,g)}const S=u.get(f),C=typeof S=="number"?S:this.options.estimateSize(d),w=m+C;c[d]={index:d,start:m,size:C,end:w,key:f,lane:g},h[g]=d}return this.measurementsCache=c,c},{key:!1,debug:()=>this.options.debug}),this.calculateRange=qe(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,n,s,r)=>this.range=t.length>0&&n>0?Cf({measurements:t,outerSize:n,scrollOffset:s,lanes:r}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=qe(()=>{let t=null,n=null;const s=this.calculateRange();return s&&(t=s.startIndex,n=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,n]},(t,n,s,r,i)=>r===null||i===null?[]:t({startIndex:r,endIndex:i,overscan:n,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const n=this.options.indexAttribute,s=t.getAttribute(n);return s?parseInt(s,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(s!==void 0&&this.range){const r=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,s-r),o=Math.min(this.options.count-1,s+r);return t>=i&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((i,o)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(o))});return}const n=this.indexFromElement(t),s=this.options.getItemKey(n),r=this.elementsCache.get(s);r!==t&&(r&&this.observer.unobserve(r),this.observer.observe(t),this.elementsCache.set(s,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,n)=>{var s;const r=this.measurementsCache[t];if(!r)return;const i=n-(this.itemSizeCache.get(r.key)??r.size);i!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,i,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,n)),this.notify(!1))},this.getVirtualItems=qe(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,n)=>{const s=[];for(let r=0,i=t.length;r<i;r++){const o=n[t[r]];s.push(o)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const n=this.getMeasurements();if(n.length!==0)return Ti(n[da(0,n.length-1,s=>Ti(n[s]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,n,s=0)=>{if(!this.scrollElement)return 0;const r=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=t>=i+r?"end":"start"),n==="center"?t+=(s-r)/2:n==="end"&&(t-=r);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,n="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const s=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[t];if(!i)return;if(n==="auto")if(i.end>=r+s-this.options.scrollPaddingEnd)n="end";else if(i.start<=r+this.options.scrollPaddingStart)n="start";else return[r,n];if(n==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),n];const o=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,n,i.size),n]},this.scrollToOffset=(t,{align:n="start",behavior:s="auto"}={})=>{const r=this.getOffsetForAlignment(t,n),i=this.now();this.scrollState={index:null,align:n,behavior:s,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:n="auto",behavior:s="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const r=this.getOffsetForIndex(t,n);if(!r)return;const[i,o]=r,a=this.now();this.scrollState={index:t,align:o,behavior:s,startedAt:a,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:n="auto"}={})=>{const s=this.getScrollOffset()+t,r=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:r,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const n=this.getMeasurements();let s;if(n.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((t=n[n.length-1])==null?void 0:t.end)??0;else{const r=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&r.some(o=>o===null);){const o=n[i];r[o.lane]===null&&(r[o.lane]=o.end),i--}s=Math.max(...r.filter(o=>o!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:n,behavior:s})=>{this.options.scrollToFn(t,{behavior:s,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const e=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,t=e?e[0]:this.scrollState.lastTargetOffset,n=1,s=t!==this.scrollState.lastTargetOffset;if(!s&&ff(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=n){this.scrollState=null;return}}else this.scrollState.stableFrames=0,s&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior="auto",this._scrollToOffset(t,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}},da=(e,t,n,s)=>{for(;e<=t;){const r=(e+t)/2|0,i=n(r);if(i<s)e=r+1;else if(i>s)t=r-1;else return r}return e>0?e-1:0};function Cf({measurements:e,outerSize:t,scrollOffset:n,lanes:s}){const r=e.length-1,i=u=>e[u].start;if(e.length<=s)return{startIndex:0,endIndex:r};let o=da(0,r,i,n),a=o;if(s===1)for(;a<r&&e[a].end<n+t;)a++;else if(s>1){const u=Array(s).fill(0);for(;a<r&&u.some(c=>c<n+t);){const c=e[a];u[c.lane]=c.end,a++}const l=Array(s).fill(n+t);for(;o>=0&&l.some(c=>c>=n);){const c=e[o];l[c.lane]=c.start,o--}o=Math.max(0,o-o%s),a=Math.min(r,a+(s-1-a%s))}return{startIndex:o,endIndex:a}}var xi=typeof document<"u"?I.useLayoutEffect:I.useEffect;function bf({useFlushSync:e=!0,...t}){const n=I.useReducer(()=>({}),{})[1],s={...t,onChange:(i,o)=>{var a;e&&o?(0,hf.flushSync)(n):n(),(a=t.onChange)==null||a.call(t,i,o)}},[r]=I.useState(()=>new Rf(s));return r.setOptions(s),xi(()=>r._didMount(),[]),xi(()=>r._willUpdate()),r}function tp(e){return bf({observeElementRect:vf,observeElementOffset:Sf,scrollToFn:If,...e})}export{Df as C,kf as D,Hi as E,Pf as O,jf as S,Lf as T,$f as _,Yf as a,js as b,Kf as c,Vf as d,zf as f,Uf as g,Bf as h,Xf as i,qf as l,Lu as m,Zf as n,Wf as o,Hf as p,ep as r,Qf as s,tp as t,Uu as u,Co as v,Nf as w,yo as x,Gf as y};
|