db-studio 1.10.0 → 1.11.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 +6 -6
- package/dist/index.js.map +1 -1
- package/dist/web-dist/assets/{_pathlessLayout-eo6iLvBo.js → _pathlessLayout-CJRtdlfu.js} +73 -73
- package/dist/web-dist/assets/_pathlessLayout-CJRtdlfu.js.map +1 -0
- package/dist/web-dist/assets/_pathlessLayout-ciCuJ1PR.js +1 -0
- package/dist/web-dist/assets/{_pathlessLayout-CEv6uosT.js.map → _pathlessLayout-ciCuJ1PR.js.map} +1 -1
- package/dist/web-dist/assets/_queryId-6swfGplM.js +1 -0
- package/dist/web-dist/assets/{_queryId-Bq64AuuI.js.map → _queryId-6swfGplM.js.map} +1 -1
- package/dist/web-dist/assets/{_table-Bt9of1on.js → _table-DHk3bHnN.js} +1 -1
- package/dist/web-dist/assets/{_table-Bt9of1on.js.map → _table-DHk3bHnN.js.map} +1 -1
- package/dist/web-dist/assets/_table-dUsH_2LP.js +1 -0
- package/dist/web-dist/assets/{_table-CQhKMAcZ.js.map → _table-dUsH_2LP.js.map} +1 -1
- package/dist/web-dist/assets/{browser-CFsrLhq1.js → browser-CKmBpcoz.js} +1 -1
- package/dist/web-dist/assets/{browser-CFsrLhq1.js.map → browser-CKmBpcoz.js.map} +1 -1
- package/dist/web-dist/assets/code-editor-C9H5SO98.js +9 -0
- package/dist/web-dist/assets/code-editor-C9H5SO98.js.map +1 -0
- package/dist/web-dist/assets/database.store-BvoUSH8Y.js +1 -0
- package/dist/web-dist/assets/database.store-BvoUSH8Y.js.map +1 -0
- package/dist/web-dist/assets/{dist-B90HBock.js → dist-C-7rnx4R.js} +1 -1
- package/dist/web-dist/assets/{dist-B90HBock.js.map → dist-C-7rnx4R.js.map} +1 -1
- package/dist/web-dist/assets/highlighted-body-OFNGDK62-qZDgwznf.js +1 -0
- package/dist/web-dist/assets/{highlighted-body-OFNGDK62-BGFI1Y6G.js.map → highlighted-body-OFNGDK62-qZDgwznf.js.map} +1 -1
- package/dist/web-dist/assets/icons-0UA1AvNu.js +1 -0
- package/dist/web-dist/assets/icons-0UA1AvNu.js.map +1 -0
- package/dist/web-dist/assets/index-BSNZ1oRs.js +35 -0
- package/dist/web-dist/assets/index-BSNZ1oRs.js.map +1 -0
- package/dist/web-dist/assets/index-BWKgNfEb.css +2 -0
- package/dist/web-dist/assets/{indexes-BKOZUa9Z.js → indexes-D-oUHra7.js} +1 -1
- package/dist/web-dist/assets/{indexes-BKOZUa9Z.js.map → indexes-D-oUHra7.js.map} +1 -1
- package/dist/web-dist/assets/{logs-DHha3vDy.js → logs-wkipM6zd.js} +1 -1
- package/dist/web-dist/assets/{logs-DHha3vDy.js.map → logs-wkipM6zd.js.map} +1 -1
- package/dist/web-dist/assets/mermaid-GHXKKRXX-BZ1Tdv8E.js +1 -0
- package/dist/web-dist/assets/middleware-CCyr6cvp.js +1 -0
- package/dist/web-dist/assets/middleware-CCyr6cvp.js.map +1 -0
- package/dist/web-dist/assets/popover-WwEzK7ho.js +1 -0
- package/dist/web-dist/assets/popover-WwEzK7ho.js.map +1 -0
- package/dist/web-dist/assets/query-runner-B-lngX3P.js +9 -0
- package/dist/web-dist/assets/query-runner-B-lngX3P.js.map +1 -0
- package/dist/web-dist/assets/{radix-ui-BUv2Nuc1.js → radix-ui-6dcJ5m4U.js} +1 -1
- package/dist/web-dist/assets/{radix-ui-BUv2Nuc1.js.map → radix-ui-6dcJ5m4U.js.map} +1 -1
- package/dist/web-dist/assets/react-B_x-GW6a.js +1 -0
- package/dist/web-dist/assets/react-B_x-GW6a.js.map +1 -0
- package/dist/web-dist/assets/{react-dom-0lXVP1OR.js → react-dom-CsRkF-uK.js} +1 -1
- package/dist/web-dist/assets/{react-dom-0lXVP1OR.js.map → react-dom-CsRkF-uK.js.map} +1 -1
- package/dist/web-dist/assets/{redis-value-CJoRCZun.js → redis-value-Dq29EMpv.js} +1 -1
- package/dist/web-dist/assets/{redis-value-CJoRCZun.js.map → redis-value-Dq29EMpv.js.map} +1 -1
- package/dist/web-dist/assets/runner-CL63BPMX.js +1 -0
- package/dist/web-dist/assets/{runner-CZKDzRoU.js.map → runner-CL63BPMX.js.map} +1 -1
- package/dist/web-dist/assets/schema-BNzZaUjg.js +64 -0
- package/dist/web-dist/assets/schema-BNzZaUjg.js.map +1 -0
- package/dist/web-dist/assets/{schema-0sozVL-z.js → schema-CIr5j9z3.js} +1 -1
- package/dist/web-dist/assets/{schema-0sozVL-z.js.map → schema-CIr5j9z3.js.map} +1 -1
- package/dist/web-dist/assets/{table-CPQhgD-a.js → table-BoQghHv7.js} +1 -1
- package/dist/web-dist/assets/{table-CPQhgD-a.js.map → table-BoQghHv7.js.map} +1 -1
- package/dist/web-dist/assets/tanstack-C-qfmRNM.js +10 -0
- package/dist/web-dist/assets/tanstack-C-qfmRNM.js.map +1 -0
- package/dist/web-dist/assets/toggle-group-CxRlYNqR.js +1 -0
- package/dist/web-dist/assets/toggle-group-CxRlYNqR.js.map +1 -0
- package/dist/web-dist/assets/{tooltip-DinwklI8.js → tooltip-1-bWFncb.js} +2 -2
- package/dist/web-dist/assets/{tooltip-DinwklI8.js.map → tooltip-1-bWFncb.js.map} +1 -1
- package/dist/web-dist/assets/{visualizer-DTPn0ywW.js → visualizer-qFaRAy7F.js} +1 -1
- package/dist/web-dist/assets/{visualizer-DTPn0ywW.js.map → visualizer-qFaRAy7F.js.map} +1 -1
- package/dist/web-dist/index.html +13 -11
- package/package.json +1 -1
- package/dist/web-dist/assets/_pathlessLayout-CEv6uosT.js +0 -1
- package/dist/web-dist/assets/_pathlessLayout-eo6iLvBo.js.map +0 -1
- package/dist/web-dist/assets/_queryId-Bq64AuuI.js +0 -1
- package/dist/web-dist/assets/_table-CQhKMAcZ.js +0 -1
- package/dist/web-dist/assets/code-editor-DQ86aZkm.js +0 -9
- package/dist/web-dist/assets/code-editor-DQ86aZkm.js.map +0 -1
- package/dist/web-dist/assets/database.store-KDHkiedw.js +0 -1
- package/dist/web-dist/assets/database.store-KDHkiedw.js.map +0 -1
- package/dist/web-dist/assets/highlighted-body-OFNGDK62-BGFI1Y6G.js +0 -1
- package/dist/web-dist/assets/icons-Bm7rSZLJ.js +0 -1
- package/dist/web-dist/assets/icons-Bm7rSZLJ.js.map +0 -1
- package/dist/web-dist/assets/index-BtqHnOp0.js +0 -23
- package/dist/web-dist/assets/index-BtqHnOp0.js.map +0 -1
- package/dist/web-dist/assets/index-ktDWx_UP.css +0 -2
- package/dist/web-dist/assets/mermaid-GHXKKRXX-DjR37lQN.js +0 -1
- package/dist/web-dist/assets/popover-Cm3PsrMh.js +0 -1
- package/dist/web-dist/assets/popover-Cm3PsrMh.js.map +0 -1
- package/dist/web-dist/assets/query-runner-6BhVPaC9.js +0 -9
- package/dist/web-dist/assets/query-runner-6BhVPaC9.js.map +0 -1
- package/dist/web-dist/assets/runner-CZKDzRoU.js +0 -1
- package/dist/web-dist/assets/schema-cZHeTHA0.js +0 -64
- package/dist/web-dist/assets/schema-cZHeTHA0.js.map +0 -1
- package/dist/web-dist/assets/tanstack-D6l4LIt3.js +0 -10
- package/dist/web-dist/assets/tanstack-D6l4LIt3.js.map +0 -1
- package/dist/web-dist/assets/toggle-group-BRWnLosM.js +0 -1
- package/dist/web-dist/assets/toggle-group-BRWnLosM.js.map +0 -1
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{r as zr,t as Je}from"./rolldown-runtime-CXHxssQy.js";import{ot as Js}from"./icons-Bm7rSZLJ.js";import{Ot as co,kt as ho}from"./radix-ui-BUv2Nuc1.js";var Xe=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(){}},fo=class extends Xe{#t;#e;#s;constructor(){super(),this.#s=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#s=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},Xs=new fo,go={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},po=class{#t=go;#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)}},Me=new po;function mo(e){setTimeout(e,0)}var vo=typeof window>"u"||"Deno"in globalThis;function V(){}function So(e,t){return typeof e=="function"?e(t):e}function Cs(e){return typeof e=="number"&&e>=0&&e!==1/0}function Vr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Se(e,t){return typeof e=="function"?e(t):e}function J(e,t){return typeof e=="function"?e(t):e}function Mn(e,t){const{type:s="all",exact:n,fetchStatus:r,predicate:i,queryKey:o,stale:a}=e;if(o){if(n){if(t.queryHash!==Ys(o,t.options))return!1}else if(!at(t.queryKey,o))return!1}if(s!=="all"){const u=t.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||r&&r!==t.state.fetchStatus||i&&!i(t))}function xn(e,t){const{exact:s,status:n,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(s){if(Ae(t.options.mutationKey)!==Ae(i))return!1}else if(!at(t.options.mutationKey,i))return!1}return!(n&&t.state.status!==n||r&&!r(t))}function Ys(e,t){return(t?.queryKeyHashFn||Ae)(e)}function Ae(e){return JSON.stringify(e,(t,s)=>ws(s)?Object.keys(s).sort().reduce((n,r)=>(n[r]=s[r],n),{}):s)}function at(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>at(e[s],t[s])):!1}var yo=Object.prototype.hasOwnProperty;function qr(e,t,s=0){if(e===t)return e;if(s>500)return t;const n=Pn(e)&&Pn(t);if(!n&&!(ws(e)&&ws(t)))return t;const r=(n?e:Object.keys(e)).length,i=n?t:Object.keys(t),o=i.length,a=n?new Array(o):{};let u=0;for(let l=0;l<o;l++){const c=n?l:i[l],d=e[c],h=t[c];if(d===h){a[c]=d,(n?l<r:yo.call(e,c))&&u++;continue}if(d===null||h===null||typeof d!="object"||typeof h!="object"){a[c]=h;continue}const f=qr(d,h,s+1);a[c]=f,f===d&&u++}return r===o&&u===r?e:a}function $t(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function Pn(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ws(e){if(!An(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!An(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function An(e){return Object.prototype.toString.call(e)==="[object Object]"}function Io(e){return new Promise(t=>{Me.setTimeout(t,e)})}function bs(e,t,s){return typeof s.structuralSharing=="function"?s.structuralSharing(e,t):s.structuralSharing!==!1?qr(e,t):t}function Ro(e,t,s=0){const n=[...e,t];return s&&n.length>s?n.slice(1):n}function Co(e,t,s=0){const n=[t,...e];return s&&n.length>s?n.slice(0,-1):n}var Zs=Symbol();function Qr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Zs?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function en(e,t){return typeof e=="function"?e(...t):!!e}function wo(e,t,s){let n=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),n||(n=!0,r.aborted?s():r.addEventListener("abort",s,{once:!0})),r)}),e}var lt=(()=>{let e=()=>vo;return{isServer(){return e()},setIsServer(t){e=t}}})();function Es(){let e,t;const s=new Promise((r,i)=>{e=r,t=i});s.status="pending",s.catch(()=>{});function n(r){Object.assign(s,r),delete s.resolve,delete s.reject}return s.resolve=r=>{n({status:"fulfilled",value:r}),e(r)},s.reject=r=>{n({status:"rejected",reason:r}),t(r)},s}function Jd(e){return e.state.status==="success"}var bo=mo;function Eo(){let e=[],t=0,s=a=>{a()},n=a=>{a()},r=bo;const i=a=>{t?e.push(a):r(()=>{s(a)})},o=()=>{const a=e;e=[],a.length&&r(()=>{n(()=>{a.forEach(u=>{s(u)})})})};return{batch:a=>{let u;t++;try{u=a()}finally{t--,t||o()}return u},batchCalls:a=>(...u)=>{i(()=>{a(...u)})},schedule:i,setNotifyFunction:a=>{s=a},setBatchNotifyFunction:a=>{n=a},setScheduler:a=>{r=a}}}var G=Eo(),_o=class extends Xe{#t=!0;#e;#s;constructor(){super(),this.#s=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#e||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#s=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#t}},jt=new _o;function To(e){return Math.min(1e3*2**e,3e4)}function Wr(e){return(e??"online")==="online"?jt.isOnline():!0}var _s=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Kr(e){let t=!1,s=0,n;const r=Es(),i=()=>r.status!=="pending",o=g=>{if(!i()){const m=new _s(g);h(m),e.onCancel?.(m)}},a=()=>{t=!0},u=()=>{t=!1},l=()=>Xs.isFocused()&&(e.networkMode==="always"||jt.isOnline())&&e.canRun(),c=()=>Wr(e.networkMode)&&e.canRun(),d=g=>{i()||(n?.(),r.resolve(g))},h=g=>{i()||(n?.(),r.reject(g))},f=()=>new Promise(g=>{n=m=>{(i()||l())&&g(m)},e.onPause?.()}).then(()=>{n=void 0,i()||e.onContinue?.()}),p=()=>{if(i())return;let g;const m=s===0?e.initialPromise:void 0;try{g=m??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(d).catch(v=>{if(i())return;const S=e.retry??(lt.isServer()?0:3),C=e.retryDelay??To,b=typeof C=="function"?C(s,v):C,w=S===!0||typeof S=="number"&&s<S||typeof S=="function"&&S(s,v);if(t||!w){h(v);return}s++,e.onFail?.(s,v),Io(b).then(()=>l()?void 0:f()).then(()=>{t?h(v):p()})})};return{promise:r,status:()=>r.status,cancel:o,continue:()=>(n?.(),r),cancelRetry:a,continueRetry:u,canStart:c,start:()=>(c()?p():f().then(p),r)}}var Jr=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Cs(this.gcTime)&&(this.#t=Me.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(lt.isServer()?1/0:3e5))}clearGcTimeout(){this.#t!==void 0&&(Me.clearTimeout(this.#t),this.#t=void 0)}};function Mo(e){return{onFetch:(t,s)=>{const n=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},u=0;const l=async()=>{let c=!1;const d=p=>{wo(p,()=>t.signal,()=>c=!0)},h=Qr(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 d(R),R})(),C=await h(S),{maxPages:b}=t.options,w=m?Co:Ro;return{pages:w(p.pages,C,b),pageParams:w(p.pageParams,g,b)}};if(r&&i.length){const p=r==="backward",g=p?Xr:Ts,m={pages:i,pageParams:o};a=await f(m,g(n,m),p)}else{const p=e??i.length;do{const g=u===0?o[0]??n.initialPageParam:Ts(n,a);if(u>0&&g==null)break;a=await f(a,g),u++}while(u<p)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=l}}}function Ts(e,{pages:t,pageParams:s}){const n=t.length-1;return t.length>0?e.getNextPageParam(t[n],t,s[n],s):void 0}function Xr(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}function xo(e,t){return t?Ts(e,t)!=null:!1}function Po(e,t){return!t||!e.getPreviousPageParam?!1:Xr(e,t)!=null}var Ao=class extends Jr{#t;#e;#s;#n;#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.#n=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=Fn(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=Fn(this.options);t.data!==void 0&&(this.setState(On(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const s=bs(this.state.data,e,this.options);return this.#l({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e){this.#l({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(V).catch(V):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#e}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>J(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Zs||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Se(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:!Vr(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#a||this.#f()?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#n.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 s=new AbortController,n=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(this.#a=!0,s.signal)})},r=()=>{const a=Qr(this.options,t),l=(()=>{const c={client:this.#i,queryKey:this.queryKey,meta:this.meta};return n(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 n(a),a})();(this.#t==="infinite"?Mo(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#l({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=Kr({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:a=>{a instanceof _s&&a.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.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.#n.config.onSuccess?.(a,this),this.#n.config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof _s){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.#n.config.onError?.(a,this),this.#n.config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}#l(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Yr(s.data,this.options),fetchMeta:e.meta??null};case"success":const n={...s,...On(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=e.manual?n:void 0,n;case"error":const r=e.error;return{...s,error:r,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),G.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Yr(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Wr(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function On(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Fn(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,n=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var Zr=class extends Xe{constructor(e,t){super(),this.options=t,this.#t=e,this.#a=null,this.#o=Es(),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#s=void 0;#n=void 0;#i;#r;#o;#a;#f;#l;#c;#d;#u;#h;#g=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),Ln(this.#e,this.options)?this.#p():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ms(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ms(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#I(),this.#R(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,s=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof J(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#C(),this.#e.setOptions(this.options),t._defaulted&&!$t(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const n=this.hasListeners();n&&Nn(this.#e,s,this.options,t)&&this.#p(),this.updateResult(),n&&(this.#e!==s||J(this.options.enabled,this.#e)!==J(t.enabled,this.#e)||Se(this.options.staleTime,this.#e)!==Se(t.staleTime,this.#e))&&this.#m();const r=this.#v();n&&(this.#e!==s||J(this.options.enabled,this.#e)!==J(t.enabled,this.#e)||r!==this.#h)&&this.#S(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),s=this.createResult(t,e);return Fo(this,s)&&(this.#n=s,this.#r=this.options,this.#i=this.#e.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,n)=>(this.trackProp(n),t?.(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,n))})}trackProp(e){this.#g.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),s=this.#t.getQueryCache().build(this.#t,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#p({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#p(e){this.#C();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(V)),t}#m(){this.#I();const e=Se(this.options.staleTime,this.#e);if(lt.isServer()||this.#n.isStale||!Cs(e))return;const t=Vr(this.#n.dataUpdatedAt,e)+1;this.#d=Me.setTimeout(()=>{this.#n.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#S(e){this.#R(),this.#h=e,!(lt.isServer()||J(this.options.enabled,this.#e)===!1||!Cs(this.#h)||this.#h===0)&&(this.#u=Me.setInterval(()=>{(this.options.refetchIntervalInBackground||Xs.isFocused())&&this.#p()},this.#h))}#y(){this.#m(),this.#S(this.#v())}#I(){this.#d!==void 0&&(Me.clearTimeout(this.#d),this.#d=void 0)}#R(){this.#u!==void 0&&(Me.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const s=this.#e,n=this.options,r=this.#n,i=this.#i,o=this.#r,a=e!==s?e.state:this.#s,{state:u}=e;let l={...u},c=!1,d;if(t._optimisticResults){const R=this.hasListeners(),y=!R&&Ln(e,t),_=R&&Nn(e,s,t,n);(y||_)&&(l={...l,...Yr(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(l.fetchStatus="idle")}let{error:h,errorUpdatedAt:f,status:p}=l;d=l.data;let g=!1;if(t.placeholderData!==void 0&&d===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",d=bs(r?.data,R,t),c=!0)}if(t.select&&d!==void 0&&!g)if(r&&d===i?.data&&t.select===this.#f)d=this.#l;else try{this.#f=t.select,d=t.select(d),d=bs(r?.data,d,t),this.#l=d,this.#a=null}catch(R){this.#a=R}this.#a&&(h=this.#a,d=this.#l,f=Date.now(),p="error");const m=l.fetchStatus==="fetching",v=p==="pending",S=p==="error",C=v&&m,b=d!==void 0,w={status:p,fetchStatus:l.fetchStatus,isPending:v,isSuccess:p==="success",isError:S,isInitialLoading:C,isLoading:C,data:d,dataUpdatedAt:l.dataUpdatedAt,error:h,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&&!b,isPaused:l.fetchStatus==="paused",isPlaceholderData:c,isRefetchError:S&&b,isStale:tn(e,t),refetch:this.refetch,promise:this.#o,isEnabled:J(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const R=w.data!==void 0,y=w.status==="error"&&!R,_=x=>{y?x.reject(w.error):R&&x.resolve(w.data)},T=()=>{const x=this.#o=w.promise=Es();_(x)},E=this.#o;switch(E.status){case"pending":e.queryHash===s.queryHash&&_(E);break;case"fulfilled":(y||w.data!==E.value)&&T();break;case"rejected":(!y||w.error!==E.reason)&&T()}}return w}updateResult(){const e=this.#n,t=this.createResult(this.#e,this.options);if(this.#i=this.#e.state,this.#r=this.options,this.#i.data!==void 0&&(this.#c=this.#e),$t(t,e))return;this.#n=t;const s=()=>{if(!e)return!0;const{notifyOnChangeProps:n}=this.options,r=typeof n=="function"?n():n;if(r==="all"||!r&&!this.#g.size)return!0;const i=new Set(r??this.#g);return this.options.throwOnError&&i.add("error"),Object.keys(this.#n).some(o=>{const a=o;return this.#n[a]!==e[a]&&i.has(a)})};this.#w({listeners:s()})}#C(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#s=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#w(e){G.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Oo(e,t){return J(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&J(t.retryOnMount,e)===!1)}function Ln(e,t){return Oo(e,t)||e.state.data!==void 0&&Ms(e,t,t.refetchOnMount)}function Ms(e,t,s){if(J(t.enabled,e)!==!1&&Se(t.staleTime,e)!=="static"){const n=typeof s=="function"?s(e):s;return n==="always"||n!==!1&&tn(e,t)}return!1}function Nn(e,t,s,n){return(e!==t||J(n.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&tn(e,s)}function tn(e,t){return J(t.enabled,e)!==!1&&e.isStaleByTime(Se(t.staleTime,e))}function Fo(e,t){return!$t(e.getCurrentResult(),t)}var Lo=class extends Zr{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,n=super.createResult(e,t),{isFetching:r,isRefetching:i,isError:o,isRefetchError:a}=n,u=s.fetchMeta?.fetchMore?.direction,l=o&&u==="forward",c=r&&u==="forward",d=o&&u==="backward",h=r&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:xo(t,s.data),hasPreviousPage:Po(t,s.data),isFetchNextPageError:l,isFetchingNextPage:c,isFetchPreviousPageError:d,isFetchingPreviousPage:h,isRefetchError:a&&!l&&!d,isRefetching:i&&!c&&!h}}},No=class extends Jr{#t;#e;#s;#n;constructor(e){super(),this.#t=e.client,this.mutationId=e.mutationId,this.#s=e.mutationCache,this.#e=[],this.state=e.state||ei(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#e.includes(e)||(this.#e.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#i({type:"continue"})},s={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#n=Kr({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(i,o)=>{this.#i({type:"failed",failureCount:i,error:o})},onPause:()=>{this.#i({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#s.canRun(this)});const n=this.state.status==="pending",r=!this.#n.canStart();try{if(n)t();else{this.#i({type:"pending",variables:e,isPaused:r}),this.#s.config.onMutate&&await this.#s.config.onMutate(e,this,s);const o=await this.options.onMutate?.(e,s);o!==this.state.context&&this.#i({type:"pending",context:o,variables:e,isPaused:r})}const i=await this.#n.start();return await this.#s.config.onSuccess?.(i,e,this.state.context,this,s),await this.options.onSuccess?.(i,e,this.state.context,s),await this.#s.config.onSettled?.(i,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(i,null,e,this.state.context,s),this.#i({type:"success",data:i}),i}catch(i){try{await this.#s.config.onError?.(i,e,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(i,e,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,i,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,i,e,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#i({type:"error",error:i}),i}finally{this.#s.runNext(this)}}#i(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),G.batch(()=>{this.#e.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function ei(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ko=class extends Xe{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#s=0}#t;#e;#s;build(e,t,s){const n=new No({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(n),n}add(e){this.#t.add(e);const t=St(e);if(typeof t=="string"){const s=this.#e.get(t);s?s.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=St(e);if(typeof t=="string"){const s=this.#e.get(t);if(s)if(s.length>1){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}else s[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=St(e);if(typeof t=="string"){const s=this.#e.get(t)?.find(n=>n.state.status==="pending");return!s||s===e}else return!0}runNext(e){const t=St(e);return typeof t=="string"?this.#e.get(t)?.find(s=>s!==e&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){G.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(s=>xn(t,s))}findAll(e={}){return this.getAll().filter(t=>xn(e,t))}notify(e){G.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return G.batch(()=>Promise.all(e.map(t=>t.continue().catch(V))))}};function St(e){return e.options.scope?.id}var Do=class extends Xe{#t;#e=void 0;#s;#n;constructor(e,t){super(),this.#t=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#t.defaultMutationOptions(e),$t(this.options,t)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Ae(t.mutationKey)!==Ae(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#r(e)}getCurrentResult(){return this.#e}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#i(),this.#r()}mutate(e,t){return this.#n=t,this.#s?.removeObserver(this),this.#s=this.#t.getMutationCache().build(this.#t,this.options),this.#s.addObserver(this),this.#s.execute(e)}#i(){const e=this.#s?.state??ei();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){G.batch(()=>{if(this.#n&&this.hasListeners()){const t=this.#e.variables,s=this.#e.context,n={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,t,s,n)}catch(r){Promise.reject(r)}try{this.#n.onSettled?.(e.data,null,t,s,n)}catch(r){Promise.reject(r)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,t,s,n)}catch(r){Promise.reject(r)}try{this.#n.onSettled?.(void 0,e.error,t,s,n)}catch(r){Promise.reject(r)}}}this.listeners.forEach(t=>{t(this.#e)})})}},$o=class extends Xe{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,s){const n=t.queryKey,r=t.queryHash??Ys(n,t);let i=this.get(r);return i||(i=new Ao({client:e,queryKey:n,queryHash:r,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(n)}),this.add(i)),i}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){G.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Mn(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Mn(e,s)):t}notify(e){G.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){G.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){G.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Xd=class{#t;#e;#s;#n;#i;#r;#o;#a;constructor(e={}){this.#t=e.queryCache||new $o,this.#e=e.mutationCache||new ko,this.#s=e.defaultOptions||{},this.#n=new Map,this.#i=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=Xs.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#a=jt.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),s=this.#t.build(this,t),n=s.state.data;return n===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(Se(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:s})=>[t,s.data])}setQueryData(e,t,s){const n=this.defaultQueryOptions({queryKey:e}),r=this.#t.get(n.queryHash)?.state.data,i=So(t,r);if(i!==void 0)return this.#t.build(this,n).setData(i,{...s,manual:!0})}setQueriesData(e,t,s){return G.batch(()=>this.#t.findAll(e).map(({queryKey:n})=>[n,this.setQueryData(n,t,s)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;G.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#t;return G.batch(()=>(s.findAll(e).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},n=G.batch(()=>this.#t.findAll(e).map(r=>r.cancel(s)));return Promise.all(n).then(V).catch(V)}invalidateQueries(e,t={}){return G.batch(()=>(this.#t.findAll(e).forEach(s=>{s.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},n=G.batch(()=>this.#t.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,s);return s.throwOnError||(i=i.catch(V)),r.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(n).then(V)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#t.build(this,t);return s.isStaleByTime(Se(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(V).catch(V)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(V).catch(V)}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.#s}setDefaultOptions(e){this.#s=e}setQueryDefaults(e,t){this.#n.set(Ae(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(n=>{at(e,n.queryKey)&&Object.assign(s,n.defaultOptions)}),s}setMutationDefaults(e,t){this.#i.set(Ae(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#i.values()],s={};return t.forEach(n=>{at(e,n.mutationKey)&&Object.assign(s,n.defaultOptions)}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#s.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Ys(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===Zs&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#s.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},I=zr(Js(),1),O=ho(),ti=I.createContext(void 0),si=e=>{const t=I.useContext(ti);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Yd=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,O.jsx)(ti.Provider,{value:e,children:t})),ni=I.createContext(!1),jo=()=>I.useContext(ni),Zd=ni.Provider;function Uo(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Bo=I.createContext(Uo()),Go=()=>I.useContext(Bo),Ho=(e,t,s)=>{const n=s?.state.error&&typeof e.throwOnError=="function"?en(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||n)&&(t.isReset()||(e.retryOnMount=!1))},zo=e=>{I.useEffect(()=>{e.clearReset()},[e])},Vo=({result:e,errorResetBoundary:t,throwOnError:s,query:n,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&n&&(r&&e.data===void 0||en(s,[e.error,n])),qo=e=>{if(e.suspense){const s=r=>r==="static"?r:Math.max(r??1e3,1e3),n=e.staleTime;e.staleTime=typeof n=="function"?(...r)=>s(n(...r)):s(n),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Qo=(e,t)=>e.isLoading&&e.isFetching&&!t,Wo=(e,t)=>e?.suspense&&t.isPending,kn=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function ri(e,t,s){const n=jo(),r=Go(),i=si(s),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const a=i.getQueryCache().get(o.queryHash);o._optimisticResults=n?"isRestoring":"optimistic",qo(o),Ho(o,r,a),zo(r);const u=!i.getQueryCache().get(o.queryHash),[l]=I.useState(()=>new t(i,o)),c=l.getOptimisticResult(o),d=!n&&e.subscribed!==!1;if(I.useSyncExternalStore(I.useCallback(h=>{const f=d?l.subscribe(G.batchCalls(h)):V;return l.updateResult(),f},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),I.useEffect(()=>{l.setOptions(o)},[o,l]),Wo(o,c))throw kn(o,l,r);if(Vo({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&&!lt.isServer()&&Qo(c,n)&&(u?kn(o,l,r):a?.promise)?.catch(V).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?c:l.trackResult(c)}function eh(e,t){return ri(e,Zr,t)}function th(e,t){const s=si(t),[n]=I.useState(()=>new Do(s,e));I.useEffect(()=>{n.setOptions(e)},[n,e]);const r=I.useSyncExternalStore(I.useCallback(o=>n.subscribe(G.batchCalls(o)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),i=I.useCallback((o,a)=>{n.mutate(o,a).catch(V)},[n]);if(r.error&&en(n.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:i,mutateAsync:r.mutate}}function sh(e,t){return ri(e,Lo,t)}var Dn=I.use,sn=I.useLayoutEffect;function Ko(e,t,s){I.useEffect(()=>{if(!e.current||s||typeof IntersectionObserver!="function")return()=>t();const n=new IntersectionObserver(r=>{t(r.pop())},{rootMargin:"100px"});return n.observe(e.current),()=>{n.disconnect(),t()}},[t,s,e])}function Jo(e){const t=I.useRef(null);return I.useImperativeHandle(e,()=>t.current,[]),t}function ut(e){return e[e.length-1]}function qe(e,t){return typeof e=="function"?e(t):e}var ii=Object.prototype.hasOwnProperty,Xo=Object.prototype.propertyIsEnumerable;function oi(e){for(const t in e)if(ii.call(e,t))return!0;return!1}var Yo=()=>Object.create(null),Te=(e,t)=>xe(e,t,Yo);function xe(e,t,s=()=>({}),n=0){if(e===t)return e;if(n>500)return t;const r=t,i=Un(e)&&Un(r);if(!i&&!(Ut(e)&&Ut(r)))return r;const o=i?e:$n(e);if(!o)return r;const a=i?r:$n(r);if(!a)return r;const u=o.length,l=a.length,c=i?new Array(l):s();let d=0;for(let h=0;h<l;h++){const f=i?h:a[h],p=e[f],g=r[f];if(p===g){c[f]=p,(i?h<u:ii.call(e,f))&&d++;continue}if(p===null||g===null||typeof p!="object"||typeof g!="object"){c[f]=g;continue}const m=xe(p,g,s,n+1);c[f]=m,m===p&&d++}return u===l&&d===u?e:c}function $n(e){const t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;const s=Object.getOwnPropertySymbols(e);if(s.length===0)return t;for(const n of s){if(!Xo.call(e,n))return!1;t.push(n)}return t}function Ut(e){if(!jn(e))return!1;const t=e.constructor;if(typeof t>"u")return!0;const s=t.prototype;return!(!jn(s)||!s.hasOwnProperty("isPrototypeOf"))}function jn(e){return Object.prototype.toString.call(e)==="[object Object]"}function Un(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ye(e,t,s){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 n=0,r=e.length;n<r;n++)if(!ye(e[n],t[n],s))return!1;return!0}if(Ut(e)&&Ut(t)){const n=s?.ignoreUndefined??!0;if(s?.partial){for(const o in t)if((!n||t[o]!==void 0)&&!ye(e[o],t[o],s))return!1;return!0}let r=0;if(!n)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((!n||t[o]!==void 0)&&(i++,i>r||!ye(e[o],t[o],s)))return!1;return r===i}return!1}function Zo(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 ea=/[\x00-\x1f\x7f"<>`{}]/g;function ta(e){return e.replace(ea,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0"))}function Bn(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,s=>{try{return decodeURI(s)}catch{return s}})}return ta(t)}var sa=["http:","https:","mailto:","tel:"];function Bt(e,t){if(!e)return!1;try{const s=new URL(e);return!t.has(s.protocol)}catch{return!1}}function Ze(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 s=0,n="",r;for(;(r=t.exec(e))!==null;)n+=Bn(e.slice(s,r.index))+r[0],s=t.lastIndex;n=n+Bn(s?e.slice(s):e);let i=!1;return n.startsWith("//")&&(i=!0,n="/"+n.replace(/^\/+/,"")),{path:n,handledProtocolRelativeURL:i}}function na(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function ra(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;return!0}function nn(){throw new Error("Invariant failed")}function Gt(e){const t=new Map;let s,n;const r=i=>{i.next&&(i.prev?(i.prev.next=i.next,i.next.prev=i.prev,i.next=void 0,n&&(n.next=i,i.prev=n)):(i.next.prev=void 0,s=i.next,i.next=void 0,n&&(i.prev=n,n.next=i)),n=i)};return{get(i){const o=t.get(i);if(o)return r(o),o.value},set(i,o){if(t.size>=e&&s){const u=s;t.delete(u.key),u.next&&(s=u.next,u.next.prev=void 0),u===n&&(n=void 0)}const a=t.get(i);if(a)a.value=o,r(a);else{const u={key:i,value:o,prev:n};n&&(n.next=u),n=u,s||(s=u),t.set(i,u)}},clear(){t.clear(),s=void 0,n=void 0}}}var pe=4,ai=5;function li(e,t,s=new Uint16Array(6)){const n=e.indexOf("/",t),r=n===-1?e.length:n,i=e.substring(t,r);if(!i||!i.includes("$"))return s[0]=0,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s;if(i==="$"){const u=e.length;return s[0]=2,s[1]=t,s[2]=t,s[3]=u,s[4]=u,s[5]=u,s}if(i.charCodeAt(0)===36)return s[0]=1,s[1]=t,s[2]=t+1,s[3]=r,s[4]=r,s[5]=r,s;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 s[0]=3,s[1]=t+o,s[2]=t+l,s[3]=t+c,s[4]=t+a+1,s[5]=r,s}}else if(u===36){const l=o+1,c=o+2;return c===a?(s[0]=2,s[1]=t+o,s[2]=t+l,s[3]=t+c,s[4]=t+a+1,s[5]=e.length,s):(s[0]=1,s[1]=t+o,s[2]=t+c,s[3]=t+a,s[4]=t+a+1,s[5]=r,s)}}return s[0]=0,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s}function Qt(e,t,s,n,r,i,o,a){a?.(s);let u=n;{const l=s.fullPath??s.from,c=s.options,d=l.length,h=c?.caseSensitive??e,f=c?.params?.parse??c?.parseParams;for(;u<d;){const g=li(l,u,t);let m;const v=u,S=g[5];u=S+1,i++;const C=g[0];switch(C){case 0:{const b=l.substring(g[2],g[3]);let w=b,R;h?R=r.static??=new Map:(w=b.toLowerCase(),R=r.staticInsensitive??=new Map);const y=R.get(w);if(y)m=y;else{const _=ze(l);_.parent=r,_.depth=i,m=_,R.set(w,_)}break}case 1:case 3:case 2:{let b=l.substring(v,g[1]),w=l.substring(g[4],S);const R=h&&!!(b||w);h||(b=b.toLowerCase(),w=w.toLowerCase());const y=C===1?r.dynamic:C===3?r.optional:r.wildcard,_=C!==2&&!f&&y?.find(T=>!T.parse&&T.caseSensitive===R&&T.prefix===b&&T.suffix===w);if(_)m=_;else{const T=ia(C,l,R,b,w);m=T,T.parent=r,T.depth=i;let E;C===1?E=r.dynamic??=[]:C===3?E=r.optional??=[]:E=r.wildcard??=[],E.push(T),E.length===2&&o?.push(E)}break}}r=m}if(f&&s.children&&!s.isRoot&&s.id&&s.id.charCodeAt(s.id.lastIndexOf("/")+1)===95){const g=ze(l);g.kind=ai,g.parent=r,i++,g.depth=i,r.pathless??=[],r.pathless.push(g),r=g}const p=(s.path||!s.children)&&!s.isRoot;if(p&&l.endsWith("/")){const g=ze(l);g.kind=pe,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=s,r.fullPath=l)}if(s.children)for(const l of s.children)Qt(e,t,l,u,r,i,o,a)}function ui(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 ze(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 ia(e,t,s,n,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:s,prefix:n,suffix:r}}function oa(e,t){const s=ze("/"),n=new Uint16Array(6),r=[];for(const i of e)Qt(!1,n,i,1,s,0,r);for(const i of r)i.sort(ui);t.masksTree=s,t.flatCache=Gt(1e3)}function aa(e,t){e||="/";const s=t.flatCache.get(e);if(s!==void 0)return s;const n=rn(e,t.masksTree);return t.flatCache.set(e,n),n}function la(e,t,s,n,r){e||="/",n||="/";const i=t?`case\0${e}`:e;let o=r.singleCache.get(i);return o||(o=ze("/"),Qt(t,new Uint16Array(6),{from:e},1,o,0),r.singleCache.set(i,o)),rn(n,o,s)}function ua(e,t,s=!1){const n=s?e:`nofuzz\0${e}`,r=t.matchCache.get(n);if(r!==void 0)return r;e||="/";let i;try{i=rn(e,t.segmentTree,s)}catch(o){if(o instanceof URIError)i=null;else throw o}return i&&(i.branch=di(i.route)),t.matchCache.set(n,i),i}function ca(e){return e==="/"?e:e.replace(/\/{1,}$/,"")}function da(e,t=!1,s){const n=ze(e.fullPath),r=new Uint16Array(6),i=[],o={},a={};let u=0;Qt(t,r,e,1,n,0,i,l=>{if(s?.(l,u),l.id in o&&nn(),o[l.id]=l,u!==0&&l.path){const c=ca(l.fullPath);(!a[c]||l.fullPath.endsWith("/"))&&(a[c]=l)}u++});for(const l of i)l.sort(ui);return{processedTree:{segmentTree:n,singleCache:Gt(1e3),matchCache:Gt(1e3),flatCache:null,masksTree:null},routesById:o,routesByPath:a}}function rn(e,t,s=!1){const n=e.split("/"),r=fa(e,n,t,s);if(!r)return null;const[i]=ci(e,n,r);return{route:r.node.route,rawParams:i}}function ci(e,t,s){const n=ha(s.node);let r=null;const i=Object.create(null);let o=s.extract?.part??0,a=s.extract?.node??0,u=s.extract?.path??0,l=s.extract?.segment??0;for(;a<n.length;o++,a++,u++,l++){const c=n[a];if(c.kind===pe)break;if(c.kind===ai){l--,o--,u--;continue}const d=t[o],h=u;if(d&&(u+=d.length),c.kind===1){r??=s.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=d.substring(p,d.length-g);i[m]=decodeURIComponent(v)}else{const g=f.substring(1);i[g]=decodeURIComponent(d)}}else if(c.kind===3){if(s.skipped&1<<a){o--,u=h-1;continue}r??=s.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?d.substring(p,d.length-g):d;v&&(i[m]=decodeURIComponent(v))}else if(c.kind===2){const f=c,p=e.substring(h+f.prefix.length,e.length-f.suffix.length),g=decodeURIComponent(p);i["*"]=g,i._splat=g;break}}return s.rawParams&&Object.assign(i,s.rawParams),[i,{part:o,node:a,path:u,segment:l}]}function di(e){const t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function ha(e){const t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function fa(e,t,s,n){if(e==="/"&&s.index)return{node:s.index,skipped:0};const r=!ut(t),i=r&&e!=="/",o=t.length-(r?1:0),a=[{node:s,index:1,skipped:0,statics:0,dynamics:0,optionals:0}];let u=null,l=null;for(;a.length;){const c=a.pop(),{node:d,index:h,skipped:f,statics:p,dynamics:g,optionals:m}=c;let{extract:v,rawParams:S}=c;if(d.kind===2&&d.route&&!It(l,c))continue;if(d.parse){if(!Gn(e,t,c))continue;S=c.rawParams,v=c.extract}n&&d.route&&d.kind!==pe&&It(u,c)&&(u=c);const C=h===o;if(C&&(d.route&&(!i||d.kind===pe||d.kind===2)&&It(l,c)&&(l=c),!d.optional&&!d.wildcard&&!d.index&&!d.pathless))continue;const b=C?void 0:t[h];let w;if(C&&d.index){const R={node:d.index,index:h,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S};let y=!0;if(d.index.parse&&(Gn(e,t,R)||(y=!1)),y){if(!g&&!m&&!f&&ga(p,o))return R;It(l,R)&&(l=R)}}if(d.wildcard)for(let R=d.wildcard.length-1;R>=0;R--){const y=d.wildcard[R],{prefix:_,suffix:T}=y;if(!(_&&(C||!(y.caseSensitive?b:w??=b.toLowerCase()).startsWith(_)))){if(T){if(C)continue;const E=t.slice(h).join("/"),x=E.slice(-T.length);if((y.caseSensitive?x:x.toLowerCase())!==T||E.length-T.length<_.length)continue}a.push({node:y,index:o,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}}if(d.optional){const R=f|1<<d.depth+1;for(let y=d.optional.length-1;y>=0;y--){const _=d.optional[y];a.push({node:_,index:h,skipped:R,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}if(!C)for(let y=d.optional.length-1;y>=0;y--){const _=d.optional[y],{prefix:T,suffix:E}=_;if(T||E){const x=_.caseSensitive?b:w??=b.toLowerCase();if(T&&!x.startsWith(T)||E&&x.indexOf(E,x.length-E.length)<T.length)continue}a.push({node:_,index:h+1,skipped:f,statics:p,dynamics:g,optionals:m+yt(o,h),extract:v,rawParams:S})}}if(!C&&d.dynamic&&b)for(let R=d.dynamic.length-1;R>=0;R--){const y=d.dynamic[R],{prefix:_,suffix:T}=y;if(_||T){const E=y.caseSensitive?b:w??=b.toLowerCase();if(_&&!E.startsWith(_)||T&&E.indexOf(T,E.length-T.length)<_.length)continue}a.push({node:y,index:h+1,skipped:f,statics:p,dynamics:g+yt(o,h),optionals:m,extract:v,rawParams:S})}if(!C&&d.staticInsensitive){const R=d.staticInsensitive.get(w??=b.toLowerCase());R&&a.push({node:R,index:h+1,skipped:f,statics:p+yt(o,h),dynamics:g,optionals:m,extract:v,rawParams:S})}if(!C&&d.static){const R=d.static.get(b);R&&a.push({node:R,index:h+1,skipped:f,statics:p+yt(o,h),dynamics:g,optionals:m,extract:v,rawParams:S})}if(d.pathless)for(let R=d.pathless.length-1;R>=0;R--){const y=d.pathless[R];a.push({node:y,index:h,skipped:f,statics:p,dynamics:g,optionals:m,extract:v,rawParams:S})}}if(l)return l;if(n&&u){let c=u.index;for(let h=0;h<u.index;h++)c+=t[h].length;const d=c===e.length?"/":e.slice(c);return u.rawParams??=Object.create(null),u.rawParams["**"]=decodeURIComponent(d),u}return null}function yt(e,t){return 2**(e-t-1)}function ga(e,t){return e===2**(t-1)-1}function Gn(e,t,s){let n,r;try{[n,r]=ci(e,t,s)}catch{return null}if(s.rawParams=n,s.extract=r,!s.node.parse)return!0;try{if(s.node.parse(n)===!1)return null}catch{}return!0}function It(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===pe)>(e.node.kind===pe)||t.node.kind===pe==(e.node.kind===pe)&&t.node.depth>e.node.depth))):!0}function Ot(e){return Ft(e.filter(t=>t!==void 0).join("/"))}function Ft(e){return e.replace(/\/{2,}/g,"/")}function hi(e){return e==="/"?e:e.replace(/^\/{1,}/,"")}function de(e){const t=e.length;return t>1&&e[t-1]==="/"?e.replace(/\/{1,}$/,""):e}function fi(e){return de(hi(e))}function Ht(e,t){return e?.endsWith("/")&&e!=="/"&&e!==`${t}/`?e.slice(0,-1):e}function pa(e,t,s){return Ht(e,s)===Ht(t,s)}function ma({base:e,to:t,trailingSlash:s="never",cache:n}){if(t.includes("//")&&(t=Ft(t)),t.startsWith("/"))return t.length===1||s==="preserve"?t:s==="always"?t.endsWith("/")?t:`${t}/`:t.endsWith("/")?t.slice(0,-1):t;const r=t===".";let i;if(n){i=r?e:e+"\0"+t;const l=n.get(i);if(l)return l}let o;if(r)o=e.split("/");else{for(e.includes("//")&&(e=Ft(e)),o=e.split("/");o.length>1&&ut(o)==="";)o.pop();const l=t.split("/");for(let c=0,d=l.length;c<d;c++){const h=l[c];h===""?c?c===d-1&&o.push(h):o=[h]:h===".."?o.length>1?o.pop():o=[""]:h==="."||o.push(h)}}o.length>1&&(ut(o)===""?s==="never"&&o.pop():s==="always"&&o.push(""));const a=o.join("/"),u=(r?Ft(a):a)||"/";return i&&n&&n.set(i,u),u}function va(e){const t=new Map(e.map(r=>[encodeURIComponent(r),r])),s=Array.from(t.keys()).map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),n=new RegExp(s,"g");return r=>r.replace(n,i=>t.get(i)??i)}function os(e,t,s){const n=t[e];return typeof n!="string"?n:e==="_splat"?/^[a-zA-Z0-9\-._~!/]*$/.test(n)?n:n.split("/").map(r=>zn(r,s)).join("/"):zn(n,s)}function Hn({path:e,params:t,decoder:s,...n}){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=li(e,c,u);const d=u[5];if(a=d+1,c===d)continue;const h=u[0];if(h===0){l+="/"+e.substring(c,d);continue}if(h===2){const f=t._splat;i._splat=f,i["*"]=f;const p=e.substring(c,u[1]),g=e.substring(u[4],d);if(!f){r=!0,(p||g)&&(l+="/"+p+g);continue}const m=os("_splat",t,s);l+="/"+p+m+g;continue}if(h===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],d),m=os(f,t,s)??"undefined";l+="/"+p+m+g;continue}if(h===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],d),v=os(f,t,s)??"";l+="/"+g+v+m;continue}}return e.endsWith("/")&&(l+="/"),{usedParams:i,interpolatedPath:l||"/",isMissingParams:r}}function zn(e,t){const s=encodeURIComponent(e);return t?.(s)??s}function Qe(e){return e?.isNotFound===!0}function Sa(){try{return sessionStorage}catch{return}}var ya="tsr-scroll-restoration-v1_3",gi=Sa();function Ia(){try{return JSON.parse(gi?.getItem("tsr-scroll-restoration-v1_3")||"{}")}catch{return{}}}function Ra(){try{gi?.setItem(ya,JSON.stringify(Be))}catch{}}var Be=Ia(),Vn="data-scroll-restoration-id",Ca=e=>e.state.__TSR_key||e.href;function wa(e){const t=e.getAttribute(Vn);if(t)return`[${Vn}="${t}"]`;let s="",n=e,r;for(;r=n.parentNode;){let i=1,o=n;for(;o=o.previousElementSibling;)i++;const a=`${n.localName}:nth-child(${i})`;s=s?`${a} > ${s}`:a,n=r}return s}var Rt=!1,Lt="window";function xs(e){try{return typeof e=="function"?e():document.querySelector(e)}catch{}}function qn(e){const t=new Set;for(const s of e){if(s===Lt)continue;const n=xs(s);n&&t.add(n)}return t}function ba(e,t){const s=t??e.options.scrollRestoration,n=e._scroll;s&&(n.restoring=!0);const r=e.options.getScrollRestorationKey||Ca,i=new Set,o=a=>{const u=Be[a]||={};for(const l of i)l===document?u[Lt]={scrollX,scrollY}:l.isConnected&&(u[wa(l)]={scrollX:l.scrollLeft,scrollY:l.scrollTop})};s&&!n.restoration&&(n.restoration=!0,Rt=!1,history.scrollRestoration="manual",document.addEventListener("scroll",a=>{Rt||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())),Ra()})),!n.reset&&(n.reset=!0,e.subscribe("onRendered",a=>{const u=e.options.scrollRestorationBehavior,l=e.options.scrollToTopSelectors,c=n.next,d=n.hash;let h;if(i.clear(),n.next=!0,n.hash=!1,typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation}))return;const f=r(a.toLocation),p=a.fromLocation&&r(a.fromLocation);if(n.restoring&&p&&p!==f){const g=Be[p];if(g){let m=Be[f];for(const v in g){if(v===Lt){if(c)continue}else{const S=xs(v);if(!S||c&&l&&(h??=qn(l),h.has(S)))continue}m||(m=Be[f]={}),m[v]??=g[v]}}}Rt=!0;try{const g=a.toLocation.hash,m=a.toLocation.state.__hashScrollIntoViewOptions??!0;let v=!1;if(c){!g&&l&&(h??=qn(l));const S=g&&m&&d,C=n.restoring?Be[f]:void 0;if(C)for(const b in C){const{scrollX:w,scrollY:R}=C[b];if(b===Lt){if(S)continue;scrollTo({top:R,left:w,behavior:u}),v=!0}else{const y=xs(b);y&&(y.scrollLeft=w,y.scrollTop=R,h?.delete(y))}}if(!g){const b={top:0,left:0,behavior:u};if(v||scrollTo(b),h)for(const w of h)w.scrollTo(b)}}!v&&g&&m&&document.getElementById(g)?.scrollIntoView(m)}finally{Rt=!1}}))}function Ea(e,t=String){const s=new URLSearchParams;for(const n in e){const r=e[n];r!==void 0&&s.set(n,t(r))}return s.toString()}function as(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function _a(e){const t=new URLSearchParams(e),s=Object.create(null);for(const[n,r]of t.entries()){const i=s[n];i==null?s[n]=as(r):Array.isArray(i)?i.push(as(r)):s[n]=[i,as(r)]}return s}var Ta=/^(?:\s|["[{\d-]|fa|nu|tr)/,Ma=Pa(JSON.parse),xa=Aa(JSON.stringify,JSON.parse);function Pa(e){return t=>{t[0]==="?"&&(t=t.substring(1));const s=_a(t);for(const n in s){const r=s[n];if(typeof r=="string")try{s[n]=e(r)}catch{}}return s}}function Aa(e,t){const s=t===JSON.parse;function n(r){if(r&&typeof r=="object")try{return e(r)}catch{}else if(t&&typeof r=="string"){if(s&&!Ta.test(r))return r;try{return t(r),e(r)}catch{}}return r}return r=>{const i=Ea(r,n);return i?`?${i}`:""}}var nt="__root__";function Oa(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 s=new Response(null,{status:e.statusCode,headers:t});if(s.options=e,e.throw)throw s;return s}function pi(e){return e instanceof Response&&!!e.options}function Fa(e){return{input:({url:t})=>{for(const s of e)t=Ps(s,t);return t},output:({url:t})=>{for(let s=e.length-1;s>=0;s--)t=mi(e[s],t);return t}}}function La(e){const t=fi(e.basepath),s=`/${t}`,n=e.caseSensitive?s:s.toLowerCase(),r=`${n}/`;return{input:({url:i})=>{const o=e.caseSensitive?i.pathname:i.pathname.toLowerCase();return o===n?i.pathname="/":o.startsWith(r)&&(i.pathname=i.pathname.slice(s.length)),i},output:({url:i})=>(i.pathname=Ot(["/",t,i.pathname]),i)}}function Ps(e,t){const s=e?.input?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function mi(e,t){const s=e?.output?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function Na(e,t){const{createMutableStore:s,createReadonlyStore:n,batch:r}=t,i=new Map,o=s("idle"),a=s(e),u=s(void 0),l=s([]),c=n(()=>l.get().map(g=>i.get(g).get())),d=n(()=>({status:o.get(),isLoading:o.get()==="pending",matches:c.get(),location:a.get(),resolvedLocation:u.get()}));function h(g){let m=i.get(g);return m||(m=s(void 0),i.set(g,m)),m}const f={status:o,location:a,resolvedLocation:u,ids:l,matches:c,byRoute:i,__store:d,getMatchStore:h,setMatches:p};function p(g){const m=l.get(),v=g.map(S=>S.routeId);r(()=>{ra(m,v)||l.set(v);for(const S of m)v.includes(S)||i.get(S).set(()=>{});for(const S of g){const C=h(S.routeId);C.get()!==S&&C.set(S)}})}return f}var Ie="__TSR_index",Qn="popstate",Wn="beforeunload";function ka(e){let t=e.getLocation();const s=new Set,n=o=>{t=e.getLocation(),s.forEach(a=>a({location:t,action:o}))},r=o=>{e.notifyOnIndexChange??!0?n(o):t=e.getLocation()},i=async({task:o,navigateOpts:a,...u})=>{if(a?.ignoreBlocker??!1){o();return}const l=e.getBlockers?.()??[],c=u.type==="PUSH"||u.type==="REPLACE";if(typeof document<"u"&&l.length&&c)for(const d of l){const h=zt(u.path,u.state);if(await d.blockerFn({currentLocation:t,nextLocation:h,action:u.type})){e.onBlocked?.();return}}o()};return{get location(){return t},get length(){return e.getLength()},subscribers:s,subscribe:o=>(s.add(o),()=>{s.delete(o)}),push:(o,a,u)=>{const l=t.state[Ie];a=Kn(l+1,a),i({task:()=>{e.pushState(o,a),n({type:"PUSH"})},navigateOpts:u,type:"PUSH",path:o,state:a})},replace:(o,a,u)=>{const l=t.state[Ie];a=Kn(l,a),i({task:()=>{e.replaceState(o,a),n({type:"REPLACE"})},navigateOpts:u,type:"REPLACE",path:o,state:a})},go:(o,a)=>{i({task:()=>{e.go(o),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[Ie]!==0,createHref:o=>e.createHref(o),block:o=>{if(!e.setBlockers)return()=>{};const a=e.getBlockers?.()??[];return e.setBlockers([...a,o]),()=>{const u=e.getBlockers?.()??[];e.setBlockers?.(u.filter(l=>l!==o))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:n}}function Kn(e,t){t||(t={});const s=on();return{...t,key:s,__TSR_key:s,[Ie]:e}}function Da(e){const t=e?.window??(typeof document<"u"?window:void 0),s=t.history.pushState,n=t.history.replaceState;let r=[];const i=()=>r,o=y=>r=y,a=e?.createHref??(y=>y),u=e?.parseLocation??(()=>zt(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){const y=on();t.history.replaceState({[Ie]:0,key:y,__TSR_key:y},"")}let l=u(),c,d=!1,h=!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(_),x=!!m;x||(c=l),l=zt(_,T),m=[E,T,m?.[2]||y],x||queueMicrotask(()=>v())},C=y=>{l=u(),R.notify({type:y})},b=async()=>{if(h){h=!1;return}const y=u(),_=y.state[Ie]-l.state[Ie],T=_===1,E=_===-1,x=!T&&!E||d;d=!1;const L=x?"GO":E?"BACK":"FORWARD",F=x?{type:"GO",index:_}:{type:E?"BACK":"FORWARD"};if(f)f=!1;else{const $=i();if(typeof document<"u"&&$.length){for(const M of $)if(await M.blockerFn({currentLocation:l,nextLocation:y,action:L})){h=!0,t.history.go(1),R.notify(F);return}}}l=u(),R.notify(F)},w=y=>{if(p){p=!1;return}let _=!1;const T=i();if(typeof document<"u"&&T.length)for(const E of T){const x=E.enableBeforeUnload??!0;if(x===!0){_=!0;break}if(typeof x=="function"&&x()===!0){_=!0;break}}if(_)return y.preventDefault(),y.returnValue=""},R=ka({getLocation:g,getLength:()=>t.history.length,pushState:(y,_)=>S(!0,y,_),replaceState:(y,_)=>S(!1,y,_),back:y=>(y&&(f=!0),p=!0,t.history.back()),forward:y=>{y&&(f=!0),p=!0,t.history.forward()},go:y=>{d=!0,t.history.go(y)},createHref:y=>a(y),flush:v,destroy:()=>{t.history.pushState=s,t.history.replaceState=n,t.removeEventListener(Wn,w,{capture:!0}),t.removeEventListener(Qn,b)},onBlocked:()=>{c&&l!==c&&(l=c)},getBlockers:i,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Wn,w,{capture:!0}),t.addEventListener(Qn,b),t.history.pushState=function(...y){const _=s.apply(t.history,y);return R._ignoreSubscribers||C("PUSH"),_},t.history.replaceState=function(...y){const _=n.apply(t.history,y);return R._ignoreSubscribers||C("REPLACE"),_},R}function $a(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"");return t.startsWith("//")&&(t="/"+t.replace(/^\/+/,"")),t}function zt(e,t){const s=$a(e),n=s.indexOf("#"),r=s.indexOf("?"),i=on();return{href:s,pathname:s.substring(0,n>0?r>0?Math.min(n,r):n:r>0?r:s.length),hash:n>-1?s.substring(n):"",search:r>-1?s.slice(r,n===-1?void 0:n):"",state:t||{[Ie]:0,key:i,__TSR_key:i}}}function on(){return(Math.random()+1).toString(36).substring(7)}function Jn(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function Wt(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function Xn({key:e,__TSR_key:t,__TSR_index:s,__hashScrollIntoViewOptions:n,...r}){return r}function ja(e,t,s,n){for(const r of t){if(n&&e._tx!==n)return;s.some(i=>i.routeId===r.routeId)||e.routesById[r.routeId].options.onLeave?.(r)}for(const r of s){if(n&&e._tx!==n)return;e.routesById[r.routeId].options[t.some(i=>i.routeId===r.routeId)?"onStay":"onEnter"]?.(r)}}var Ua=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 s=>(s(),!1),this.update=s=>{const n=this.options,r=this.basepath??n?.basepath??"/",i=this.basepath===void 0,o=n?.rewrite;if(this.options={...n,...s},this.isServer=this.options.isServer??!1??typeof document>"u",this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=va(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=Da()),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=Gt(1e3),l=this.buildRouteTree(),this.setRoutes(l)}if(!this.stores&&this.latestLocation){const l=this.getStoreConfig(this);this.batch=l.batch,this.stores=Na(this.latestLocation,l),ba(this)}const a=this.options.basepath??"/",u=this.options.rewrite;if(i||r!==a||o!==u){this.basepath=a;const l=[],c=fi(a);c&&c!=="/"&&l.push(La({basepath:a})),u&&l.push(u),this.rewrite=l.length===0?void 0:l.length===1?l[0]:Fa(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 s=da(this.routeTree,this.options.caseSensitive,(n,r)=>{n.init({originalIndex:r})});return this.options.routeMasks&&oa(this.options.routeMasks,s.processedTree),s},this.subscribe=(s,n)=>{const r={eventType:s,fn:n};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=s=>{for(const n of this.subscribers)if(n.eventType===s.type)try{n.fn(s)}catch(r){console.error(r)}},this.parseLocation=(s,n)=>{const r=({pathname:u,search:l,hash:c,href:d,state:h})=>{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:Ze(u).path,external:!1,searchStr:S,search:Te(n?.search,v),hash:Ze(c.slice(1)).path,state:xe(n?.state,h)}}const f=new URL(d,this.origin),p=Ps(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:d,pathname:Ze(p.pathname).path,external:!!this.rewrite&&p.origin!==this.origin,searchStr:m,search:Te(n?.search,g),hash:Ze(p.hash.slice(1)).path,state:xe(n?.state,h)}},i=r(s),{__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=(s,n)=>ma({base:s,to:n,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(s,n,r)=>typeof s=="string"?this.matchRoutesInternal({pathname:s,search:n},r):this.matchRoutesInternal(s,n),this.getMatchedRoutes=s=>{const n=Object.create(null),r=ua(de(s),this.processedTree,!0);return r&&Object.assign(n,r.rawParams),[r?.branch||[this.routesById.__root__],n,r?.route]},this.buildLocation=s=>{const n=(i={})=>{if(i.href){const T=zt(i.href,{});i={...i,to:Ps(this.rewrite,new URL(T.pathname,this.origin)).pathname,search:this.options.parseSearch(T.search),hash:T.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],d=this.resolvePathWithBase(u,i.to?`${i.to}`:".");let h=Yn(i.params,c);const f=this.routesByPath[de(d)];let p;if(f)p=this.getRouteBranch(f);else if(d.includes("$"))p=[];else{const[T,E,x]=this.getMatchedRoutes(d);p=T,this.options.notFoundRoute&&(!x||x.path!=="/"&&E["**"])&&(p=[...p,this.options.notFoundRoute])}if(p.length&&oi(h))for(const T of p){const E=T.options.params?.stringify??T.options.stringifyParams;if(E){h===c&&(h=Object.assign(Object.create(null),h));try{Object.assign(h,E(h))}catch{}}}const g=s.leaveParams?d:Ze(Hn({path:d,params:h,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path;let m=l;if(s._includeValidateSearch&&this.options.search?.strict){const T={};p.forEach(E=>{if(E.options.validateSearch)try{Object.assign(T,Nt(E.options.validateSearch,{...T,...m}))}catch{}}),m=T}m=Ga(m,i,p,s._includeValidateSearch),m=Te(l,m);const v=this.options.stringifySearch(m),S=i.hash===!0?o.hash:i.hash?qe(i.hash,o.hash):void 0,C=S?`#${S}`:"";let b=i.state===!0?o.state:i.state?qe(i.state,o.state):{};i.state&&(b=xe(o.state,b));const w=`${g}${v}${C}`;let R,y,_=!1;if(this.rewrite){const T=new URL(w,this.origin),E=mi(this.rewrite,T);R=T.href.replace(T.origin,""),E.origin!==this.origin?(y=E.href,_=!0):y=E.pathname+E.search+E.hash}else R=na(w),y=R;return{publicHref:y,href:R,pathname:g,search:m,searchStr:v,state:b,hash:S??"",external:_,unmaskOnReload:i.unmaskOnReload}},r=n(s);if(s.mask)r.maskedLocation=n({from:s.from,...s.mask});else if(this.options.routeMasks){const i=aa(r.pathname,this.processedTree);if(i){const o=Object.assign(Object.create(null),i.rawParams),{from:a,params:u,...l}=i.route,c=Yn(u,o);r.maskedLocation=n({from:s.from,...l,params:c})}}return r},this.commitLocation=async({viewTransition:s,ignoreBlocker:n,...r})=>{let i;const o=de(this.latestLocation.href)===de(r.href)&&ye(Xn(r.state),Xn(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:d,...h}=r;c&&(h={...c,state:{...c.state,__tempKey:void 0,__tempLocation:{...h,search:h.searchStr,state:{...h.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(h.unmaskOnReload??this.options.unmaskOnReload??!1)&&(h.state.__tempKey=this.tempLocationKey)),h.state.__hashScrollIntoViewOptions=d??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=s,i=r.replace?"REPLACE":"PUSH",this.history[i==="REPLACE"?"replace":"push"](h.publicHref,h.state,{ignoreBlocker:n}),this.history.subscribers.size||this.load({action:{type:i}})}return this._scroll.next=r.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:s,resetScroll:n,hashScrollIntoView:r,viewTransition:i,ignoreBlocker:o,...a}={})=>{const u=this.buildLocation({...a,_includeValidateSearch:!0});this._pendingLocation=u;const l=this.commitLocation({...u,viewTransition:i,replace:s,resetScroll:n,hashScrollIntoView:r,ignoreBlocker:o});return queueMicrotask(()=>{this._pendingLocation===u&&(this._pendingLocation=void 0)}),l},this.navigate=async({to:s,reloadDocument:n,href:r,publicHref:i,...o})=>{let a=!1;if(r)try{new URL(`${r}`),a=!0}catch{}if(a&&!n&&(n=!0),n){if(s!==void 0||!r){const l=this.buildLocation({to:s,...o});r=r??l.publicHref,i=i??l.publicHref}const u=!a&&i?i:r;if(Bt(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:s,_isNavigate:!0})},this.load=async s=>{this.updateLatestLocation(),s?.action&&(this._scroll.hash=s.action.type==="PUSH"||s.action.type==="REPLACE"),await Xa(this,s)},this.startViewTransition=s=>{const n=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,n&&typeof document.startViewTransition=="function"){let r;if(typeof n=="object"&&window.CSS?.supports?.("selector(:active-view-transition-type(a))")){const i=this.latestLocation,o=this.stores.resolvedLocation.get(),a=typeof n.types=="function"?n.types(Wt(i,o)):n.types;if(a===!1)return s();r={update:s,types:a}}else r=s;return document.startViewTransition(r).updateCallbackDone}return s()},this.invalidate=s=>{const n=this._committed,r=s?.filter,i=this._preloads,o=new Set([...n,...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(d=>o.has(d.id))&&(i.delete(l),a.push(l));const u=l=>{if(o.has(l.id)){const c=this.routesById[l.routeId],d={...l,invalid:!0,...(s?.forcePending||l.status==="error"||l.status==="notFound")&&Jn(c)?{status:"pending",error:void 0}:void 0};return l._flight=void 0,d}return l};this._committed=n.map(u);for(const[l,c]of this._cache)o.has(l)&&(c.invalid=!0,s?.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:s?.sync})},this.resolveRedirect=s=>{const n=s.headers.get("Location");if(s.options.href){if(n)try{const r=new URL(n);if(this.origin&&r.origin===this.origin){const i=r.pathname+r.search+r.hash;s.options.href=i,s.headers.set("Location",i)}}catch{}}else{const r=this.buildLocation(s.options).publicHref||"/";s.options.href=r,s.headers.set("Location",r)}if(s.options.href&&Bt(s.options.href,this.protocolAllowlist))throw new Error("Redirect blocked: unsafe protocol");return s.headers.get("Location")||s.headers.set("Location",s.options.href),s},this.clearCache=s=>{const n=this._cache,r=this._preloads,i=s?.filter,o=[],a=[];for(const[l,c]of n)(!i||i(c))&&(a.push(l),o.push(c));const u=[];for(const[l,c]of r??[])(!i||c.some(i))&&(u.push(l),o.push(...c));for(const l of a)n.delete(l);for(const l of u)r.delete(l);for(const l of o){const c=l._flight;l._flight=void 0,c&&!--c[2]&&(this._flights?.get(l.id)===c&&this._flights.delete(l.id),u.push(c[1]))}for(const l of u)l.abort()},this.loadRouteChunk=Ve,this.preloadRoute=s=>Ya(this,s),this.matchRoute=(s,n)=>{const r={...s,to:s.to?this.resolvePathWithBase(s.from||"",s.to):void 0,params:s.params||{},leaveParams:!0},i=this.buildLocation(r),o=this.stores.status.get()==="pending";if(n?.pending&&!o)return!1;const a=n?.pending??!o?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),u=la(i.pathname,n?.caseSensitive??!1,n?.fuzzy??!1,a.pathname,this.processedTree);return!u||s.params&&!ye(u.rawParams,s.params,{partial:!0})?!1:n?.includeSearch??!0?ye(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??xa,parseSearch:e.parseSearch??Ma,protocolAllowlist:e.protocolAllowlist??sa}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:s}){this.routesById=e,this.routesByPath=t,this.processedTree=s;const n=this.options.notFoundRoute;n&&(n.init({originalIndex:99999999999}),this.routesById[n.id]=n)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=di(e),this.routeBranchCache.set(e,t)),t}matchRoutesInternal(e,t){const[s,n,r]=this.getMatchedRoutes(e.pathname);let i=s,o=!1;(r?r.path!=="/"&&n["**"]:de(e.pathname))&&(this.options.notFoundRoute?i=[...i,this.options.notFoundRoute]:o=!0);const a=o?Ha(this.options.notFoundMode,i):void 0,u=new Array(i.length),l=this._committed,c=(h,f)=>{const p=l[f];return p?.routeId===h.id?p:h===this.options.notFoundRoute?l.find(g=>g.routeId===h.id):void 0};let d;for(let h=0;h<i.length;h++){const f=i[h],p=u[h-1];let g,m,v;{const F=p?.search??e.search,$=p?._strictSearch??void 0;try{const M=Nt(f.options.validateSearch,{...F})??void 0;g={...F,...M},m={...$,...M}}catch(M){let Ne=M;if(M instanceof Vt||(Ne=new Vt(M.message,{cause:M})),t?.throwOnError)throw Ne;g=F,m={},v=Ne}}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:b,usedParams:w}=Hn({path:f.fullPath,params:n,decoder:this.pathParamsDecoder,server:this.isServer}),R=f.id+b+C,y=c(f,h),_=this._cache.get(R)??(y?.id===R?y:void 0);d=_?._strictParams??Object.assign(w,d);let T;if(!_)try{Zn(f,d)}catch(F){if(Qe(F)||pi(F)?T=F:T=new Ba(F.message,{cause:F}),t?.throwOnError)throw T}const E=y?"stay":"enter";let x;if(_)x={..._,cause:E,search:Te(y?y.search:_.search,g),_strictSearch:m,searchError:v};else{const F=Jn(f)?"pending":"success";x={id:R,ssr:f.options.ssr,index:h,routeId:f.id,params:y?.params??d,_strictParams:d,pathname:b,updatedAt:Date.now(),search:y?Te(y.search,g):g,_strictSearch:m,searchError:v,status:F,isFetching:!1,error:void 0,paramsError:T,context:{},abortController:t?._controller??new AbortController,cause:E,loaderDeps:y?xe(y.loaderDeps,S):S,invalid:!1,preload:!1,staticData:f.options.staticData||{},fullPath:f.fullPath}}const L=a===f.id;x._notFound&&!L&&(x.error=void 0),x._notFound=L,u[h]=x}for(let h=0;h<u.length;h++){const f=u[h];f.params=f.cause==="stay"?Te(f.params,d):d,t?._controller&&(f.context={})}return u}matchRoutesLightweight(e){const t=ut(this.stores.ids.get()),s=t?this.stores.byRoute.get(t).get():void 0,n=s?.id,r=this.lightweightCache.get(e);if(r&&r[0]===n)return r[1];const[i,o]=this.getMatchedRoutes(e.pathname),a=ut(i),u={...e.search};for(const h of i)try{Object.assign(u,Nt(h.options.validateSearch,u))}catch{}const l=s&&s.routeId===a.id&&s.pathname===e.pathname;let c;if(l)c=s.params;else{const h=Object.assign(Object.create(null),o);for(const f of i)try{Zn(f,h)}catch{}c=h}const d=[i,a.fullPath,u,c];return this.lightweightCache.set(e,[n,d]),d}},Vt=class extends Error{},Ba=class extends Error{};function Nt(e,t){if(e==null)return{};if("~standard"in e){const s=e["~standard"].validate(t);if(s instanceof Promise)throw new Vt("Async validation not supported");if(s.issues)throw new Vt(JSON.stringify(s.issues,void 0,2),{cause:s});return s.value}return"parse"in e?e.parse(t):typeof e=="function"?e(t):{}}function Ga(e,t,s,n){const r=[];for(const o of s){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:d})=>{const h=d(a.preSearchFilters?a.preSearchFilters.reduce((f,p)=>p(f),c):c);return a.postSearchFilters?a.postSearchFilters.reduce((f,p)=>p(f),h):h};r.push(l)}const u=a.validateSearch;if(n&&u){const l=({search:c,next:d,meta:h})=>{const f=d(c);try{const p=Nt(u,f);if(h&&p)for(const g in p)g in f||(h.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=qe(t.search,a);return u&&(u.explicit=c),c}const l=(c,d)=>{if(d){const h=u||{};return{search:i(o+1,c,h),meta:h}}return i(o+1,c,u)};return r[o]({search:a,next:l,meta:u})};return i(0,e)}function Ha(e,t){if(e!=="root"){let s;for(let n=t.length-1;n>=0;n--){const r=t[n];if(r.options.notFoundComponent)return r.id;s||=r.children&&r.id}if(s)return s}return nt}function Yn(e,t){if(e===!1||e===null)return Object.create(null);if((e??!0)===!0)return t;const s=Object.assign(Object.create(null),t);return Object.assign(s,qe(e,s))}function Zn(e,t){const s=e.options.params?.parse??e.options.parseParams;s&&Object.assign(t,s(t))}function As(e,t){return e.options[t]?.preload?.()}function za(e,t){const s=As(e,"component");let n=As(e,"pendingComponent");return t&&(n?n=n.then(t):t()),s&&n?Promise.all([s,n]).then(()=>{}):s??n}function Ve(e,t,s){const n=()=>t===!1?void 0:t?As(e,t):za(e,s),r=e._lazy;if(r)return r===!0?n():r.then(n);if(!e.lazyFn)return n();const i=e.lazyFn().then(o=>{{const{id:a,...u}=o.options;Object.assign(e.options,u),e._lazy=!0}},o=>{throw e._lazy=void 0,o});return e._lazy=i,i.then(n)}function an(e){const t=e.findIndex(s=>s.status!=="success"||s._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var le=0,fe=1,Kt=2,X=3,Ce=[4];function ct(e){return typeof e[0]=="number"}function Oe(e,t){return t.aborted?Promise.race([Promise.reject(t),e]):new Promise((s,n)=>{const r=()=>n(t);t.addEventListener("abort",r,{once:!0}),Promise.resolve(e).then(s,n).finally(()=>t.removeEventListener("abort",r))})}function Fe(e,t){return e.routesById[t.routeId]}function dt(e,t,s){return pi(e)?[X,e]:Qe(e)?(e.routeId||=s,[Kt,e]):t?(typeof e?.then=="function"&&(e=new Error("A Promise was thrown",{cause:e})),[fe,e]):[le,e]}function ln(e,t){let s=dt(t,!0,e.id);if(s[0]!==fe)return s;try{e.options.onError?.(s[1])}catch(n){s=dt(n,!0,e.id)}return s}function rt(e,t,s,n,r){return r[0].signal.aborted?Ce:dn(e,t,s,ln(s,n),r)}async function Va(e,t,s,n,r,i){const[o,a]=t,u=s[0].signal,l=!!s[3];for(let c=s[6]??0;c<n;c++){const d=a[c],h=Fe(e,d);d.abortController=s[0];const f=a[c-1]?.context??e.options.context??{},p={params:d.params,location:o,navigate:S=>e.navigate({...S,_fromLocation:o}),buildLocation:e.buildLocation,cause:l?"preload":d.cause,abortController:s[0],preload:l,matches:a,routeId:h.id};try{const S=d._ctx||=h.options.context?h.options.context({...p,deps:d.loaderDeps,context:f})||{}:void 0;d.context={...f,...S}}catch(S){return he(e,d),[c,rt(e,t,h,S,s)]}if(u.aborted)return[c,Ce];const g=d.paramsError??d.searchError;if(g!==void 0)return he(e,d),[c,rt(e,t,h,g,s)];const m=h.options.beforeLoad;if(!m)continue;const v=d.status;c>=i&&(d.status="pending",s[7]?.());try{ht(e,d,"beforeLoad",s[0]);const S=await Oe(m({...p,search:d.search,context:d.context,...e.options.additionalContext}),u);if(u.aborted)return[c,Ce];const C=dn(e,t,h,dt(S,!1,h.id),s);if(C[0]!==le)return he(e,d),[c,C];d.context={...d.context,...S}}catch(S){return he(e,d),[c,rt(e,t,h,S,s)]}finally{d.status=v,ht(e,d,!1,s[0])}}r()}function un(e,t,s){if(!(!s||--s[2])){if(e._flights?.get(t.id)===s){const n=e._tx;if(n&&!n[0].signal.aborted&&!n[3].includes(t)&&n[3].some(r=>r.id===t.id)&&n[3].some(r=>r.isFetching==="beforeLoad"))return;e._flights.delete(t.id)}return s[1]}}function he(e,t){const s=t._flight;t._flight=void 0,un(e,t,s)?.abort()}function Q(e,t,s,n){const r=[];for(const i of t)if(!s?.includes(i)){const o=i._flight;if(i._flight=void 0,n&&o?.[2]===1&&e._flights?.get(i.id)===o&&s?.some(a=>a.id===i.id))o[2]=0;else{const a=un(e,i,o);a&&r.push(a)}}for(const i of r)i.abort()}function cn(e){for(const t of e){const s=t._flight;s&&s[2]++}}function ht(e,t,s,n){if(t.isFetching=s,n&&e._tx?.[0]!==n)return;const r=e.stores.byRoute.get(t.routeId),i=r?.get();i?.id===t.id&&r.set({...i,isFetching:s})}function vi(e,t,s,n,r,i,o){const a=t[0];return{params:s.params,location:a,navigate:u=>e.navigate({...u,_fromLocation:a}),cause:o?"preload":s.cause,abortController:r,preload:o,deps:s.loaderDeps,parentMatchPromise:i,context:s.context,route:n,...e.options.additionalContext}}async function er(e,t,s,n,r,i,o){const a=o[0],u=a.signal;if(u.aborted)return Ce;if(!r)return[le,void 0];let l=s._flight;ht(e,s,"loader",a);try{if(!l){const c=new AbortController;l=[Promise.resolve().then(()=>r(vi(e,t,s,n,c,i,!!o[3]))).then(d=>dt(d,!1,n.id),d=>dt(d,!0,n.id)).then(d=>(d[0]!==le&&e._flights?.get(s.id)===l&&(e._flights.delete(s.id),l[2]||c.abort()),d[0]===fe&&l[2]?ln(n,d[1]):d)),c,1],(e._flights??=new Map).set(s.id,l)}return s._flight=l,s.abortController=l[1],dn(e,t,n,await Oe(l[0],u),o)}catch(c){if(c!==u||!u.aborted)throw c;return he(e,s),Ce}finally{ht(e,s,!1,a)}}function tr(e,t,s){t[0]!==X&&(e.status="success",e.error=void 0,t[0]===le?(e.loaderData=t[1],e.invalid=!1,e.updatedAt=Date.now(),e.preload=s):e.invalid=!0)}function qa(e,t,s){const n=e._cache.get(t.id);if(n!==s||e._committed.some(i=>i.id===t.id&&i._flight===t._flight))return;const r={...t,_notFound:void 0,context:{}};r._flight&&r._flight[2]++,e._cache.set(t.id,r),n&&he(e,n)}function sr(e,t){return t[0]===fe||t[0]===Kt?{...e,status:t[0]===fe?"error":"notFound",error:t[1],_flight:void 0}:e}function Qa(e,t,s,n,r,i,o){const a=t[1][s],u=Fe(e,a),l=!!i[3],c=e._cache.get(a.id);let d,h=!1,f;try{if(a.status==="success"&&(d=u.options.shouldReload,typeof d=="function"&&(d=d(vi(e,t,a,u,i[0],r,l))),i[0].signal.aborted&&(f=Ce)),!f)if(a.status!=="success")h=!0;else{const L=l||a.preload?u.options.preloadStaleTime??e.options.defaultPreloadStaleTime??3e4:u.options.staleTime??e.options.defaultStaleTime??0;h=!!(a.invalid||d||d===void 0&&Date.now()-a.updatedAt>=L&&(i[5]||a.cause==="enter"||i[2].some(F=>F.routeId===a.routeId&&F.id!==a.id)))}}catch(L){a.invalid=!0,he(e,a),f=rt(e,t,u,L,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&&!h&&!l&&d===void 0?h=!0:h||(S=void 0);const C=!!(p&&h&&a.status==="success"&&!l&&!i[4]&&((g?void 0:p.staleReloadMode)??e.options.defaultStaleReloadMode)!=="blocking"),b=h&&v,w=b&&!C&&(a.status!=="success"||!!p),R=s>=o?i[7]:void 0,y=u.lazyFn&&u._lazy!==!0?R:void 0;if(b&&!p&&(a.invalid=!1,a.updatedAt=Date.now()),S&&S[2]++,w){const L=a._flight;a._flight=S,un(e,a,L)?.abort(),s>=o&&(a.status="pending"),R?.()}b||(a.isFetching=!1);const _=(f?Promise.resolve(f):w?er(e,t,a,u,m,r,i):Promise.resolve([le,a.loaderData])).then(L=>(w&&(tr(a,L,l),L[0]===le&&(p&&!i[0].signal.aborted&&qa(e,a,c),s>=o&&(a.status="pending"))),L)),T=Oe(Promise.resolve().then(()=>Ve(u,void 0,y)),i[0].signal).then(()=>{},L=>t[1].some((F,$)=>$<=s&&(F.status==="error"||F.status==="notFound"||F._notFound))?void 0:[s,rt(e,t,u,L,i)]).then(L=>_.then(F=>(w&&!L&&F[0]===le&&a.status==="pending"&&!i[0].signal.aborted&&(a.status="success",R?.()),L)));if(n.push([s,_,T]),!C)return _.then(L=>sr(a,L));const E={...a,status:"pending",preload:!1,_flight:S};a.invalid=!1,a.isFetching="loader";const x=er(e,t,E,u,m,r,i).then(L=>(a.isFetching=!1,tr(E,L,!1),L));return(t[2]??=[]).push([s,x,T,E]),x.then(L=>sr(E,L))}async function Os(e,t,s,n,r=0){const i=s?.[1][1];let o=i?.routeId?t.findIndex(a=>a.routeId===i.routeId):s?.[0]??t.length-1;o<0&&(o=0);for(let a=o;a>=0;a--){const u=Fe(e,t[a]);try{const l=Ve(u,!1);l&&await Oe(l,n)}catch(l){if(l===n&&n.aborted)throw l}if(u.options.notFoundComponent)return a}return i?.routeId?o:r}function Pe(e,t){t[2]&&(Q(e,t[2].map(s=>s[3])),t[2]=void 0)}async function nr(e,t,s,n){let r;try{await Promise.all(e.map(i=>i[1].then(async o=>{const a=i[0];if(!(n&&a>=await n)){if(o[0]>=X)throw[a,o];!r&&o[0]!==le&&(r=[a,o],await Promise.all((s??[]).map(u=>{if(!(u[0]<=a))return u[1].then(l=>{if(l[0]===X)throw[u[0],l]})})))}})))}catch(i){return i}return t??r}function dn(e,t,s,n,r,i){for(;n[0]===X;){const o=n[1],a=o.options;if(a.reloadDocument?r[3]:r[1]>=20)return n;try{return a.href&&a.reloadDocument?(e.resolveRedirect(o),n):[X,o,e.buildLocation({...a,_fromLocation:t[0],_includeValidateSearch:!0})]}catch(u){n=i?[fe,u]:ln(s,u),i=!0}}return n}async function Si(e,t,s,n,r,i){const o=t[1];let a=await r,u=!1;const l=o.findIndex(f=>f._notFound),c=f=>f[1][0]===Kt?Os(e,o,f,n.signal):f[0];let d=l<0?o.length:l;if((a?.[1][0]??0)>=X)d=0;else if(a){d=a[2]??=await c(a);for(const f of s){if(f[0]>=d)break;const p=await f[1];if(p[0]!==le&&p[0]<X&&!("loaderData"in o[f[0]])){a=[f[0],p],d=a[2]=await c(a);break}}}for(const f of s){if(f[0]>=d)break;const p=await f[2];if(p){a=p;break}}if((a?.[1][0]??0)>=X){const f=a[1];if(f[0]!==X||f[1].options.reloadDocument||f[2])return Pe(e,t),f;u=!0,a=[0,[fe,new Error("Too many redirects")]]}const h=a?a[2]??await c(a):l;if(h>=0){const f=a?.[1],p=f?.[0],g=o[h],m=f?.[1],v=()=>{f&&(g._notFound=void 0,p===fe?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=Fe(e,g);try{await Oe(f?Promise.resolve().then(()=>Ve(S,p===fe?"errorComponent":"notFoundComponent")):Promise.all([Ve(S),Ve(S,"notFoundComponent")]),n.signal)}catch(C){if(C===n.signal&&n.signal.aborted)return Pe(e,t),Ce}f?u&&(n.abort(),await Promise.all([...s.map(C=>C[1]),...s.map(C=>C[2]),...(t[2]??[]).map(C=>C[1])]),Pe(e,t),Q(e,o),v()):g.status="success"}return t}async function yi(e,t,s,n=0,r=t[1].length){const i=t[1];for(let o=n;o<r;o++){const a=i[o],u=Fe(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,d]=await Oe(Promise.all([u.head?.(l),u.scripts?.(l)]),s);a.meta=c?.meta,a.links=c?.links,a.headScripts=c?.scripts,a.styles=c?.styles,a.scripts=d}catch(l){if(l===s&&s.aborted)break;console.error(l)}if(a.status!=="success"||a._notFound)break}return t}async function Ii(e,t,s,n){const r=[t,s],i=n[0].signal;let o;try{const a=e.stores.matches.get();let u=s.findIndex(v=>v._notFound);if(e.options.notFoundMode!=="root"&&u>=0){const v=await Os(e,s,void 0,i,u);s[u]._notFound=void 0,s[v]._notFound=!0,u=v}let l=u<0?s.length:u+1,c=0;for(;c<l&&c!==u;){const v=s[c],S=n[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 d=[],h=n[6]??0;let f=h?Promise.resolve(s[h-1]):void 0;const p=()=>{for(let v=h;v<l&&!i.aborted;v++)f=Qa(e,r,v,d,f,n,c)},g=await Va(e,r,n,l,p,c);if(g){if(n[4]=!0,l=g[0],g[1][0]===Kt){const v=await Os(e,s,g,i);g[2]=v,l=Math.min(l,v+1)}else g[1][0]>=X&&(l=0);p()}if(!i.aborted&&!n[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=Si(e,r,d,n[0],nr(d,g,r[2]),n[7]);r[2]?.length&&(r[3]=nr(r[2],void 0,void 0,m.then(v=>ct(v)?0:an(s).length,()=>0))),o=await m}catch(a){if(Pe(e,r),a===i&&i.aborted)return Ce;throw a}return ct(o)?o:yi(e,o,i,n[6]===s.length?n[6]:0)}function Fs(e,t){if(e._tx!==t)return;const s=t[3],n=e.stores.matches.get();let r=e._pending;for(let i=0;i<s.length;i++){const o=s[i],a=o.status==="success"&&!o._notFound,u=n[i]?.id===o.id&&n[i]?.status==="pending";if(a&&!u)continue;const l=Fe(e,o),c=a||o.invalid?0:l.options.pendingMs??e.options.defaultPendingMs,d=l.options.pendingComponent??e.options.defaultPendingComponent;if(!d||typeof c!="number"||c===1/0){r&&(r[0]=t,r[2]=0,r[4]=!0);return}const h=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()+h:t[4]+c,void 0,u||void 0,d]),r[4]&&!f&&r[5]===d)return;if(r[5]=d,!r[4]){clearTimeout(r[3]);const m=r[2]-Date.now();if(m>0){r[3]=setTimeout(()=>Fs(e,t),m);return}r[2]=0}const p=s.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()+h),m));return}}function et(e,t){const s=e._pending;(e._tx===t||!e._tx?.[3].some(n=>n.id===s?.[1]))&&(clearTimeout(s?.[3]),e._pending=void 0)}async function rr(e,t){const s=e._pending;if(!s)return;clearTimeout(s[3]);const n=s[2]-Date.now();if(!s[4]||n<=0||!an(t[3]).some(i=>i.id===s[1]))return;let r;try{await Oe(new Promise(i=>{r=setTimeout(i,n)}),t[0].signal)}catch{}clearTimeout(r)}function Ri(e,t){e._committed=t,e.stores.setMatches(t)}function Wa(e,t,s,n){const r=e._committed,i=e._cache;for(const u of s)u.preload=!1,n&&(u._assetEnd=void 0);const o=an(s).length,a=new Map;{const u=Date.now();for(const l of[...r,...i.values()]){if(l.status!=="success"||s.some((d,h)=>d.id===l.id&&(h<o||d.status==="success")))continue;const c=Fe(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,Ri(e,s),Q(e,[...i.values(),...r],[...s,...a.values()]),ja(e,r,s,t)}async function Ct(e,t){let s=e._tx;for(;s&&s!==t;){if(await s[5],e._tx===s)return;s=e._tx}}function Ci(e,t,s){const n=s[1].options,r=s[2];if(!r)return e.navigate({...n,replace:!0,ignoreBlocker:!0});if(n.reloadDocument)return e.navigate({href:r.publicHref,reloadDocument:!0,replace:!0,ignoreBlocker:!0});r._redirects=t[1]+1,e._pendingLocation=r;const i=e.commitLocation({...r,viewTransition:n.viewTransition,replace:!0,resetScroll:n.resetScroll,hashScrollIntoView:n.hashScrollIntoView,ignoreBlocker:!0});return queueMicrotask(()=>{e._pendingLocation===r&&(e._pendingLocation=void 0)}),i}async function Ka(e,t,s,n,r){const i=s.map(u=>({...u}));cn(i);for(const u of n)he(e,i[u[0]]),i[u[0]]=u[3];const o=[t[2],i];let a;try{a=await Si(e,o,n,t[0],r)}catch(u){throw Q(e,i),u}if(ct(a)){Q(e,i),a[0]===X&&e._tx===t&&e._committed===s&&await Ci(e,t,a);return}if(await yi(e,a,t[0].signal),e._tx!==t||e._committed!==s){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),he(e,l))}Ri(e,i),Q(e,s,i)}async function Ja(e,t,s,n,r,i){const o=await Ii(e,t[2],t[3],[t[0],t[1],e._committed,void 0,r,s,i,n]);if(ct(o)){const d=o[0]===X&&e._tx===t;if((!d||o[1].options.reloadDocument)&&et(e,t),Q(e,t[3]),t[3]=[],!d)return;if(e._tx!==t){et(e,t);return}await Ci(e,t,o);return}const a=o[1];if(e._tx===t&&await rr(e,t),e._tx!==t){et(e,t),Q(e,a),Pe(e,o);return}const u=t[2],l=Wt(u,e.stores.resolvedLocation.get()),c=o[2];await e.startViewTransition(async()=>{if(e._tx===t&&await rr(e,t),e._tx!==t){et(e,t),Q(e,a),Pe(e,o);return}const d=()=>{et(e,t),Wa(e,t,a,i),e._tx===t&&(e.emit({type:"onLoad",...l}),e._tx===t&&e.emit({type:"onBeforeRouteMount",...l}))},h=await e.startTransition(d,a);if(e._tx!==t){Pe(e,o);return}c?.length&&Ka(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}),h&&e._tx===t&&e.emit({type:"onRendered",...l})}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0)})}async function Xa(e,t){const s=e._tx,n=e.stores.resolvedLocation.get(),r=n??e.stores.location.get(),i=e.latestLocation,o=e._pendingLocation,a=o?.href===i.href?o._redirects??0:0,u=e._handoff,l=u?.[0](),c=new AbortController,d=e._preflight;if(e._preflight=c,l||u?.[1](),d?.abort(),!c.signal.aborted){const b=Wt(i,n);e.emit({type:"onBeforeNavigate",...b}),c.signal.aborted||e.emit({type:"onBeforeLoad",...b})}if(c.signal.aborted){await Ct(e,s);return}const h=r.href===i.href;let f=c;const p=e.matchRoutes(i,{_controller:c});cn(p);const g=l?u[1](p):void 0;if(g?f=l:l?.abort(),c.signal.aborted){Q(e,p),await Ct(e,s);return}e._preflight=void 0;let m;const v=()=>Ja(e,C,h,()=>Fs(e,C),t?.sync,g),S=t?.sync?new Promise(b=>m=b):Promise.resolve().then(v).then(),C=[f,a,i,p,Date.now(),S];if(e._tx=C,s){for(const b of e.stores.matches.get()){if(e._tx!==C)break;b.isFetching&&ht(e,b,!1)}s[0].abort(),Q(e,s[3],C[3],!0)}if(e._tx!==C){Q(e,C[3]),C[3]=[],m?.(),await Ct(e,C);return}e.batch(()=>{e.stores.status.set("pending"),e.stores.location.set(i)}),(g||!e._committed.length&&p[0]?.status!=="success"&&!p.some(b=>b._notFound))&&Fs(e,C),m?.(v()),await S,await Ct(e,C)}async function Ya(e,t){let s=e.buildLocation(t);for(let n=0;;n++){const r=e._committed,i=new AbortController;let o,a,u;try{try{o=e.matchRoutes(s,{_controller:i}),cn(o),a=(e._preloads??=new Map).set(i,o),u=await Ii(e,s,o,[i,n,r,!0])}finally{a&&(a=a.delete(i),Q(e,o)),i.abort()}if(!ct(u))return u[1];if(!a||u.length<3)return;s=u[2]}catch(l){Qe(l)||console.error(l);return}}}var Za="Error preloading route! ☝️",wi=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 s=this.options,n=!s?.path&&!s?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=nt:this.parentRoute||nn();let r=n?nt:s?.path;r&&r!=="/"&&(r=hi(r));const i=s?.id||r;let o=n?nt:Ot([this.parentRoute.id==="__root__"?"":this.parentRoute.id,i]);r==="__root__"&&(r="/"),o!=="__root__"&&(o=Ot(["/",o]));const a=o==="__root__"?"/":Ot([this.parentRoute.fullPath,r]);this._path=r,this._id=o,this._fullPath=a,this._to=de(a)},this.addChildren=t=>this._addFileChildren(t),this._addFileChildren=t=>(Array.isArray(t)&&(this.children=t),typeof t=="object"&&t!==null&&(this.children=Object.values(t)),this),this._addFileTypes=()=>this,this.updateLoader=t=>(Object.assign(this.options,t),this),this.update=t=>(Object.assign(this.options,t),this),this.lazy=t=>(this.lazyFn=t,this),this.redirect=t=>Oa({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.")}},el=class extends wi{constructor(e){super(e)}},hn=class extends I.Component{constructor(...e){super(...e),this.state={error:null},this.reset=()=>{this.setState({error:null})}}static getDerivedStateFromProps(e,t){const s=e.getResetKey();return t.error&&t.resetKey!==s?{resetKey:s,error:null}:{resetKey:s}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){const e=this.state.error;return e?I.createElement(this.props.errorComponent??tl,{error:e,reset:this.reset}):this.props.children}};function tl({error:e}){const[t,s]=I.useState(!1);return(0,O.jsxs)("div",{style:{padding:".5rem",maxWidth:"100%"},children:[(0,O.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:".5rem"},children:[(0,O.jsx)("strong",{style:{fontSize:"1rem"},children:"Something went wrong!"}),(0,O.jsx)("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:()=>s(n=>!n),children:t?"Hide Error":"Show Error"})]}),(0,O.jsx)("div",{style:{height:".25rem"}}),t?(0,O.jsx)("div",{children:(0,O.jsx)("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"},children:e.message?(0,O.jsx)("code",{children:e.message}):null})}):null]})}function sl({children:e,fallback:t=null}){return(0,O.jsx)(I.Fragment,{children:bi()?e:t})}function bi(){return I.useSyncExternalStore(nl,()=>!0,()=>!1)}function nl(){return()=>{}}var Ei=I.createContext(null);function ee(e){return I.useContext(Ei)}var Jt=I.createContext(void 0),rl=I.createContext(void 0),j=(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))(j||{});function il({update:e,notify:t,unwatched:s}){return{link:n,unlink:r,propagate:i,checkDirty:o,shallowPropagate:a};function n(l,c,d){const h=c.depsTail;if(h!==void 0&&h.dep===l)return;const f=h!==void 0?h.nextDep:c.deps;if(f!==void 0&&f.dep===l){f.version=d,c.depsTail=f;return}const p=l.subsTail;if(p!==void 0&&p.version===d&&p.sub===c)return;const g=c.depsTail=l.subsTail={version:d,dep:l,sub:c,prevDep:h,nextDep:f,prevSub:p,nextSub:void 0};f!==void 0&&(f.prevDep=g),h!==void 0?h.nextDep=g:c.deps=g,p!==void 0?p.nextSub=g:l.subs=g}function r(l,c=l.sub){const d=l.dep,h=l.prevDep,f=l.nextDep,p=l.nextSub,g=l.prevSub;return f!==void 0?f.prevDep=h:c.depsTail=h,h!==void 0?h.nextDep=f:c.deps=f,p!==void 0?p.prevSub=g:d.subsTail=g,g!==void 0?g.nextSub=p:(d.subs=p)===void 0&&s(d),f}function i(l){let c=l.nextSub,d;e:do{const h=l.sub;let f=h.flags;if(f&60?f&12?f&4?!(f&48)&&u(l,h)?(h.flags=f|40,f&=1):f=0:h.flags=f&-9|32:f=0:h.flags=f|32,f&2&&t(h),f&1){const p=h.subs;if(p!==void 0){const g=(l=p).nextSub;g!==void 0&&(d={value:c,prev:d},c=g);continue}}if((l=c)!==void 0){c=l.nextSub;continue}for(;d!==void 0;)if(l=d.value,d=d.prev,l!==void 0){c=l.nextSub;continue e}break}while(!0)}function o(l,c){let d,h=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)&&(d={value:l,prev:d}),l=p.deps,c=p,++h;continue}if(!f){const m=l.nextDep;if(m!==void 0){l=m;continue}}for(;h--;){const m=c.subs,v=m.nextSub!==void 0;if(v?(l=d.value,d=d.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,d=c.flags;(d&48)===32&&(c.flags=d|16,(d&6)===2&&t(c))}while((l=l.nextSub)!==void 0)}function u(l,c){let d=c.depsTail;for(;d!==void 0;){if(d===l)return!0;d=d.prevDep}return!1}}function ol(e,t,s){const n=typeof e=="object",r=n?e:void 0;return{next:(n?e.next:e)?.bind(r),error:(n?e.error:t)?.bind(r),complete:(n?e.complete:s)?.bind(r)}}var Ls=[],kt=0,{link:ir,unlink:al,propagate:ll,checkDirty:_i,shallowPropagate:or}=il({update(e){return e._update()},notify(e){Ls[Ns++]=e,e.flags&=~j.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=j.Mutable|j.Dirty,qt(e))}}),wt=0,Ns=0,ae,ks=0;function ul(e){try{++ks,e()}finally{--ks||Ti()}}function qt(e){const t=e.depsTail;let s=t!==void 0?t.nextDep:e.deps;for(;s!==void 0;)s=al(s,e)}function Ti(){if(!(ks>0)){for(;wt<Ns;){const e=Ls[wt];Ls[wt++]=void 0,e.notify()}wt=0,Ns=0}}function ar(e,t){const s=typeof e=="function",n=e,r={_snapshot:s?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:s?j.None:j.Mutable,get(){return ae!==void 0&&ir(r,ae,kt),r._snapshot},subscribe(i){const o=ol(i),a={current:!1},u=cl(()=>{r.get(),a.current?o.next?.(r._snapshot):a.current=!0});return{unsubscribe:()=>{u.stop()}}},_update(i){const o=ae,a=t?.compare??Object.is;if(s)ae=r,++kt,r.depsTail=void 0;else if(i===void 0)return!1;s&&(r.flags=j.Mutable|j.RecursedCheck);try{const u=r._snapshot,l=typeof i=="function"?i(u):i===void 0&&s?n(u):i;return u===void 0||!a(u,l)?(r._snapshot=l,!0):!1}finally{ae=o,s&&(r.flags&=~j.RecursedCheck),qt(r)}}};return s?(r.flags=j.Mutable|j.Dirty,r.get=function(){const i=r.flags;if(i&j.Dirty||i&j.Pending&&_i(r.deps,r)){if(r._update()){const o=r.subs;o!==void 0&&or(o)}}else i&j.Pending&&(r.flags=i&~j.Pending);return ae!==void 0&&ir(r,ae,kt),r._snapshot}):r.set=function(i){if(r._update(i)){const o=r.subs;o!==void 0&&(ll(o),or(o),Ti())}},r}function cl(e){const t=()=>{const n=ae;ae=s,++kt,s.depsTail=void 0,s.flags=j.Watching|j.RecursedCheck;try{return e()}finally{ae=n,s.flags&=~j.RecursedCheck,qt(s)}},s={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:j.Watching|j.RecursedCheck,notify(){const n=this.flags;n&j.Dirty||n&j.Pending&&_i(this.deps,this)?t():this.flags=j.Watching},stop(){this.flags=j.None,this.depsTail=void 0,qt(this)}};return t(),s}var dl=Je((e=>{var t=Js();function s(h,f){return h===f&&(h!==0||1/h===1/f)||h!==h&&f!==f}var n=typeof Object.is=="function"?Object.is:s,r=t.useState,i=t.useEffect,o=t.useLayoutEffect,a=t.useDebugValue;function u(h,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})},[h,p,f]),i(function(){return l(m)&&v({inst:m}),h(function(){l(m)&&v({inst:m})})},[h]),a(p),p}function l(h){var f=h.getSnapshot;h=h.value;try{var p=f();return!n(h,p)}catch{return!0}}function c(h,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:u;e.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d})),hl=Je(((e,t)=>{t.exports=dl()})),fl=Je((e=>{var t=Js(),s=hl();function n(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var r=typeof Object.is=="function"?Object.is:n,i=s.useSyncExternalStore,o=t.useRef,a=t.useEffect,u=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(c,d,h,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,b=y,y=f(y),p!==void 0&&m.hasValue){var _=m.value;if(p(_,y))return w=_}return w=y}if(_=w,r(b,y))return _;var T=f(y);return p!==void 0&&p(_,T)?(b=y,_):(b=y,w=T)}var C=!1,b,w,R=h===void 0?null:h;return[function(){return S(d())},R===null?void 0:function(){return S(R())}]},[d,h,f,p]);var v=i(c,g[0],g[1]);return a(function(){m.hasValue=!0,m.value=v},[v]),l(v),v}})),gl=Je(((e,t)=>{t.exports=fl()})),pl=gl();function ml(e,t){return e===t}function ge(e,t,s=ml){const n=(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,pl.useSyncExternalStoreWithSelector)(n,r,r,t,s)}var lr={};function Mi(e,t){const s=I.useRef();return n=>{const r=e?.select?e.select(n):n;return e?.structuralSharing??t.options.defaultStructuralSharing?s.current=xe(s.current,r):r}}function Le(e){const t=ee(),s=I.useContext(e.from?rl:Jt),n=e.from??s,r=t.stores.getMatchStore(n),i=Mi(e,t),o=ge(r,a=>a?i(a):lr);if(o!==lr)return o;(e.shouldThrow??!0)&&nn()}function xi(e){return Le({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function Pi(e){const{select:t,...s}=e;return Le({...s,select:n=>t?t(n.loaderDeps):n.loaderDeps})}function Ai(e){return Le({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const s=e.strict===!1?t.params:t._strictParams;return e.select?e.select(s):s}})}function Oi(e){return Le({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function fn(e){const t=ee();return I.useCallback(s=>t.navigate({...s,from:s.from??e?.from}),[e?.from,t])}function nh(e){const t=ee(),s=fn(),n=I.useRef(null);return sn(()=>{n.current!==e&&(s(e),n.current=e)},[t,e,s]),null}function Fi(e){return Le({...e,select:t=>e.select?e.select(t.context):t.context})}function ls(e){const t=I.useRef(e);return ye(t.current,e,{ignoreUndefined:!1})||(t.current=e),t.current}function vl(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function Sl(e,t,s){if(e?.external)return Bt(e.href,s)?void 0:e.href;if(!El(t)&&!(typeof t!="string"||t.indexOf(":")===-1))try{return new URL(t),Bt(t,s)?void 0:t}catch{}}function yl(e,t,s,n,r,i){if(i)return!1;if(s?.exact){if(!pa(e.pathname,t.pathname,n))return!1}else{const o=Ht(e.pathname,n),a=Ht(t.pathname,n);if(!(o.startsWith(a)&&(o.length===a.length||o[a.length]==="/")))return!1}return(s?.includeSearch??!0)&&!ye(e.search,t.search,{partial:!s?.exact,ignoreUndefined:!s?.explicitUndefined})?!1:s?.includeHash?r&&e.hash===t.hash:!0}function Il(e,t){const s=ee(),n=Jo(t),{activeProps:r,inactiveProps:i,activeOptions:o,to:a,preload:u,preloadDelay:l,preloadIntentProximity:c,hashScrollIntoView:d,replace:h,startTransition:f,resetScroll:p,viewTransition:g,children:m,target:v,disabled:S,style:C,className:b,onClick:w,onBlur:R,onFocus:y,onMouseEnter:_,onMouseLeave:T,onTouchStart:E,ignoreBlocker:x,params:L,search:F,hash:$,state:M,mask:Ne,reloadDocument:Rn,unsafeRelative:Cn,from:wn,_fromLocation:bn,...gt}=e,pt=bi(),es=ls(e.search),ts=ls(e.params),mt=ls(o),Ee=I.useMemo(()=>e,[s,e.from,e._fromLocation,e.hash,e.to,es,ts,e.state,e.mask,e.unsafeRelative]),ss=I.useCallback(B=>{const re=s.buildLocation({_fromLocation:B,...Ee}),$e=bl(re.maskedLocation?re.maskedLocation.publicHref:re.publicHref,re.maskedLocation?re.maskedLocation.external:re.external,s.history,S),rs=Sl($e,a,s.protocolAllowlist);return[$e?.href,rs,yl(B,re,mt,s.basepath,pt,rs!==void 0)]},[mt,S,pt,Ee,s,a]),[ns,Ye,se]=ge(s.stores.location,ss,vl),W=se?qe(r,{})??Rl:us,ke=se?us:qe(i,{})??us,vt=[b,W.className,ke.className].filter(Boolean).join(" "),k=(C||W.style||ke.style)&&{...C,...W.style,...ke.style},D=I.useRef(!1),q=e.reloadDocument||Ye||S?!1:u??s.options.defaultPreload,ne=l??s.options.defaultPreloadDelay??0,U=I.useCallback(()=>{s.preloadRoute(Ee).catch(B=>{console.warn(B),console.warn(Za)})},[s,Ee]),De=I.useCallback(B=>{if(!B){cs(n);return}if(!(B.isIntersecting??q==="intent")){B.isIntersecting===!1&&cs(n);return}if(!ne){U();return}it.has(n)||it.set(n,setTimeout(()=>{it.delete(n),U()},ne))},[U,n,q,ne]);Ko(n,De,q!=="viewport"),I.useEffect(()=>{D.current||q==="render"&&(U(),D.current=!0)},[U,q]);const _e=B=>{const re=B.currentTarget.getAttribute("target"),$e=v!==void 0?v:re;!S&&!(B.metaKey||B.altKey||B.ctrlKey||B.shiftKey)&&!B.defaultPrevented&&(!$e||$e==="_self")&&B.button===0&&(B.preventDefault(),s.navigate({...Ee,replace:h,resetScroll:p,hashScrollIntoView:d,startTransition:f,viewTransition:g,ignoreBlocker:x}))};if(Ye)return{...gt,ref:n,href:Ye,...m&&{children:m},...v&&{target:v},...S&&{disabled:S},...C&&{style:C},...b&&{className:b},...w&&{onClick:w},...R&&{onBlur:R},...y&&{onFocus:y},..._&&{onMouseEnter:_},...T&&{onMouseLeave:T},...E&&{onTouchStart:E}};const N=()=>{q==="intent"&&U()},K=()=>{q==="intent"&&cs(n)};return{...gt,...W,...ke,href:ns,ref:n,onClick:je([w,_e]),onBlur:je([R,K]),onFocus:je([y,De]),onMouseEnter:je([_,De]),onMouseLeave:je([T,K]),onTouchStart:je([E,N]),disabled:!!S,target:v,...k&&{style:k},...vt&&{className:vt},...S&&Cl,...se&&wl}}var us={},Rl={className:"active"},Cl={role:"link","aria-disabled":!0},wl={"data-status":"active","aria-current":"page"},it=new WeakMap,cs=e=>{clearTimeout(it.get(e)),it.delete(e)},je=e=>t=>{for(const s of e)if(s){if(t.defaultPrevented)return;s(t)}};function bl(e,t,s,n){if(!n)return t?{href:e,external:!0}:{href:s.createHref(e)||"/",external:!1}}function El(e){if(typeof e!="string")return!1;const t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var Li=I.forwardRef((e,t)=>{const{_asChild:s,...n}=e,{type:r,...i}=Il(n,t),o=typeof n.children=="function"?n.children({isActive:i["data-status"]==="active"}):n.children;if(!s){const{disabled:a,...u}=i;return I.createElement("a",u,o)}return I.createElement(s,i,o)}),_l=class extends wi{constructor(e){super(e),this.useMatch=t=>Le({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>Fi({...t,from:this.id}),this.useSearch=t=>Oi({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>Ai({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>Pi({...t,from:this.id}),this.useLoaderData=t=>xi({...t,from:this.id}),this.useNavigate=()=>fn({from:this.fullPath}),this.Link=I.forwardRef((t,s)=>(0,O.jsx)(Li,{ref:s,from:this.fullPath,...t}))}};function Tl(e){return new _l(e)}var Ml=class extends el{constructor(e){super(e),this.useMatch=t=>Le({select:t?.select,from:this.id,structuralSharing:t?.structuralSharing}),this.useRouteContext=t=>Fi({...t,from:this.id}),this.useSearch=t=>Oi({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useParams=t=>Ai({select:t?.select,structuralSharing:t?.structuralSharing,from:this.id}),this.useLoaderDeps=t=>Pi({...t,from:this.id}),this.useLoaderData=t=>xi({...t,from:this.id}),this.useNavigate=()=>fn({from:this.fullPath}),this.Link=I.forwardRef((t,s)=>(0,O.jsx)(Li,{ref:s,from:this.fullPath,...t}))}};function rh(e){return new Ml(e)}function ih(e){return t=>{const s=Tl(t);return s.isRoot=!1,s}}function oh(e,t){let s,n,r;const i=()=>(s||(r=void 0,s=e().then(a=>{s=void 0,o.preload=void 0,n=a[t??"default"]}).catch(a=>{s=void 0,r=a})),s),o=function(u){if(r){if(Zo(r)&&typeof sessionStorage<"u"){const l=`tanstack_router_reload:${r.message}`;if(!sessionStorage.getItem(l))throw sessionStorage.setItem(l,"1"),window.location.reload(),new Promise(()=>{})}throw r}if(!n)if(Dn)Dn(i());else throw i();return I.createElement(n,u)};return o.preload=i,o}function xl(e){const t=ee(),s=`not-found-${ge(t.stores.location,n=>n.pathname)}-${ge(t.stores.status,n=>n)}`;return(0,O.jsx)(hn,{getResetKey:()=>s,onCatch:(n,r)=>{if(Qe(n))e.onCatch?.(n,r);else throw n},errorComponent:({error:n})=>{if(Qe(n))return e.fallback?.(n);throw n},children:e.children})}function Pl(){return(0,O.jsx)("p",{children:"Not Found"})}function Ge(e){return(0,O.jsx)(O.Fragment,{children:e.children})}function Ni(e,t,s){return t.options.notFoundComponent?(0,O.jsx)(t.options.notFoundComponent,{...s}):e.options.defaultNotFoundComponent?(0,O.jsx)(e.options.defaultNotFoundComponent,{...s}):(0,O.jsx)(Pl,{})}function Xt(e,t){const s=t?.options.pendingComponent??e.options.defaultPendingComponent;return s?(0,O.jsx)(s,{}):null}var Al=(e,t)=>e[0]===t[0]&&e[1]===t[1],ki=(e,t,s)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||s===!1||s==="data-only"||!e.ssr,Di=I.memo(function({routeId:t}){const s=ee();return(0,O.jsx)(Ol,{router:s,match:ge(s.stores.getMatchStore(t),n=>n)})});function Ol({router:e,match:t}){const s=e.routesById[t.routeId],n=Xt(e,s),r=s.options.errorComponent??e.options.defaultErrorComponent,i=s.options.onCatch??e.options.defaultOnCatch,o=s.isRoot?s.options.notFoundComponent??e.options.notFoundRoute?.options.component:s.options.notFoundComponent,a=t.ssr===!1||t.ssr==="data-only",u=ki(e,s,t.ssr)&&(s.options.wrapInSuspense??n??(s.options.errorComponent?.preload||a))?I.Suspense:Ge,l=r?hn:Ge,c=o?xl:Ge;return(0,O.jsxs)(s.isRoot?s.options.shellComponent??Ge:Ge,{children:[(0,O.jsx)(Jt.Provider,{value:t.routeId,children:(0,O.jsx)(u,{fallback:n,children:(0,O.jsx)(l,{getResetKey:()=>t,errorComponent:r,onCatch:(d,h)=>{if(Qe(d))throw d.routeId??=t.routeId,d;i?.(d,h)},children:(0,O.jsx)(c,{fallback:d=>{if(d.routeId??=t.routeId,d.routeId!==t.routeId)throw d;return I.createElement(o,d)},children:a?(0,O.jsx)(sl,{fallback:n,children:(0,O.jsx)(ur,{match:t})}):(0,O.jsx)(ur,{match:t})})})})}),null]})}var ur=I.memo(function({match:t}){const s=ee(),n=t.routeId,r=s.routesById[n],i=I.useMemo(()=>{const a=(r.options.remountDeps??s.options.defaultRemountDeps)?.({routeId:n,loaderDeps:t.loaderDeps,params:t._strictParams,search:t._strictSearch});return a?JSON.stringify(a):void 0},[n,t.loaderDeps,t._strictParams,t._strictSearch,r.options.remountDeps,s.options.defaultRemountDeps]),o=I.useMemo(()=>{const a=r.options.component??s.options.defaultComponent;return a?(0,O.jsx)(a,{},i):(0,O.jsx)(Fl,{})},[i,r.options.component,s.options.defaultComponent]);if(t.status==="pending"){if(s.ssr&&!ki(s,r,t.ssr))return o;if(s._tx)throw s._tx[5];return Xt(s,r)}if(t.status==="notFound")return Ni(s,r,t.error);if(t.status==="error")throw t.error;return o}),Fl=I.memo(function(){const t=ee(),s=I.useContext(Jt);let n,r,i;{const a=t.stores.getMatchStore(s);[n,r]=ge(a,u=>[!!u._notFound,u.error],Al),i=ge(t.stores.ids,u=>u[u.indexOf(s)+1])}if(n)return Ni(t,t.routesById[s],r);if(!i)return null;const o=(0,O.jsx)(Di,{routeId:i});return s==="__root__"?(0,O.jsx)(I.Suspense,{fallback:Xt(t),children:o}):o});function $i(e,t){const s=e[1];e.length=0,s?.(t)}function Ll({t:e}){const t=ee(),s=t._rendered??=[];return t.startTransition=(n,r)=>new Promise(i=>{$i(s,!1),s.push(r,i),e(t),I.startTransition(n)}),sn(()=>{const n=t.history.subscribe(t.load);t.updateLatestLocation();const r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(de(r.publicHref)!==de(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),n;const o=t.stores.resolvedLocation.get();return o?.href===r.href&&o.state.__TSR_key===r.state.__TSR_key?s.push(t.stores.matches.get(),a=>{a&&t.emit({type:"onRendered",...Wt(o,o)})}):t._tx||t.load({sync:!0}).catch(console.error),n},[t,t.history]),null}function Nl(){const e=ee(),t=e.routesById[nt],s=Xt(e,t),n=e.ssr?Ge:I.Suspense,r=(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Ll,{t:I.useState()[1]}),(0,O.jsx)(n,{fallback:s,children:(0,O.jsx)(kl,{})})]});return e.options.InnerWrap?(0,O.jsx)(e.options.InnerWrap,{children:r}):r}function kl(){const e=ee(),t=e._rendered,s=ge(e.stores.matches,o=>t[0]??o),n=s[0],r=n?.routeId;sn(()=>{t[0]===s&&$i(t,!0)},[t,s]);const i=r?(0,O.jsx)(Di,{routeId:r}):null;return(0,O.jsx)(Jt.Provider,{value:r,children:e.options.disableGlobalCatchBoundary?i:(0,O.jsx)(hn,{getResetKey:()=>n,onCatch:void 0,children:i})})}var Dl=e=>({createMutableStore:ar,createReadonlyStore:ar,batch:ul}),ah=e=>new $l(e),$l=class extends Ua{constructor(e){super(e,Dl)}};function jl({router:e,children:t,...s}){oi(s)&&e.update({...e.options,...s,context:{...e.options.context,...s.context}});const n=(0,O.jsx)(Ei.Provider,{value:e,children:t});return e.options.Wrap?(0,O.jsx)(e.options.Wrap,{children:n}):n}function lh({router:e,...t}){return(0,O.jsx)(jl,{router:e,...t,children:(0,O.jsx)(Nl,{})})}function uh(e){const t=ee();return ge(t.stores.location,Mi(e,t))}function me(e,t){return typeof e=="function"?e(t):e}function Y(e,t){return s=>{t.setState(n=>({...n,[e]:me(s,n[e])}))}}function Yt(e){return e instanceof Function}function Ul(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function Bl(e,t){const s=[],n=r=>{r.forEach(i=>{s.push(i);const o=t(i);o!=null&&o.length&&n(o)})};return n(e),s}function P(e,t,s){let n=[],r;return i=>{let o;s.key&&s.debug&&(o=Date.now());const a=e(i);if(!(a.length!==n.length||a.some((l,c)=>n[c]!==l)))return r;n=a;let u;if(s.key&&s.debug&&(u=Date.now()),r=t(...a),s==null||s.onChange==null||s.onChange(r),s.key&&s.debug&&s!=null&&s.debug()){const l=Math.round((Date.now()-o)*100)/100,c=Math.round((Date.now()-u)*100)/100,d=c/16,h=(f,p)=>{for(f=String(f);f.length<p;)f=" "+f;return f};console.info(`%c⏱ ${h(c,5)} /${h(l,5)} ms`,`
|
|
2
|
-
font-size: .6rem;
|
|
3
|
-
font-weight: bold;
|
|
4
|
-
color: hsl(${Math.max(0,Math.min(120-120*d,120))}deg 100% 31%);`,s?.key)}return r}}function A(e,t,s,n){return{debug:()=>{var r;return(r=e?.debugAll)!=null?r:e[t]},key:!1,onChange:n}}function Gl(e,t,s,n){const r=()=>{var o;return(o=i.getValue())!=null?o:e.options.renderFallbackValue},i={id:`${t.id}_${s.id}`,row:t,column:s,getValue:()=>t.getValue(n),renderValue:r,getContext:P(()=>[e,s,t,i],(o,a,u,l)=>({table:o,column:a,row:u,cell:l,getValue:l.getValue,renderValue:l.renderValue}),A(e.options,"debugCells","cell.getContext"))};return e._features.forEach(o=>{o.createCell==null||o.createCell(i,s,t,e)},{}),i}function Hl(e,t,s,n){var r,i;const o={...e._getDefaultColumnDef(),...t},a=o.accessorKey;let u=(r=(i=o.id)!=null?i:a?typeof String.prototype.replaceAll=="function"?a.replaceAll(".","_"):a.replace(/\./g,"_"):void 0)!=null?r:typeof o.header=="string"?o.header:void 0,l;if(o.accessorFn?l=o.accessorFn:a&&(a.includes(".")?l=d=>{let h=d;for(const p of a.split(".")){var f;h=(f=h)==null?void 0:f[p]}return h}:l=d=>d[o.accessorKey]),!u)throw new Error;let c={id:`${String(u)}`,accessorFn:l,parent:n,depth:s,columnDef:o,columns:[],getFlatColumns:P(()=>[!0],()=>{var d;return[c,...(d=c.columns)==null?void 0:d.flatMap(h=>h.getFlatColumns())]},A(e.options,"debugColumns","column.getFlatColumns")),getLeafColumns:P(()=>[e._getOrderColumnsFn()],d=>{var h;return(h=c.columns)!=null&&h.length?d(c.columns.flatMap(f=>f.getLeafColumns())):[c]},A(e.options,"debugColumns","column.getLeafColumns"))};for(const d of e._features)d.createColumn==null||d.createColumn(c,e);return c}var H="debugHeaders";function cr(e,t,s){var n;let r={id:(n=s.id)!=null?n:t.id,column:t,index:s.index,isPlaceholder:!!s.isPlaceholder,placeholderId:s.placeholderId,depth:s.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],o=a=>{a.subHeaders&&a.subHeaders.length&&a.subHeaders.map(o),i.push(a)};return o(r),i},getContext:()=>({table:e,header:r,column:t})};return e._features.forEach(i=>{i.createHeader==null||i.createHeader(r,e)}),r}var zl={createTable:e=>{e.getHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n,r)=>{var i,o;const a=(i=n?.map(c=>s.find(d=>d.id===c)).filter(Boolean))!=null?i:[],u=(o=r?.map(c=>s.find(d=>d.id===c)).filter(Boolean))!=null?o:[],l=s.filter(c=>!(n!=null&&n.includes(c.id))&&!(r!=null&&r.includes(c.id)));return bt(t,[...a,...l,...u],e)},A(e.options,H,"getHeaderGroups")),e.getCenterHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n,r)=>(s=s.filter(i=>!(n!=null&&n.includes(i.id))&&!(r!=null&&r.includes(i.id))),bt(t,s,e,"center")),A(e.options,H,"getCenterHeaderGroups")),e.getLeftHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,s,n)=>{var r;return bt(t,(r=n?.map(i=>s.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"left")},A(e.options,H,"getLeftHeaderGroups")),e.getRightHeaderGroups=P(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,s,n)=>{var r;return bt(t,(r=n?.map(i=>s.find(o=>o.id===i)).filter(Boolean))!=null?r:[],e,"right")},A(e.options,H,"getRightHeaderGroups")),e.getFooterGroups=P(()=>[e.getHeaderGroups()],t=>[...t].reverse(),A(e.options,H,"getFooterGroups")),e.getLeftFooterGroups=P(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),A(e.options,H,"getLeftFooterGroups")),e.getCenterFooterGroups=P(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),A(e.options,H,"getCenterFooterGroups")),e.getRightFooterGroups=P(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),A(e.options,H,"getRightFooterGroups")),e.getFlatHeaders=P(()=>[e.getHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,H,"getFlatHeaders")),e.getLeftFlatHeaders=P(()=>[e.getLeftHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,H,"getLeftFlatHeaders")),e.getCenterFlatHeaders=P(()=>[e.getCenterHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,H,"getCenterFlatHeaders")),e.getRightFlatHeaders=P(()=>[e.getRightHeaderGroups()],t=>t.map(s=>s.headers).flat(),A(e.options,H,"getRightFlatHeaders")),e.getCenterLeafHeaders=P(()=>[e.getCenterFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),A(e.options,H,"getCenterLeafHeaders")),e.getLeftLeafHeaders=P(()=>[e.getLeftFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),A(e.options,H,"getLeftLeafHeaders")),e.getRightLeafHeaders=P(()=>[e.getRightFlatHeaders()],t=>t.filter(s=>{var n;return!((n=s.subHeaders)!=null&&n.length)}),A(e.options,H,"getRightLeafHeaders")),e.getLeafHeaders=P(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,s,n)=>{var r,i,o,a,u,l;return[...(r=(i=t[0])==null?void 0:i.headers)!=null?r:[],...(o=(a=s[0])==null?void 0:a.headers)!=null?o:[],...(u=(l=n[0])==null?void 0:l.headers)!=null?u:[]].map(c=>c.getLeafHeaders()).flat()},A(e.options,H,"getLeafHeaders"))}};function bt(e,t,s,n){var r,i;let o=0;const a=function(d,h){h===void 0&&(h=1),o=Math.max(o,h),d.filter(f=>f.getIsVisible()).forEach(f=>{var p;(p=f.columns)!=null&&p.length&&a(f.columns,h+1)},0)};a(e);let u=[];const l=(d,h)=>{const f={depth:h,id:[n,`${h}`].filter(Boolean).join("_"),headers:[]},p=[];d.forEach(g=>{const m=[...p].reverse()[0],v=g.column.depth===f.depth;let S,C=!1;if(v&&g.column.parent?S=g.column.parent:(S=g.column,C=!0),m&&m?.column===S)m.subHeaders.push(g);else{const b=cr(s,S,{id:[n,h,S.id,g?.id].filter(Boolean).join("_"),isPlaceholder:C,placeholderId:C?`${p.filter(w=>w.column===S).length}`:void 0,depth:h,index:p.length});b.subHeaders.push(g),p.push(b)}f.headers.push(g),g.headerGroup=f}),u.push(f),h>0&&l(p,h-1)};l(t.map((d,h)=>cr(s,d,{depth:o,index:h})),o-1),u.reverse();const c=d=>d.filter(h=>h.column.getIsVisible()).map(h=>{let f=0,p=0,g=[0];h.subHeaders&&h.subHeaders.length?(g=[],c(h.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,h.colSpan=f,h.rowSpan=p,{colSpan:f,rowSpan:p}});return c((r=(i=u[0])==null?void 0:i.headers)!=null?r:[]),u}var Vl=(e,t,s,n,r,i,o)=>{let a={id:t,index:n,original:s,depth:r,parentId:o,_valuesCache:{},_uniqueValuesCache:{},getValue:u=>{if(a._valuesCache.hasOwnProperty(u))return a._valuesCache[u];const l=e.getColumn(u);if(l!=null&&l.accessorFn)return a._valuesCache[u]=l.accessorFn(a.original,n),a._valuesCache[u]},getUniqueValues:u=>{if(a._uniqueValuesCache.hasOwnProperty(u))return a._uniqueValuesCache[u];const l=e.getColumn(u);if(l!=null&&l.accessorFn)return l.columnDef.getUniqueValues?(a._uniqueValuesCache[u]=l.columnDef.getUniqueValues(a.original,n),a._uniqueValuesCache[u]):(a._uniqueValuesCache[u]=[a.getValue(u)],a._uniqueValuesCache[u])},renderValue:u=>{var l;return(l=a.getValue(u))!=null?l:e.options.renderFallbackValue},subRows:i??[],getLeafRows:()=>Bl(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=>Gl(e,a,l,l.id)),A(e.options,"debugRows","getAllCells")),_getAllCellsByColumnId:P(()=>[a.getAllCells()],u=>u.reduce((l,c)=>(l[c.column.id]=c,l),{}),A(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},ql={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()}}},ji=(e,t,s)=>{var n,r;const i=s==null||(n=s.toString())==null?void 0:n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(i))};ji.autoRemove=e=>te(e);var Ui=(e,t,s)=>{var n;return!!(!((n=e.getValue(t))==null||(n=n.toString())==null)&&n.includes(s))};Ui.autoRemove=e=>te(e);var Bi=(e,t,s)=>{var n;return((n=e.getValue(t))==null||(n=n.toString())==null?void 0:n.toLowerCase())===s?.toLowerCase()};Bi.autoRemove=e=>te(e);var Gi=(e,t,s)=>{var n;return(n=e.getValue(t))==null?void 0:n.includes(s)};Gi.autoRemove=e=>te(e);var Hi=(e,t,s)=>!s.some(n=>{var r;return!((r=e.getValue(t))!=null&&r.includes(n))});Hi.autoRemove=e=>te(e)||!(e!=null&&e.length);var zi=(e,t,s)=>s.some(n=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)});zi.autoRemove=e=>te(e)||!(e!=null&&e.length);var Vi=(e,t,s)=>e.getValue(t)===s;Vi.autoRemove=e=>te(e);var qi=(e,t,s)=>e.getValue(t)==s;qi.autoRemove=e=>te(e);var gn=(e,t,s)=>{let[n,r]=s;const i=e.getValue(t);return i>=n&&i<=r};gn.resolveFilterValue=e=>{let[t,s]=e,n=typeof t!="number"?parseFloat(t):t,r=typeof s!="number"?parseFloat(s):s,i=t===null||Number.isNaN(n)?-1/0:n,o=s===null||Number.isNaN(r)?1/0:r;if(i>o){const a=i;i=o,o=a}return[i,o]};gn.autoRemove=e=>te(e)||te(e[0])&&te(e[1]);var ue={includesString:ji,includesStringSensitive:Ui,equalsString:Bi,arrIncludes:Gi,arrIncludesAll:Hi,arrIncludesSome:zi,equals:Vi,weakEquals:qi,inNumberRange:gn};function te(e){return e==null||e===""}var Ql={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:Y("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const s=t.getCoreRowModel().flatRows[0],n=s?.getValue(e.id);return typeof n=="string"?ue.includesString:typeof n=="number"?ue.inNumberRange:typeof n=="boolean"||n!==null&&typeof n=="object"?ue.equals:Array.isArray(n)?ue.arrIncludes:ue.weakEquals},e.getFilterFn=()=>{var s,n;return Yt(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(s=(n=t.options.filterFns)==null?void 0:n[e.columnDef.filterFn])!=null?s:ue[e.columnDef.filterFn]},e.getCanFilter=()=>{var s,n,r;return((s=e.columnDef.enableColumnFilter)!=null?s:!0)&&((n=t.options.enableColumnFilters)!=null?n:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var s;return(s=t.getState().columnFilters)==null||(s=s.find(n=>n.id===e.id))==null?void 0:s.value},e.getFilterIndex=()=>{var s,n;return(s=(n=t.getState().columnFilters)==null?void 0:n.findIndex(r=>r.id===e.id))!=null?s:-1},e.setFilterValue=s=>{t.setColumnFilters(n=>{const r=e.getFilterFn(),i=n?.find(c=>c.id===e.id),o=me(s,i?i.value:void 0);if(dr(r,o,e)){var a;return(a=n?.filter(c=>c.id!==e.id))!=null?a:[]}const u={id:e.id,value:o};if(i){var l;return(l=n?.map(c=>c.id===e.id?u:c))!=null?l:[]}return n!=null&&n.length?[...n,u]:[u]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const s=e.getAllLeafColumns(),n=r=>{var i;return(i=me(t,r))==null?void 0:i.filter(o=>{const a=s.find(u=>u.id===o.id);return!(a&&dr(a.getFilterFn(),o.value,a))})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(n)},e.resetColumnFilters=t=>{var s,n;e.setColumnFilters(t?[]:(s=(n=e.initialState)==null?void 0:n.columnFilters)!=null?s:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function dr(e,t,s){return(e&&e.autoRemove?e.autoRemove(t,s):!1)||typeof t>"u"||typeof t=="string"&&!t}var Wl=(e,t,s)=>s.reduce((n,r)=>{const i=r.getValue(e);return n+(typeof i=="number"?i:0)},0),Kl=(e,t,s)=>{let n;return s.forEach(r=>{const i=r.getValue(e);i!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}),n},Jl=(e,t,s)=>{let n;return s.forEach(r=>{const i=r.getValue(e);i!=null&&(n<i||n===void 0&&i>=i)&&(n=i)}),n},Xl=(e,t,s)=>{let n,r;return s.forEach(i=>{const o=i.getValue(e);o!=null&&(n===void 0?o>=o&&(n=r=o):(n>o&&(n=o),r<o&&(r=o)))}),[n,r]},Yl=(e,t)=>{let s=0,n=0;if(t.forEach(r=>{let i=r.getValue(e);i!=null&&(i=+i)>=i&&(++s,n+=i)}),s)return n/s},Zl=(e,t)=>{if(!t.length)return;const s=t.map(i=>i.getValue(e));if(!Ul(s))return;if(s.length===1)return s[0];const n=Math.floor(s.length/2),r=s.sort((i,o)=>i-o);return s.length%2!==0?r[n]:(r[n-1]+r[n])/2},eu=(e,t)=>Array.from(new Set(t.map(s=>s.getValue(e))).values()),tu=(e,t)=>new Set(t.map(s=>s.getValue(e))).size,su=(e,t)=>t.length,ds={sum:Wl,min:Kl,max:Jl,extent:Xl,mean:Yl,median:Zl,unique:eu,uniqueCount:tu,count:su},nu={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,s;return(t=(s=e.getValue())==null||s.toString==null?void 0:s.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:Y("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(s=>s!=null&&s.includes(e.id)?s.filter(n=>n!==e.id):[...s??[],e.id])},e.getCanGroup=()=>{var s,n;return((s=e.columnDef.enableGrouping)!=null?s:!0)&&((n=t.options.enableGrouping)!=null?n:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var s;return(s=t.getState().grouping)==null?void 0:s.includes(e.id)},e.getGroupedIndex=()=>{var s;return(s=t.getState().grouping)==null?void 0:s.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const s=e.getCanGroup();return()=>{s&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const s=t.getCoreRowModel().flatRows[0],n=s?.getValue(e.id);if(typeof n=="number")return ds.sum;if(Object.prototype.toString.call(n)==="[object Date]")return ds.extent},e.getAggregationFn=()=>{var s,n;if(!e)throw new Error;return Yt(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(s=(n=t.options.aggregationFns)==null?void 0:n[e.columnDef.aggregationFn])!=null?s:ds[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var s,n;e.setGrouping(t?[]:(s=(n=e.initialState)==null?void 0:n.grouping)!=null?s:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=s=>{if(e._groupingValuesCache.hasOwnProperty(s))return e._groupingValuesCache[s];const n=t.getColumn(s);return n!=null&&n.columnDef.getGroupingValue?(e._groupingValuesCache[s]=n.columnDef.getGroupingValue(e.original),e._groupingValuesCache[s]):e.getValue(s)},e._groupingValuesCache={}},createCell:(e,t,s,n)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===s.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var r;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((r=s.subRows)!=null&&r.length)}}};function ru(e,t,s){if(!(t!=null&&t.length)||!s)return e;const n=e.filter(r=>!t.includes(r.id));return s==="remove"?n:[...t.map(r=>e.find(i=>i.id===r)).filter(Boolean),...n]}var iu={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:Y("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=P(s=>[ot(t,s)],s=>s.findIndex(n=>n.id===e.id),A(t.options,"debugColumns","getIndex")),e.getIsFirstColumn=s=>{var n;return((n=ot(t,s)[0])==null?void 0:n.id)===e.id},e.getIsLastColumn=s=>{var n;const r=ot(t,s);return((n=r[r.length-1])==null?void 0:n.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var s;e.setColumnOrder(t?[]:(s=e.initialState.columnOrder)!=null?s:[])},e._getOrderColumnsFn=P(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,s,n)=>r=>{let i=[];if(!(t!=null&&t.length))i=r;else{const o=[...t],a=[...r];for(;a.length&&o.length;){const u=o.shift(),l=a.findIndex(c=>c.id===u);l>-1&&i.push(a.splice(l,1)[0])}i=[...i,...a]}return ru(i,s,n)},A(e.options,"debugTable","_getOrderColumnsFn"))}},hs=()=>({left:[],right:[]}),ou={getInitialState:e=>({columnPinning:hs(),...e}),getDefaultOptions:e=>({onColumnPinningChange:Y("columnPinning",e)}),createColumn:(e,t)=>{e.pin=s=>{const n=e.getLeafColumns().map(r=>r.id).filter(Boolean);t.setColumnPinning(r=>{var i,o;if(s==="right"){var a,u;return{left:((a=r?.left)!=null?a:[]).filter(d=>!(n!=null&&n.includes(d))),right:[...((u=r?.right)!=null?u:[]).filter(d=>!(n!=null&&n.includes(d))),...n]}}if(s==="left"){var l,c;return{left:[...((l=r?.left)!=null?l:[]).filter(d=>!(n!=null&&n.includes(d))),...n],right:((c=r?.right)!=null?c:[]).filter(d=>!(n!=null&&n.includes(d)))}}return{left:((i=r?.left)!=null?i:[]).filter(d=>!(n!=null&&n.includes(d))),right:((o=r?.right)!=null?o:[]).filter(d=>!(n!=null&&n.includes(d)))}})},e.getCanPin=()=>e.getLeafColumns().some(s=>{var n,r,i;return((n=s.columnDef.enablePinning)!=null?n:!0)&&((r=(i=t.options.enableColumnPinning)!=null?i:t.options.enablePinning)!=null?r:!0)}),e.getIsPinned=()=>{const s=e.getLeafColumns().map(a=>a.id),{left:n,right:r}=t.getState().columnPinning,i=s.some(a=>n?.includes(a)),o=s.some(a=>r?.includes(a));return i?"left":o?"right":!1},e.getPinnedIndex=()=>{var s,n;const r=e.getIsPinned();return r?(s=(n=t.getState().columnPinning)==null||(n=n[r])==null?void 0:n.indexOf(e.id))!=null?s:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=P(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(s,n,r)=>{const i=[...n??[],...r??[]];return s.filter(o=>!i.includes(o.column.id))},A(t.options,"debugRows","getCenterVisibleCells")),e.getLeftVisibleCells=P(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(s,n)=>(n??[]).map(r=>s.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"left"})),A(t.options,"debugRows","getLeftVisibleCells")),e.getRightVisibleCells=P(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(s,n)=>(n??[]).map(r=>s.find(i=>i.column.id===r)).filter(Boolean).map(r=>({...r,position:"right"})),A(t.options,"debugRows","getRightVisibleCells"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var s,n;return e.setColumnPinning(t?hs():(s=(n=e.initialState)==null?void 0:n.columnPinning)!=null?s:hs())},e.getIsSomeColumnsPinned=t=>{var s;const n=e.getState().columnPinning;if(!t){var r,i;return!!((r=n.left)!=null&&r.length||(i=n.right)!=null&&i.length)}return!!((s=n[t])!=null&&s.length)},e.getLeftLeafColumns=P(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,s)=>(s??[]).map(n=>t.find(r=>r.id===n)).filter(Boolean),A(e.options,"debugColumns","getLeftLeafColumns")),e.getRightLeafColumns=P(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,s)=>(s??[]).map(n=>t.find(r=>r.id===n)).filter(Boolean),A(e.options,"debugColumns","getRightLeafColumns")),e.getCenterLeafColumns=P(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n)=>{const r=[...s??[],...n??[]];return t.filter(i=>!r.includes(i.id))},A(e.options,"debugColumns","getCenterLeafColumns"))}};function au(e){return e||(typeof document<"u"?document:null)}var Et={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},fs=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),lu={getDefaultColumnDef:()=>Et,getInitialState:e=>({columnSizing:{},columnSizingInfo:fs(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:Y("columnSizing",e),onColumnSizingInfoChange:Y("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var s,n,r;const i=t.getState().columnSizing[e.id];return Math.min(Math.max((s=e.columnDef.minSize)!=null?s:Et.minSize,(n=i??e.columnDef.size)!=null?n:Et.size),(r=e.columnDef.maxSize)!=null?r:Et.maxSize)},e.getStart=P(s=>[s,ot(t,s),t.getState().columnSizing],(s,n)=>n.slice(0,e.getIndex(s)).reduce((r,i)=>r+i.getSize(),0),A(t.options,"debugColumns","getStart")),e.getAfter=P(s=>[s,ot(t,s),t.getState().columnSizing],(s,n)=>n.slice(e.getIndex(s)+1).reduce((r,i)=>r+i.getSize(),0),A(t.options,"debugColumns","getAfter")),e.resetSize=()=>{t.setColumnSizing(s=>{let{[e.id]:n,...r}=s;return r})},e.getCanResize=()=>{var s,n;return((s=e.columnDef.enableResizing)!=null?s:!0)&&((n=t.options.enableColumnResizing)!=null?n:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let s=0;const n=r=>{if(r.subHeaders.length)r.subHeaders.forEach(n);else{var i;s+=(i=r.column.getSize())!=null?i:0}};return n(e),s},e.getStart=()=>{if(e.index>0){const s=e.headerGroup.headers[e.index-1];return s.getStart()+s.getSize()}return 0},e.getResizeHandler=s=>{const n=t.getColumn(e.column.id),r=n?.getCanResize();return i=>{if(!n||!r||(i.persist==null||i.persist(),gs(i)&&i.touches&&i.touches.length>1))return;const o=e.getSize(),a=e?e.getLeafHeaders().map(v=>[v.column.id,v.column.getSize()]):[[n.id,n.getSize()]],u=gs(i)?Math.round(i.touches[0].clientX):i.clientX,l={},c=(v,S)=>{typeof S=="number"&&(t.setColumnSizingInfo(C=>{var b,w;const R=t.options.columnResizeDirection==="rtl"?-1:1,y=(S-((b=C?.startOffset)!=null?b:0))*R,_=Math.max(y/((w=C?.startSize)!=null?w:0),-.999999);return C.columnSizingStart.forEach(T=>{let[E,x]=T;l[E]=Math.round(Math.max(x+x*_,0)*100)/100}),{...C,deltaOffset:y,deltaPercentage:_}}),(t.options.columnResizeMode==="onChange"||v==="end")&&t.setColumnSizing(C=>({...C,...l})))},d=v=>c("move",v),h=v=>{c("end",v),t.setColumnSizingInfo(S=>({...S,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},f=au(s),p={moveHandler:v=>d(v.clientX),upHandler:v=>{f?.removeEventListener("mousemove",p.moveHandler),f?.removeEventListener("mouseup",p.upHandler),h(v.clientX)}},g={moveHandler:v=>(v.cancelable&&(v.preventDefault(),v.stopPropagation()),d(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()),h((S=v.touches[0])==null?void 0:S.clientX)}},m=uu()?{passive:!1}:!1;gs(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:n.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var s;e.setColumnSizing(t?{}:(s=e.initialState.columnSizing)!=null?s:{})},e.resetHeaderSizeInfo=t=>{var s;e.setColumnSizingInfo(t?fs():(s=e.initialState.columnSizingInfo)!=null?s:fs())},e.getTotalSize=()=>{var t,s;return(t=(s=e.getHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,s;return(t=(s=e.getLeftHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,s;return(t=(s=e.getCenterHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,s;return(t=(s=e.getRightHeaderGroups()[0])==null?void 0:s.headers.reduce((n,r)=>n+r.getSize(),0))!=null?t:0}}},_t=null;function uu(){if(typeof _t=="boolean")return _t;let e=!1;try{const t={get passive(){return e=!0,!1}},s=()=>{};window.addEventListener("test",s,t),window.removeEventListener("test",s)}catch{e=!1}return _t=e,_t}function gs(e){return e.type==="touchstart"}var cu={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:Y("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=s=>{e.getCanHide()&&t.setColumnVisibility(n=>({...n,[e.id]:s??!e.getIsVisible()}))},e.getIsVisible=()=>{var s,n;const r=e.columns;return(s=r.length?r.some(i=>i.getIsVisible()):(n=t.getState().columnVisibility)==null?void 0:n[e.id])!=null?s:!0},e.getCanHide=()=>{var s,n;return((s=e.columnDef.enableHiding)!=null?s:!0)&&((n=t.options.enableHiding)!=null?n:!0)},e.getToggleVisibilityHandler=()=>s=>{e.toggleVisibility==null||e.toggleVisibility(s.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=P(()=>[e.getAllCells(),t.getState().columnVisibility],s=>s.filter(n=>n.column.getIsVisible()),A(t.options,"debugRows","_getAllVisibleCells")),e.getVisibleCells=P(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(s,n,r)=>[...s,...n,...r],A(t.options,"debugRows","getVisibleCells"))},createTable:e=>{const t=(s,n)=>P(()=>[n(),n().filter(r=>r.getIsVisible()).map(r=>r.id).join("_")],r=>r.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),A(e.options,"debugColumns",s));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=s=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(s),e.resetColumnVisibility=s=>{var n;e.setColumnVisibility(s?{}:(n=e.initialState.columnVisibility)!=null?n:{})},e.toggleAllColumnsVisible=s=>{var n;s=(n=s)!=null?n:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((r,i)=>({...r,[i.id]:s||!(i.getCanHide!=null&&i.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(s=>!(s.getIsVisible!=null&&s.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(s=>s.getIsVisible==null?void 0:s.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>s=>{var n;e.toggleAllColumnsVisible((n=s.target)==null?void 0:n.checked)}}};function ot(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}var du={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()}}},hu={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:Y("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var s;const n=(s=e.getCoreRowModel().flatRows[0])==null||(s=s._getAllCellsByColumnId()[t.id])==null?void 0:s.getValue();return typeof n=="string"||typeof n=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var s,n,r,i;return((s=e.columnDef.enableGlobalFilter)!=null?s:!0)&&((n=t.options.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableFilters)!=null?r:!0)&&((i=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?i:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>ue.includesString,e.getGlobalFilterFn=()=>{var t,s;const{globalFilterFn:n}=e.options;return Yt(n)?n:n==="auto"?e.getGlobalAutoFilterFn():(t=(s=e.options.filterFns)==null?void 0:s[n])!=null?t:ue[n]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},fu={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:Y("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,s=!1;e._autoResetExpanded=()=>{var n,r;if(!t){e._queue(()=>{t=!0});return}if((n=(r=e.options.autoResetAll)!=null?r:e.options.autoResetExpanded)!=null?n:!e.options.manualExpanding){if(s)return;s=!0,e._queue(()=>{e.resetExpanded(),s=!1})}},e.setExpanded=n=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(n),e.toggleAllRowsExpanded=n=>{n??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=n=>{var r,i;e.setExpanded(n?{}:(r=(i=e.initialState)==null?void 0:i.expanded)!=null?r:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(n=>n.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>n=>{n.persist==null||n.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const n=e.getState().expanded;return n===!0||Object.values(n).some(Boolean)},e.getIsAllRowsExpanded=()=>{const n=e.getState().expanded;return typeof n=="boolean"?n===!0:!(!Object.keys(n).length||e.getRowModel().flatRows.some(r=>!r.getIsExpanded()))},e.getExpandedDepth=()=>{let n=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(r=>{const i=r.split(".");n=Math.max(n,i.length)}),n},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=s=>{t.setExpanded(n=>{var r;const i=n===!0?!0:!!(n!=null&&n[e.id]);let o={};if(n===!0?Object.keys(t.getRowModel().rowsById).forEach(a=>{o[a]=!0}):o=n,s=(r=s)!=null?r:!i,!i&&s)return{...o,[e.id]:!0};if(i&&!s){const{[e.id]:a,...u}=o;return u}return n})},e.getIsExpanded=()=>{var s;const n=t.getState().expanded;return!!((s=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?s:n===!0||n?.[e.id])},e.getCanExpand=()=>{var s,n,r;return(s=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?s:((n=t.options.enableExpanding)!=null?n:!0)&&!!((r=e.subRows)!=null&&r.length)},e.getIsAllParentsExpanded=()=>{let s=!0,n=e;for(;s&&n.parentId;)n=t.getRow(n.parentId,!0),s=n.getIsExpanded();return s},e.getToggleExpandedHandler=()=>{const s=e.getCanExpand();return()=>{s&&e.toggleExpanded()}}}},Ds=0,$s=10,ps=()=>({pageIndex:Ds,pageSize:$s}),gu={getInitialState:e=>({...e,pagination:{...ps(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:Y("pagination",e)}),createTable:e=>{let t=!1,s=!1;e._autoResetPageIndex=()=>{var n,r;if(!t){e._queue(()=>{t=!0});return}if((n=(r=e.options.autoResetAll)!=null?r:e.options.autoResetPageIndex)!=null?n:!e.options.manualPagination){if(s)return;s=!0,e._queue(()=>{e.resetPageIndex(),s=!1})}},e.setPagination=n=>{const r=i=>me(n,i);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(r)},e.resetPagination=n=>{var r;e.setPagination(n?ps():(r=e.initialState.pagination)!=null?r:ps())},e.setPageIndex=n=>{e.setPagination(r=>{let i=me(n,r.pageIndex);const o=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return i=Math.max(0,Math.min(i,o)),{...r,pageIndex:i}})},e.resetPageIndex=n=>{var r,i;e.setPageIndex(n?Ds:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageIndex)!=null?r:Ds)},e.resetPageSize=n=>{var r,i;e.setPageSize(n?$s:(r=(i=e.initialState)==null||(i=i.pagination)==null?void 0:i.pageSize)!=null?r:$s)},e.setPageSize=n=>{e.setPagination(r=>{const i=Math.max(1,me(n,r.pageSize)),o=r.pageSize*r.pageIndex,a=Math.floor(o/i);return{...r,pageIndex:a,pageSize:i}})},e.setPageCount=n=>e.setPagination(r=>{var i;let o=me(n,(i=e.options.pageCount)!=null?i:-1);return typeof o=="number"&&(o=Math.max(-1,o)),{...r,pageCount:o}}),e.getPageOptions=P(()=>[e.getPageCount()],n=>{let r=[];return n&&n>0&&(r=[...new Array(n)].fill(null).map((i,o)=>o)),r},A(e.options,"debugTable","getPageOptions")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:n}=e.getState().pagination,r=e.getPageCount();return r===-1?!0:r===0?!1:n<r-1},e.previousPage=()=>e.setPageIndex(n=>n-1),e.nextPage=()=>e.setPageIndex(n=>n+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var n;return(n=e.options.pageCount)!=null?n:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var n;return(n=e.options.rowCount)!=null?n:e.getPrePaginationRowModel().rows.length}}},ms=()=>({top:[],bottom:[]}),pu={getInitialState:e=>({rowPinning:ms(),...e}),getDefaultOptions:e=>({onRowPinningChange:Y("rowPinning",e)}),createRow:(e,t)=>{e.pin=(s,n,r)=>{const i=n?e.getLeafRows().map(u=>{let{id:l}=u;return l}):[],o=r?e.getParentRows().map(u=>{let{id:l}=u;return l}):[],a=new Set([...o,e.id,...i]);t.setRowPinning(u=>{var l,c;if(s==="bottom"){var d,h;return{top:((d=u?.top)!=null?d:[]).filter(g=>!(a!=null&&a.has(g))),bottom:[...((h=u?.bottom)!=null?h:[]).filter(g=>!(a!=null&&a.has(g))),...Array.from(a)]}}if(s==="top"){var f,p;return{top:[...((f=u?.top)!=null?f:[]).filter(g=>!(a!=null&&a.has(g))),...Array.from(a)],bottom:((p=u?.bottom)!=null?p:[]).filter(g=>!(a!=null&&a.has(g)))}}return{top:((l=u?.top)!=null?l:[]).filter(g=>!(a!=null&&a.has(g))),bottom:((c=u?.bottom)!=null?c:[]).filter(g=>!(a!=null&&a.has(g)))}})},e.getCanPin=()=>{var s;const{enableRowPinning:n,enablePinning:r}=t.options;return typeof n=="function"?n(e):(s=n??r)!=null?s:!0},e.getIsPinned=()=>{const s=[e.id],{top:n,bottom:r}=t.getState().rowPinning,i=s.some(a=>n?.includes(a)),o=s.some(a=>r?.includes(a));return i?"top":o?"bottom":!1},e.getPinnedIndex=()=>{var s,n;const r=e.getIsPinned();if(!r)return-1;const i=(s=r==="top"?t.getTopRows():t.getBottomRows())==null?void 0:s.map(o=>{let{id:a}=o;return a});return(n=i?.indexOf(e.id))!=null?n:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var s,n;return e.setRowPinning(t?ms():(s=(n=e.initialState)==null?void 0:n.rowPinning)!=null?s:ms())},e.getIsSomeRowsPinned=t=>{var s;const n=e.getState().rowPinning;if(!t){var r,i;return!!((r=n.top)!=null&&r.length||(i=n.bottom)!=null&&i.length)}return!!((s=n[t])!=null&&s.length)},e._getPinnedRows=(t,s,n)=>{var r;return((r=e.options.keepPinnedRows)==null||r?(s??[]).map(i=>{const o=e.getRow(i,!0);return o.getIsAllParentsExpanded()?o:null}):(s??[]).map(i=>t.find(o=>o.id===i))).filter(Boolean).map(i=>({...i,position:n}))},e.getTopRows=P(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,s)=>e._getPinnedRows(t,s,"top"),A(e.options,"debugRows","getTopRows")),e.getBottomRows=P(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,s)=>e._getPinnedRows(t,s,"bottom"),A(e.options,"debugRows","getBottomRows")),e.getCenterRows=P(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,s,n)=>{const r=new Set([...s??[],...n??[]]);return t.filter(i=>!r.has(i.id))},A(e.options,"debugRows","getCenterRows"))}},mu={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:Y("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var s;return e.setRowSelection(t?{}:(s=e.initialState.rowSelection)!=null?s:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(s=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const n={...s},r=e.getPreGroupedRowModel().flatRows;return t?r.forEach(i=>{i.getCanSelect()&&(n[i.id]=!0)}):r.forEach(i=>{delete n[i.id]}),n})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(s=>{const n=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),r={...s};return e.getRowModel().rows.forEach(i=>{js(r,i.id,n,!0,e)}),r}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=P(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,s)=>Object.keys(t).length?vs(e,s):{rows:[],flatRows:[],rowsById:{}},A(e.options,"debugTable","getSelectedRowModel")),e.getFilteredSelectedRowModel=P(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,s)=>Object.keys(t).length?vs(e,s):{rows:[],flatRows:[],rowsById:{}},A(e.options,"debugTable","getFilteredSelectedRowModel")),e.getGroupedSelectedRowModel=P(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,s)=>Object.keys(t).length?vs(e,s):{rows:[],flatRows:[],rowsById:{}},A(e.options,"debugTable","getGroupedSelectedRowModel")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:s}=e.getState();let n=!!(t.length&&Object.keys(s).length);return n&&t.some(r=>r.getCanSelect()&&!s[r.id])&&(n=!1),n},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(r=>r.getCanSelect()),{rowSelection:s}=e.getState();let n=!!t.length;return n&&t.some(r=>!s[r.id])&&(n=!1),n},e.getIsSomeRowsSelected=()=>{var t;const s=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return s>0&&s<e.getFilteredRowModel().flatRows.length},e.getIsSomePageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(s=>s.getCanSelect()).some(s=>s.getIsSelected()||s.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(s,n)=>{const r=e.getIsSelected();t.setRowSelection(i=>{var o;if(s=typeof s<"u"?s:!r,e.getCanSelect()&&r===s)return i;const a={...i};return js(a,e.id,s,(o=n?.selectChildren)!=null?o:!0,t),a})},e.getIsSelected=()=>{const{rowSelection:s}=t.getState();return pn(e,s)},e.getIsSomeSelected=()=>{const{rowSelection:s}=t.getState();return Us(e,s)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:s}=t.getState();return Us(e,s)==="all"},e.getCanSelect=()=>{var s;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(s=t.options.enableRowSelection)!=null?s:!0},e.getCanSelectSubRows=()=>{var s;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(s=t.options.enableSubRowSelection)!=null?s:!0},e.getCanMultiSelect=()=>{var s;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(s=t.options.enableMultiRowSelection)!=null?s:!0},e.getToggleSelectedHandler=()=>{const s=e.getCanSelect();return n=>{var r;s&&e.toggleSelected((r=n.target)==null?void 0:r.checked)}}}},js=(e,t,s,n,r)=>{var i;const o=r.getRow(t,!0);s?(o.getCanMultiSelect()||Object.keys(e).forEach(a=>delete e[a]),o.getCanSelect()&&(e[t]=!0)):delete e[t],n&&(i=o.subRows)!=null&&i.length&&o.getCanSelectSubRows()&&o.subRows.forEach(a=>js(e,a.id,s,n,r))};function vs(e,t){const s=e.getState().rowSelection,n=[],r={},i=function(o,a){return o.map(u=>{var l;const c=pn(u,s);if(c&&(n.push(u),r[u.id]=u),(l=u.subRows)!=null&&l.length&&(u={...u,subRows:i(u.subRows)}),c)return u}).filter(Boolean)};return{rows:i(t.rows),flatRows:n,rowsById:r}}function pn(e,t){var s;return(s=t[e.id])!=null?s:!1}function Us(e,t,s){var n;if(!((n=e.subRows)!=null&&n.length))return!1;let r=!0,i=!1;return e.subRows.forEach(o=>{if(!(i&&!r)&&(o.getCanSelect()&&(pn(o,t)?i=!0:r=!1),o.subRows&&o.subRows.length)){const a=Us(o,t);a==="all"?i=!0:(a==="some"&&(i=!0),r=!1)}}),r?"all":i?"some":!1}var Bs=/([0-9]+)/gm,vu=(e,t,s)=>Qi(we(e.getValue(s)).toLowerCase(),we(t.getValue(s)).toLowerCase()),Su=(e,t,s)=>Qi(we(e.getValue(s)),we(t.getValue(s))),yu=(e,t,s)=>mn(we(e.getValue(s)).toLowerCase(),we(t.getValue(s)).toLowerCase()),Iu=(e,t,s)=>mn(we(e.getValue(s)),we(t.getValue(s))),Ru=(e,t,s)=>{const n=e.getValue(s),r=t.getValue(s);return n>r?1:n<r?-1:0},Cu=(e,t,s)=>mn(e.getValue(s),t.getValue(s));function mn(e,t){return e===t?0:e>t?1:-1}function we(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function Qi(e,t){const s=e.split(Bs).filter(Boolean),n=t.split(Bs).filter(Boolean);for(;s.length&&n.length;){const r=s.shift(),i=n.shift(),o=parseInt(r,10),a=parseInt(i,10),u=[o,a].sort();if(isNaN(u[0])){if(r>i)return 1;if(i>r)return-1;continue}if(isNaN(u[1]))return isNaN(o)?-1:1;if(o>a)return 1;if(a>o)return-1}return s.length-n.length}var tt={alphanumeric:vu,alphanumericCaseSensitive:Su,text:yu,textCaseSensitive:Iu,datetime:Ru,basic:Cu},wu={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:Y("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const s=t.getFilteredRowModel().flatRows.slice(10);let n=!1;for(const r of s){const i=r?.getValue(e.id);if(Object.prototype.toString.call(i)==="[object Date]")return tt.datetime;if(typeof i=="string"&&(n=!0,i.split(Bs).length>1))return tt.alphanumeric}return n?tt.text:tt.basic},e.getAutoSortDir=()=>{const s=t.getFilteredRowModel().flatRows[0];return typeof s?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var s,n;if(!e)throw new Error;return Yt(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(s=(n=t.options.sortingFns)==null?void 0:n[e.columnDef.sortingFn])!=null?s:tt[e.columnDef.sortingFn]},e.toggleSorting=(s,n)=>{const r=e.getNextSortingOrder(),i=typeof s<"u"&&s!==null;t.setSorting(o=>{const a=o?.find(f=>f.id===e.id),u=o?.findIndex(f=>f.id===e.id);let l=[],c,d=i?s:r==="desc";if(o!=null&&o.length&&e.getCanMultiSort()&&n?a?c="toggle":c="add":o!=null&&o.length&&u!==o.length-1?c="replace":a?c="toggle":c="replace",c==="toggle"&&(i||r||(c="remove")),c==="add"){var h;l=[...o,{id:e.id,desc:d}],l.splice(0,l.length-((h=t.options.maxMultiSortColCount)!=null?h:Number.MAX_SAFE_INTEGER))}else c==="toggle"?l=o.map(f=>f.id===e.id?{...f,desc:d}:f):c==="remove"?l=o.filter(f=>f.id!==e.id):l=[{id:e.id,desc:d}];return l})},e.getFirstSortDir=()=>{var s,n;return((s=(n=e.columnDef.sortDescFirst)!=null?n:t.options.sortDescFirst)!=null?s:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=s=>{var n,r;const i=e.getFirstSortDir(),o=e.getIsSorted();return o?o!==i&&((n=t.options.enableSortingRemoval)==null||n)&&(!(s&&(r=t.options.enableMultiRemove)!=null)||r)?!1:o==="desc"?"asc":"desc":i},e.getCanSort=()=>{var s,n;return((s=e.columnDef.enableSorting)!=null?s:!0)&&((n=t.options.enableSorting)!=null?n:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var s,n;return(s=(n=e.columnDef.enableMultiSort)!=null?n:t.options.enableMultiSort)!=null?s:!!e.accessorFn},e.getIsSorted=()=>{var s;const n=(s=t.getState().sorting)==null?void 0:s.find(r=>r.id===e.id);return n?n.desc?"desc":"asc":!1},e.getSortIndex=()=>{var s,n;return(s=(n=t.getState().sorting)==null?void 0:n.findIndex(r=>r.id===e.id))!=null?s:-1},e.clearSorting=()=>{t.setSorting(s=>s!=null&&s.length?s.filter(n=>n.id!==e.id):[])},e.getToggleSortingHandler=()=>{const s=e.getCanSort();return n=>{s&&(n.persist==null||n.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(n):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var s,n;e.setSorting(t?[]:(s=(n=e.initialState)==null?void 0:n.sorting)!=null?s:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},bu=[zl,cu,iu,ou,ql,Ql,du,hu,wu,nu,fu,gu,pu,mu,lu];function Eu(e){var t,s;const n=[...bu,...(t=e._features)!=null?t:[]];let r={_features:n};const i=r._features.reduce((d,h)=>Object.assign(d,h.getDefaultOptions==null?void 0:h.getDefaultOptions(r)),{}),o=d=>r.options.mergeOptions?r.options.mergeOptions(i,d):{...i,...d};let a={...(s=e.initialState)!=null?s:{}};r._features.forEach(d=>{var h;a=(h=d.getInitialState==null?void 0:d.getInitialState(a))!=null?h:a});const u=[];let l=!1;const c={_features:n,options:{...i,...e},initialState:a,_queue:d=>{u.push(d),l||(l=!0,Promise.resolve().then(()=>{for(;u.length;)u.shift()();l=!1}).catch(h=>setTimeout(()=>{throw h})))},reset:()=>{r.setState(r.initialState)},setOptions:d=>{const h=me(d,r.options);r.options=o(h)},getState:()=>r.options.state,setState:d=>{r.options.onStateChange==null||r.options.onStateChange(d)},_getRowId:(d,h,f)=>{var p;return(p=r.options.getRowId==null?void 0:r.options.getRowId(d,h,f))!=null?p:`${f?[f.id,h].join("."):h}`},getCoreRowModel:()=>(r._getCoreRowModel||(r._getCoreRowModel=r.options.getCoreRowModel(r)),r._getCoreRowModel()),getRowModel:()=>r.getPaginationRowModel(),getRow:(d,h)=>{let f=(h?r.getPrePaginationRowModel():r.getRowModel()).rowsById[d];if(!f&&(f=r.getCoreRowModel().rowsById[d],!f))throw new Error;return f},_getDefaultColumnDef:P(()=>[r.options.defaultColumn],d=>{var h;return d=(h=d)!=null?h:{},{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()),{}),...d}},A(e,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>r.options.columns,getAllColumns:P(()=>[r._getColumnDefs()],d=>{const h=function(f,p,g){return g===void 0&&(g=0),f.map(m=>{const v=Hl(r,m,g,p),S=m;return v.columns=S.columns?h(S.columns,v,g+1):[],v})};return h(d)},A(e,"debugColumns","getAllColumns")),getAllFlatColumns:P(()=>[r.getAllColumns()],d=>d.flatMap(h=>h.getFlatColumns()),A(e,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:P(()=>[r.getAllFlatColumns()],d=>d.reduce((h,f)=>(h[f.id]=f,h),{}),A(e,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:P(()=>[r.getAllColumns(),r._getOrderColumnsFn()],(d,h)=>h(d.flatMap(f=>f.getLeafColumns())),A(e,"debugColumns","getAllLeafColumns")),getColumn:d=>r._getAllFlatColumnsById()[d]};Object.assign(r,c);for(let d=0;d<r._features.length;d++){const h=r._features[d];h==null||h.createTable==null||h.createTable(r)}return r}function ch(){return e=>P(()=>[e.options.data],t=>{const s={rows:[],flatRows:[],rowsById:{}},n=function(r,i,o){i===void 0&&(i=0);const a=[];for(let l=0;l<r.length;l++){const c=Vl(e,e._getRowId(r[l],l,o),r[l],l,i,void 0,o?.id);if(s.flatRows.push(c),s.rowsById[c.id]=c,a.push(c),e.options.getSubRows){var u;c.originalSubRows=e.options.getSubRows(r[l],l),(u=c.originalSubRows)!=null&&u.length&&(c.subRows=n(c.originalSubRows,i+1,c))}}return a};return s.rows=n(t),s},A(e.options,"debugTable","getRowModel",()=>e._autoResetPageIndex()))}function dh(){return e=>P(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,s)=>{if(!s.rows.length||!(t!=null&&t.length))return s;const n=e.getState().sorting,r=[],i=n.filter(u=>{var l;return(l=e.getColumn(u.id))==null?void 0:l.getCanSort()}),o={};i.forEach(u=>{const l=e.getColumn(u.id);l&&(o[u.id]={sortUndefined:l.columnDef.sortUndefined,invertSorting:l.columnDef.invertSorting,sortingFn:l.getSortingFn()})});const a=u=>{const l=u.map(c=>({...c}));return l.sort((c,d)=>{for(let f=0;f<i.length;f+=1){var h;const p=i[f],g=o[p.id],m=g.sortUndefined,v=(h=p?.desc)!=null?h:!1;let S=0;if(m){const C=c.getValue(p.id),b=d.getValue(p.id),w=C===void 0,R=b===void 0;if(w||R){if(m==="first")return w?-1:1;if(m==="last")return w?1:-1;S=w&&R?0:w?m:-m}}if(S===0&&(S=g.sortingFn(c,d,p.id)),S!==0)return v&&(S*=-1),g.invertSorting&&(S*=-1),S}return c.index-d.index}),l.forEach(c=>{var d;r.push(c),(d=c.subRows)!=null&&d.length&&(c.subRows=a(c.subRows))}),l};return{rows:a(s.rows),flatRows:r,rowsById:s.rowsById}},A(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}function hh(e,t){return e?_u(e)?I.createElement(e,t):e:null}function _u(e){return Tu(e)||typeof e=="function"||Mu(e)}function Tu(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function Mu(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function fh(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[s]=I.useState(()=>({current:Eu(t)})),[n,r]=I.useState(()=>s.current.initialState);return s.current.setOptions(i=>({...i,...e,state:{...n,...e.state},onStateChange:o=>{r(o),e.onStateChange==null||e.onStateChange(o)}})),s.current}var xu=zr(co(),1);function Ue(e,t,s){let n=s.initialDeps??[],r,i=!0;function o(){var a,u,l;let c;s.key&&((a=s.debug)!=null&&a.call(s))&&(c=Date.now());const d=e();if(!(d.length!==n.length||d.some((f,p)=>n[p]!==f)))return r;n=d;let h;if(s.key&&((u=s.debug)!=null&&u.call(s))&&(h=Date.now()),r=t(...d),s.key&&((l=s.debug)!=null&&l.call(s))){const f=Math.round((Date.now()-c)*100)/100,p=Math.round((Date.now()-h)*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
|
-
font-size: .6rem;
|
|
6
|
-
font-weight: bold;
|
|
7
|
-
color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,s?.key)}return s?.onChange&&!(i&&s.skipInitialOnChange)&&s.onChange(r),i=!1,r}return o.updateDeps=a=>{n=a},o}function hr(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var Pu=(e,t)=>Math.abs(e-t)<1.01,Au=(e,t,s)=>{let n;return function(...r){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,r),s)}},fr=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},Ou=e=>e,Fu=e=>{const t=Math.max(e.startIndex-e.overscan,0),s=Math.min(e.endIndex+e.overscan,e.count-1),n=[];for(let r=t;r<=s;r++)n.push(r);return n},Lu=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const r=o=>{const{width:a,height:u}=o;t({width:Math.round(a),height:Math.round(u)})};if(r(fr(s)),!n.ResizeObserver)return()=>{};const i=new n.ResizeObserver(o=>{const a=()=>{const u=o[0];if(u?.borderBoxSize){const l=u.borderBoxSize[0];if(l){r({width:l.inlineSize,height:l.blockSize});return}}r(fr(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return i.observe(s,{box:"border-box"}),()=>{i.unobserve(s)}},gr={passive:!0},pr=typeof window>"u"?!0:"onscrollend"in window,Nu=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let r=0;const i=e.options.useScrollendEvent&&pr?()=>{}:Au(n,()=>{t(r,!1)},e.options.isScrollingResetDelay),o=c=>()=>{const{horizontal:d,isRtl:h}=e.options;r=d?s.scrollLeft*(h&&-1||1):s.scrollTop,i(),t(r,c)},a=o(!0),u=o(!1);s.addEventListener("scroll",a,gr);const l=e.options.useScrollendEvent&≺return l&&s.addEventListener("scrollend",u,gr),()=>{s.removeEventListener("scroll",a),l&&s.removeEventListener("scrollend",u)}},ku=(e,t,s)=>{if(t?.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},Du=(e,{adjustments:t=0,behavior:s},n)=>{var r,i;const o=e+t;(i=(r=n.scrollElement)==null?void 0:r.scrollTo)==null||i.call(r,{[n.options.horizontal?"left":"top"]:o,behavior:s})},$u=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,s,n;return((n=(s=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:s.now)==null?void 0:n.call(s))??Date.now()},this.observer=(()=>{let t=null;const s=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(n=>{n.forEach(r=>{const i=()=>{const o=r.target,a=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(a)&&this.resizeItem(a,this.options.measureElement(o,r,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var n;(n=s())==null||n.disconnect(),t=null},observe:n=>{var r;return(r=s())==null?void 0:r.observe(n,{box:"border-box"})},unobserve:n=>{var r;return(r=s())==null?void 0:r.unobserve(n)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([s,n])=>{typeof n>"u"&&delete t[s]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Ou,rangeExtractor:Fu,onChange:()=>{},measureElement:ku,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var s,n;(n=(s=this.options).onChange)==null||n.call(s,this,t)},this.maybeNotify=Ue(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const s=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==s){if(this.cleanup(),!s){this.maybeNotify();return}this.scrollElement=s,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(n=>{this.observer.observe(n)}),this.unsubs.push(this.options.observeElementRect(this,n=>{this.scrollRect=n,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(n,r)=>{this.scrollAdjustments=0,this.scrollDirection=r?this.getScrollOffset()<n?"forward":"backward":null,this.scrollOffset=n,this.isScrolling=r,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,s)=>{const n=new Map,r=new Map;for(let i=s-1;i>=0;i--){const o=t[i];if(n.has(o.lane))continue;const a=r.get(o.lane);if(a==null||o.end>a.end?r.set(o.lane,o):o.end<a.end&&n.set(o.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((i,o)=>i.end===o.end?i.index-o.index:i.end-o.end)[0]:void 0},this.getMeasurementOptions=Ue(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,s,n,r,i,o,a)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:s,scrollMargin:n,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a}),{key:!1}),this.getMeasurements=Ue(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:s,scrollMargin:n,getItemKey:r,enabled:i,lanes:o,laneAssignmentMode:a},u)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const h of this.laneAssignments.keys())h>=t&&this.laneAssignments.delete(h);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(h=>{this.itemSizeCache.set(h.key,h.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),d=new Array(o).fill(void 0);for(let h=0;h<l;h++){const f=c[h];f&&(d[f.lane]=h)}for(let h=l;h<t;h++){const f=r(h),p=this.laneAssignments.get(h);let g,m;const v=a==="estimate"||u.has(f);if(p!==void 0&&this.options.lanes>1){g=p;const w=d[g],R=w!==void 0?c[w]:void 0;m=R?R.end+this.options.gap:s+n}else{const w=this.options.lanes===1?c[h-1]:this.getFurthestMeasurement(c,h);m=w?w.end+this.options.gap:s+n,g=w?w.lane:h%this.options.lanes,this.options.lanes>1&&v&&this.laneAssignments.set(h,g)}const S=u.get(f),C=typeof S=="number"?S:this.options.estimateSize(h),b=m+C;c[h]={index:h,start:m,size:C,end:b,key:f,lane:g},d[g]=h}return this.measurementsCache=c,c},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ue(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,s,n,r)=>this.range=t.length>0&&s>0?ju({measurements:t,outerSize:s,scrollOffset:n,lanes:r}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ue(()=>{let t=null,s=null;const n=this.calculateRange();return n&&(t=n.startIndex,s=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,s]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,s]},(t,s,n,r,i)=>r===null||i===null?[]:t({startIndex:r,endIndex:i,overscan:s,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const s=this.options.indexAttribute,n=t.getAttribute(s);return n?parseInt(n,10):(console.warn(`Missing attribute name '${s}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var s;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const n=this.scrollState.index??((s=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:s.index);if(n!==void 0&&this.range){const r=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,n-r),o=Math.min(this.options.count-1,n+r);return t>=i&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((i,o)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(o))});return}const s=this.indexFromElement(t),n=this.options.getItemKey(s),r=this.elementsCache.get(n);r!==t&&(r&&this.observer.unobserve(r),this.observer.observe(t),this.elementsCache.set(n,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(s)&&this.resizeItem(s,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,s)=>{var n;const r=this.measurementsCache[t];if(!r)return;const i=s-(this.itemSizeCache.get(r.key)??r.size);i!==0&&(((n=this.scrollState)==null?void 0:n.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,i,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,s)),this.notify(!1))},this.getVirtualItems=Ue(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,s)=>{const n=[];for(let r=0,i=t.length;r<i;r++){const o=s[t[r]];n.push(o)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const s=this.getMeasurements();if(s.length!==0)return hr(s[Wi(0,s.length-1,n=>hr(s[n]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,s,n=0)=>{if(!this.scrollElement)return 0;const r=this.getSize(),i=this.getScrollOffset();s==="auto"&&(s=t>=i+r?"end":"start"),s==="center"?t+=(n-r)/2:s==="end"&&(t-=r);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,s="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[t];if(!i)return;if(s==="auto")if(i.end>=r+n-this.options.scrollPaddingEnd)s="end";else if(i.start<=r+this.options.scrollPaddingStart)s="start";else return[r,s];if(s==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),s];const o=s==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,s,i.size),s]},this.scrollToOffset=(t,{align:s="start",behavior:n="auto"}={})=>{const r=this.getOffsetForAlignment(t,s),i=this.now();this.scrollState={index:null,align:s,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:s="auto",behavior:n="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const r=this.getOffsetForIndex(t,s);if(!r)return;const[i,o]=r,a=this.now();this.scrollState={index:t,align:o,behavior:n,startedAt:a,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:s="auto"}={})=>{const n=this.getScrollOffset()+t,r=this.now();this.scrollState={index:null,align:"start",behavior:s,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const s=this.getMeasurements();let n;if(s.length===0)n=this.options.paddingStart;else if(this.options.lanes===1)n=((t=s[s.length-1])==null?void 0:t.end)??0;else{const r=Array(this.options.lanes).fill(null);let i=s.length-1;for(;i>=0&&r.some(o=>o===null);){const o=s[i];r[o.lane]===null&&(r[o.lane]=o.end),i--}n=Math.max(...r.filter(o=>o!==null))}return Math.max(n-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:s,behavior:n})=>{this.options.scrollToFn(t,{behavior:n,adjustments:s},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const e=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,t=e?e[0]:this.scrollState.lastTargetOffset,s=1,n=t!==this.scrollState.lastTargetOffset;if(!n&&Pu(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=s){this.scrollState=null;return}}else this.scrollState.stableFrames=0,n&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior="auto",this._scrollToOffset(t,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}},Wi=(e,t,s,n)=>{for(;e<=t;){const r=(e+t)/2|0,i=s(r);if(i<n)e=r+1;else if(i>n)t=r-1;else return r}return e>0?e-1:0};function ju({measurements:e,outerSize:t,scrollOffset:s,lanes:n}){const r=e.length-1,i=u=>e[u].start;if(e.length<=n)return{startIndex:0,endIndex:r};let o=Wi(0,r,i,s),a=o;if(n===1)for(;a<r&&e[a].end<s+t;)a++;else if(n>1){const u=Array(n).fill(0);for(;a<r&&u.some(c=>c<s+t);){const c=e[a];u[c.lane]=c.end,a++}const l=Array(n).fill(s+t);for(;o>=0&&l.some(c=>c>=s);){const c=e[o];l[c.lane]=c.start,o--}o=Math.max(0,o-o%n),a=Math.min(r,a+(n-1-a%n))}return{startIndex:o,endIndex:a}}var mr=typeof document<"u"?I.useLayoutEffect:I.useEffect;function Uu({useFlushSync:e=!0,...t}){const s=I.useReducer(()=>({}),{})[1],n={...t,onChange:(i,o)=>{var a;e&&o?(0,xu.flushSync)(s):s(),(a=t.onChange)==null||a.call(t,i,o)}},[r]=I.useState(()=>new $u(n));return r.setOptions(n),mr(()=>r._didMount(),[]),mr(()=>r._willUpdate()),r}function gh(e){return Uu({observeElementRect:Lu,observeElementOffset:Nu,scrollToFn:Du,...e})}var Gs=class extends Error{missingFeature;constructor(e){super(Bu(e)),this.name="UnsupportedResponseStreamError",this.missingFeature=e}};function Bu(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 Gu(e){if(!e.body)throw new Gs("Response.body");if(typeof e.body.getReader!="function")throw new Gs("Response.body.getReader");return e.body.getReader()}function Hu(){if(typeof globalThis.TextDecoder!="function")throw new Gs("TextDecoder");return new globalThis.TextDecoder}function zu(e){if(!e.startsWith("data:"))return e;const t=e.slice(5);return t.startsWith(" ")?t.slice(1):t}var Vu=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 ie(e,t){return e>>>t|e<<32-t}function qu(e){const t=new TextEncoder().encode(e),s=t.length*8,n=t.length+1,r=n+(56-n%64+64)%64+8,i=new Uint8Array(r);i.set(t),i[t.length]=128;const o=new DataView(i.buffer);o.setUint32(r-8,Math.floor(s/4294967296)),o.setUint32(r-4,s>>>0);let a=1779033703,u=3144134277,l=1013904242,c=2773480762,d=1359893119,h=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,L=g[E-2]??0,F=ie(x,7)^ie(x,18)^x>>>3,$=ie(L,17)^ie(L,19)^L>>>10;g[E]=(g[E-16]??0)+F+(g[E-7]??0)+$>>>0}let S=a,C=u,b=l,w=c,R=d,y=h,_=f,T=p;for(let E=0;E<64;E++){const x=ie(R,6)^ie(R,11)^ie(R,25),L=R&y^~R&_,F=T+x+L+(Vu[E]??0)+(g[E]??0)>>>0,$=(ie(S,2)^ie(S,13)^ie(S,22))+(S&C^S&b^C&b)>>>0;T=_,_=y,y=R,R=w+F>>>0,w=b,b=C,C=S,S=F+$>>>0}a=a+S>>>0,u=u+C>>>0,l=l+b>>>0,c=c+w>>>0,d=d+R>>>0,h=h+y>>>0,f=f+_>>>0,p=p+T>>>0}const m=v=>(v>>>0).toString(16).padStart(8,"0");return m(a)+m(u)+m(l)+m(c)+m(d)+m(h)+m(f)+m(p)}function Qu(e){return`sha256:${qu(e)}`}function Hs(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!="object")throw new TypeError("Interrupt values must be JSON-compatible.");if(t.has(e))throw new TypeError("Interrupt values must not cycle.");if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError("Interrupt values must use plain JSON objects.");t.add(e);let s;if(Array.isArray(e)){const n=[];for(let r=0;r<e.length;r++)n.push(Hs(e[r],t));s=`[${n.join(",")}]`}else{const n=e;s=`{${Object.keys(n).sort().map(r=>`${JSON.stringify(r)}:${Hs(n[r],t)}`).join(",")}}`}return t.delete(e),s}function We(e){return Hs(e,new WeakSet)}function Ke(e,t=Qu){if(typeof e!="string")throw new TypeError("Interrupt digests require canonical JSON text.");return t(e)}function Ki(e){e===null||typeof e!="object"||Object.isFrozen(e)||(Object.values(e).forEach(Ki),Object.freeze(e))}function z(e){const t=JSON.parse(We(e));return Ki(t),t}function Wu(e){const t=[...e].sort((r,i)=>r.interruptId.localeCompare(i.interruptId)),s=z(t),n=We(s);return Object.freeze({resolutions:s,canonicalResolutions:n,fingerprint:Ke(n)})}function vr(e){const t={};for(const[s,n]of Object.entries(e))s!=="$schema"&&(t[s]=n);return t}function Ji(e){return(typeof e=="object"||typeof e=="function")&&e!==null}function Zt(e){if(!Ji(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 be(e){return Ji(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 Ku(e){return Object.keys(e).length>0?e:void 0}function Dt(e,t=[]){const s={...e},n={};if(s.type==="object"&&s.properties){const r={...s.properties},i=Object.keys(r),o={};for(const a of i){const u=r[a];if(!u)continue;const l=!t.includes(a);let c=!1,d;if(u.type==="object"&&u.properties){const h=Dt(u,u.required||[]);r[a]=l?{...h.schema,type:["object","null"]}:h.schema,c=l,d=h.nullWidening}else if(u.type==="array"&&u.items){const h=Array.isArray(u.items)?u.items[0]:u.items,f=h?Dt(h,h.required||[]):void 0;r[a]={...u,items:f?f.schema:u.items,...l?{type:["array","null"]}:{}},c=l,d=f?.nullWidening?{items:f.nullWidening}: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||d)&&(o[a]={...d??{},...c?{widened:!0}:{}})}s.properties=r,s.required=i,s.additionalProperties=!1,Object.keys(o).length>0&&(n.properties=o)}if(s.type==="array"&&s.items){const r=Array.isArray(s.items)?s.items[0]:s.items;if(r){const i=Dt(r,r.required||[]);s.items=i.schema,i.nullWidening&&(n.items=i.nullWidening)}}return{schema:s,nullWidening:Ku(n)}}function Ju(e){if(Zt(e)){const t=vr(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(be(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:vr(e)}function zs(e,t={}){if(!e)return;const{forStructuredOutput:s=!1}=t;if(!s&&!Zt(e)&&!be(e))return e;const n=Ju(e);return!n||typeof n!="object"||!s?n:Dt(n,n.required||[]).schema}var Xu=class extends Error{name="StandardSchemaValidationError";issues;constructor(e){super(`Validation failed: ${e.map(t=>t.message||"Validation failed").join(", ")}`),this.issues=e}};function Yu(e,t){if(!be(e))return t;const s=e["~standard"].validate(t);if(s instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!s.issues)return s.value;throw new Xu(s.issues)}var Zu=new Set(["$schema","$id","$ref","$defs","type","properties","required","additionalProperties","items","oneOf","anyOf","allOf","enum","const","format","minimum","maximum","minLength","maxLength","pattern"]);function Xi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function vn(e){return Xi(e)&&Object.keys(e).some(t=>Zu.has(t))}function ec(e){return be(e)||Zt(e)||vn(e)}function tc(e){if(!Xi(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(s=>s==="approve"||s==="reject")&&t.every(s=>ec(e[s]))}function sc(e){const t={};for(const[s,n]of Object.entries(e))t[s]=n;return t}function st(e){if(be(e)){const t=Zt(e)?sc(e["~standard"].jsonSchema.input({target:"draft-2020-12"})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(vn(e))return{source:e,jsonSchema:e};throw new TypeError("Expected a supported SchemaInput.")}function Sr(e){const t={approved:{const:e.approved}},s=["approved"];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},s.push("payload")),{type:"object",properties:t,required:s,additionalProperties:!1}}function nc(e,t){const s=t===void 0?null:st(t);let n=null,r=null;if(e!==void 0)if(be(e)||vn(e))n=st(e),r=n;else if(tc(e))n=e.approve===void 0?null:st(e.approve),r=e.reject===void 0?null:st(e.reject);else throw new TypeError("approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.");const i={oneOf:[Sr({approved:!0,payload:n,inputSchema:s}),Sr({approved:!1,payload:r,inputSchema:null})]},o=We(i),a=We({approve:n?.jsonSchema??null,reject:r?.jsonSchema??null});return{branches:{approve:n,reject:r},responseSchema:i,responseSchemaHash:Ke(o),approvalSchemaHash:Ke(a)}}function yr(e){if(e===void 0)return Ke("undefined");const t=st(e).jsonSchema??{standardValidator:"unserialized"};return Ke(We(t))}var rc="tanstack:interruptBinding",ic=new Set(["text","image","audio","video","document"]);function oc(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.type!="string"||!ic.has(t.type))return!1;if(t.type==="text")return typeof t.content=="string";const s=t.source;if(typeof s!="object"||s===null)return!1;const n=s;return typeof n.value!="string"?!1:n.type==="data"?typeof n.mimeType=="string":n.type==="url"}function ac(e){return Array.isArray(e)&&e.length>0&&e.every(oc)}function Yi(e){return typeof e=="string"||ac(e)?e:JSON.stringify(e)}function lc(e){return e.type==="text"||e.type==="image"||e.type==="audio"||e.type==="video"||e.type==="document"}function uc(e){try{return JSON.stringify(e)}catch{return""}}function Zi(e){return e.length===0?null:e.every(t=>t.type==="text")?e.map(t=>t.content).join("")||null:e}function Ir(e){return e===null?"":typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.content).join("")}function cc(e){return e.role==="system"?[]:e.role!=="assistant"?[dc(e)]:fc(e)}function dc(e){const t=[];for(const s of e.parts)lc(s)&&t.push(s);return{id:e.id,role:e.role,content:Zi(t),...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function Rr(){return{contentParts:[],toolCalls:[]}}function hc(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 fc(e){const t=[];let s=Rr(),n=[];const r=new Set;function i(){const o=Zi(s.contentParts),a=o!==null,u=s.toolCalls.length>0;(a||u)&&(t.push({id:e.id,role:"assistant",content:o,...u&&{toolCalls:s.toolCalls},...n.length>0&&{thinking:n},...e.createdAt!==void 0&&{createdAt:e.createdAt}}),n=[]),s=Rr()}for(const o of e.parts)switch(o.type){case"text":case"image":case"audio":case"video":case"document":s.contentParts.push(o);break;case"tool-call":hc(o)&&s.toolCalls.push({id:o.id,type:"function",function:{name:o.name,arguments:o.arguments},...o.metadata!==void 0&&{metadata:o.metadata}});break;case"tool-result":i(),(o.state==="complete"||o.state==="error")&&!r.has(o.toolCallId)&&(t.push({id:e.id,role:"tool",content:o.content,toolCallId:o.toolCallId,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),r.add(o.toolCallId));break;case"thinking":o.content&&n.push({content:o.content,...o.signature&&{signature:o.signature}});break;case"structured-output":if(o.status==="complete"){const a=o.raw!==""?o.raw:o.data!==void 0?uc(o.data):"";a!==""&&s.contentParts.push({type:"text",content:a})}}i();for(const o of e.parts)if(o.type==="tool-call"&&(o.output!==void 0&&!r.has(o.id)&&(t.push({id:e.id,role:"tool",content:Yi(o.output),toolCallId:o.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),r.add(o.id)),o.output===void 0&&o.state==="approval-responded"&&o.approval?.approved!==void 0&&!r.has(o.id))){const a=o.approval.approved;t.push({id:e.id,role:"tool",content:JSON.stringify({approved:a,...a&&{pendingExecution:!0},message:a?"User approved this action":"User denied this action"}),toolCallId:o.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),r.add(o.id)}return t.length===0&&t.push({id:e.id,role:"assistant",content:null,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),t}function Vs(e,t){const s=[];if(e.role==="assistant"&&e.thinking?.length)for(const n of e.thinking)n.content&&s.push({type:"thinking",content:n.content,...n.signature&&{signature:n.signature}});if(e.role==="tool"&&e.toolCallId)s.push({type:"tool-result",toolCallId:e.toolCallId,content:Ir(e.content),state:"complete"});else if(Array.isArray(e.content))for(const n of e.content)s.push(n);else{const n=Ir(e.content);n&&s.push({type:"text",content:n})}if(e.toolCalls&&e.toolCalls.length>0)for(const n of e.toolCalls){let r;try{r=JSON.parse(n.function.arguments)}catch{r=void 0}s.push({type:"tool-call",id:n.id,name:n.function.name,arguments:n.function.arguments,state:"input-complete",...r!==void 0&&{input:r},...n.metadata!==void 0&&{metadata:n.metadata}})}return{id:t||ve(),role:e.role==="tool"?"assistant":e.role,parts:s,...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function gc(e){if("parts"in e)return{...e,id:e.id||ve()};const t=e.id||ve();switch(e.role){case"user":return{id:t,role:"user",parts:pc(e.content)};case"assistant":return Vs({role:"assistant",content:e.content??null,...e.toolCalls&&{toolCalls:e.toolCalls}},t);case"tool":return Vs({role:"tool",content:e.content,toolCallId:e.toolCallId},t);case"system":case"developer":return{id:t,role:"system",parts:e.content?[{type:"text",content:e.content}]:[]};case"reasoning":return{id:t,role:"assistant",parts:e.content?[{type:"thinking",content:e.content}]:[]};default:return{id:t,role:"assistant",parts:[]}}}function pc(e){if(typeof e=="string")return e?[{type:"text",content:e}]:[];const t=[];for(const s of e)s.type==="text"?t.push({type:"text",content:s.text}):s.type!=="binary"&&t.push(s);return t}function mc(e,t){return"parts"in e?{...e,id:e.id||t(),createdAt:e.createdAt||new Date}:{...Vs(e,t()),createdAt:e.createdAt??new Date}}function ve(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}var Cr=Je((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})),vc=Je((e=>{var t=e&&e.__createBinding||(Object.create?(function(l,c,d,h){h===void 0&&(h=d);var f=Object.getOwnPropertyDescriptor(c,d);(!f||("get"in f?!c.__esModule:f.writable||f.configurable))&&(f={enumerable:!0,get:function(){return c[d]}}),Object.defineProperty(l,h,f)}):(function(l,c,d,h){h===void 0&&(h=d),l[h]=c[d]})),s=e&&e.__exportStar||function(l,c){for(var d in l)d!=="default"&&!Object.prototype.hasOwnProperty.call(c,d)&&t(c,l,d)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var n=Cr();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return n.Allow}}),s(Cr(),e);var r=class extends Error{};e.PartialJSON=r;var i=class extends Error{};e.MalformedJSON=i;function o(l,c=n.Allow.ALL){if(typeof l!="string")throw new TypeError(`expecting str, got ${typeof l}`);if(!l.trim())throw new Error(`${l} is empty`);return a(l.trim(),c)}e.parseJSON=o;var a=(l,c)=>{const d=l.length;let h=0;const f=w=>{throw new r(`${w} at position ${h}`)},p=w=>{throw new i(`${w} at position ${h}`)},g=()=>(b(),h>=d&&f("Unexpected end of input"),l[h]==='"'?m():l[h]==="{"?v():l[h]==="["?S():l.substring(h,h+4)==="null"||n.Allow.NULL&c&&d-h<4&&"null".startsWith(l.substring(h))?(h+=4,null):l.substring(h,h+4)==="true"||n.Allow.BOOL&c&&d-h<4&&"true".startsWith(l.substring(h))?(h+=4,!0):l.substring(h,h+5)==="false"||n.Allow.BOOL&c&&d-h<5&&"false".startsWith(l.substring(h))?(h+=5,!1):l.substring(h,h+8)==="Infinity"||n.Allow.INFINITY&c&&d-h<8&&"Infinity".startsWith(l.substring(h))?(h+=8,1/0):l.substring(h,h+9)==="-Infinity"||n.Allow._INFINITY&c&&1<d-h&&d-h<9&&"-Infinity".startsWith(l.substring(h))?(h+=9,-1/0):l.substring(h,h+3)==="NaN"||n.Allow.NAN&c&&d-h<3&&"NaN".startsWith(l.substring(h))?(h+=3,NaN):C()),m=()=>{const w=h;let R=!1;for(h++;h<d&&(l[h]!=='"'||R&&l[h-1]==="\\");)R=l[h]==="\\"?!R:!1,h++;if(l.charAt(h)=='"')try{return JSON.parse(l.substring(w,++h-Number(R)))}catch(y){p(String(y))}else if(n.Allow.STR&c)try{return JSON.parse(l.substring(w,h-Number(R))+'"')}catch{return JSON.parse(l.substring(w,l.lastIndexOf("\\"))+'"')}f("Unterminated string literal")},v=()=>{h++,b();const w={};try{for(;l[h]!=="}";){if(b(),h>=d&&n.Allow.OBJ&c)return w;const R=m();b(),h++;try{w[R]=g()}catch(y){if(n.Allow.OBJ&c)return w;throw y}b(),l[h]===","&&h++}}catch{if(n.Allow.OBJ&c)return w;f("Expected '}' at end of object")}return h++,w},S=()=>{h++;const w=[];try{for(;l[h]!=="]";)w.push(g()),b(),l[h]===","&&h++}catch{if(n.Allow.ARR&c)return w;f("Expected ']' at end of array")}return h++,w},C=()=>{if(h===0){l==="-"&&p("Not sure what '-' is");try{return JSON.parse(l)}catch(R){if(n.Allow.NUM&c)try{return JSON.parse(l.substring(0,l.lastIndexOf("e")))}catch{}p(String(R))}}const w=h;for(l[h]==="-"&&h++;l[h]&&",]}".indexOf(l[h])===-1;)h++;h==d&&!(n.Allow.NUM&c)&&f("Unterminated number literal");try{return JSON.parse(l.substring(w,h))}catch{l.substring(w,h)==="-"&&f("Not sure what '-' is");try{return JSON.parse(l.substring(w,l.lastIndexOf("e")))}catch(y){p(String(y))}}},b=()=>{for(;h<d&&`
|
|
8
|
-
\r `.includes(l[h]);)h++};return g()},u=o;e.parse=u})),Sc=vc(),yc=class{parse(e){if(!(!e||e.trim()===""))try{return(0,Sc.parse)(e)}catch{return}}},eo=new yc;function Ic(e){return eo.parse(e)}var Rc=class{shouldEmit(e,t){return!0}};function Cc(e){const t=e?.metadata;return typeof t=="object"&&t!==null&&t.providerExecuted===!0?t:null}function wc(e){return Cc(e)!==null}function bc(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type==="text"?r[r.length-1]={type:"text",content:s}:r.push({type:"text",content:s}),{...n,parts:r}})}function Tt(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.find(l=>l.type==="tool-call"&&l.id===s.id),o=s.metadata??i?.metadata,a=s.input??i?.input,u={type:"tool-call",id:s.id,name:s.name,arguments:s.arguments,state:s.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...a!==void 0&&{input:a},...o!==void 0&&{metadata:o}};return i?r[r.indexOf(i)]=u:r.push(u),{...n,parts:r}})}function Ss(e,t,s,n,r,i){return e.map(o=>{if(o.id!==t)return o;const a=[...o.parts],u=a.findIndex(c=>c.type==="tool-result"&&c.toolCallId===s),l={type:"tool-result",toolCallId:s,content:n,state:r,...i&&{error:i}};return u>=0?a[u]=l:a.push(l),{...o,parts:a}})}function wr(e,t,s,n){return e.map(r=>{if(r.id!==t)return r;const i=[...r.parts],o=i.find(a=>a.type==="tool-call"&&a.id===s);if(o){const a=i.indexOf(o);i[a]={...o,state:"approval-requested",approval:{id:n,needsApproval:!0}}}return{...r,parts:i}})}function ys(e,t,s,n,r){return e.map(i=>{const o=[...i.parts],a=o.find(u=>u.type==="tool-call"&&u.id===t);if(a){const u=o.indexOf(a);o[u]={...a,output:r?{error:r}:s,state:n??(r?"error":"complete")}}return{...i,parts:o}})}function Ec(e,t,s){return e.map(n=>{const r=[...n.parts],i=r.find(o=>o.type==="tool-call"&&o.approval?.id===t);if(i&&i.approval){const o=r.indexOf(i);r[o]={...i,approval:{...i.approval,approved:s},state:"approval-responded"}}return{...n,parts:r}})}function _c(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.findIndex(d=>d.type==="structured-output"),o=i>=0?r[i]:null,a=(o?.raw??"")+s,u=Ic(a),l=u??o?.partial,c={type:"structured-output",status:"streaming",raw:a,...l!==void 0?{partial:l}:{},...o?.reasoning!==void 0?{reasoning:o.reasoning}:{}};return i>=0?r[i]=c:r.push(c),{...n,parts:r}})}function Tc(e,t,s,n,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(d=>d.type==="structured-output"),u=a>=0?o[a].raw:"";let l=n||u;if(l===""&&s!==void 0)try{l=JSON.stringify(s)}catch{}const c={type:"structured-output",status:"complete",data:s,partial:s,raw:l,...r!==void 0?{reasoning:r}:{}};return a>=0?o[a]=c:o.push(c),{...i,parts:o}})}function br(e,t,s){return e.map(n=>{if(n.id!==t)return n;const r=[...n.parts],i=r.findIndex(a=>a.type==="structured-output");if(i<0)return r.push({type:"structured-output",status:"error",raw:"",errorMessage:s}),{...n,parts:r};const o=r[i];return o.status==="complete"?n:(r[i]={...o,status:"error",errorMessage:s},{...n,parts:r})})}function Is(e,t,s,n,r){return e.map(i=>{if(i.id!==t)return i;const o=[...i.parts],a=o.findIndex(l=>l.type==="thinking"&&l.stepId===s),u={type:"thinking",content:n,stepId:s,...r&&{signature:r}};return a>=0?o[a]=u:o.push(u),{...i,parts:o}})}var Mc=12,xc=class to{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;recording=null;recordingStartTime=0;constructor(t={}){this.chunkStrategy=t.chunkStrategy||new Rc,this.events=t.events||{},this.jsonParser=t.jsonParser||eo,this.recordingEnabled=t.recording??!1,t.initialMessages&&(this.messages=[...t.initialMessages])}setMessages(t){this.messages=[...t],this.emitMessagesChange()}addUserMessage(t,s){const n=typeof t=="string"?[{type:"text",content:t}]:t.map(i=>i),r={id:s??ve(),role:"user",parts:n,createdAt:new Date};return this.messages=[...this.messages,r],this.emitMessagesChange(),r}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(t){this.prepareAssistantMessage();const{messageId:s}=this.ensureAssistantMessage(t);return this.pendingManualMessageId=s,s}getCurrentAssistantMessageId(){let t=null;for(const[s,n]of this.messageStates)n.role==="assistant"&&(t=s);return t}addToolResult(t,s,n){const r=this.messages.find(u=>u.parts.some(l=>l.type==="tool-call"&&l.id===t));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${t}`);return}let i=ys(this.messages,t,s,n?"error":void 0,n);const o=Yi(s),a=n?"error":"complete";i=Ss(i,r.id,t,o,a,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(t,s){this.messages=Ec(this.messages,t,s),this.emitMessagesChange()}toModelMessages(){const t=[];for(const s of this.messages)t.push(...cc(s));return t}getMessages(){return this.messages}areAllToolsComplete(){const t=this.messages.findLast(r=>r.role==="assistant");if(!t)return!0;const s=t.parts.filter(r=>r.type==="tool-call");if(s.length===0)return!0;const n=new Set(t.parts.filter(r=>r.type==="tool-result").map(r=>r.toolCallId));return s.every(r=>r.state==="complete"||r.state==="approval-responded"||r.output!==void 0&&!r.approval||n.has(r.id)||wc(r))}removeMessagesAfter(t){const s=new Set(this.messages.slice(0,t+1).map(n=>n.id));for(const n of this.structuredMessageIds)s.has(n)||this.structuredMessageIds.delete(n);for(const n of this.structuredOutputUpdateBatches.keys())s.has(n)||this.structuredOutputUpdateBatches.delete(n);for(const n of this.messageStates.keys())s.has(n)||this.messageStates.delete(n);for(const[n,r]of this.toolCallToMessage)s.has(r)||this.toolCallToMessage.delete(n);for(const n of this.activeMessageIds)s.has(n)||this.activeMessageIds.delete(n);this.messages=this.messages.slice(0,t+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(t){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(const s of t)this.processChunk(s);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(t){switch(this.recording&&this.recording.chunks.push({chunk:t,timestamp:Date.now(),index:this.recording.chunks.length}),t.type){case"TEXT_MESSAGE_START":this.handleTextMessageStartEvent(t);break;case"TEXT_MESSAGE_CONTENT":this.handleTextMessageContentEvent(t);break;case"TEXT_MESSAGE_END":this.handleTextMessageEndEvent(t);break;case"TOOL_CALL_START":this.handleToolCallStartEvent(t);break;case"TOOL_CALL_ARGS":this.handleToolCallArgsEvent(t);break;case"TOOL_CALL_END":this.handleToolCallEndEvent(t);break;case"RUN_FINISHED":this.handleRunFinishedEvent(t);break;case"RUN_ERROR":this.handleRunErrorEvent(t);break;case"STEP_FINISHED":this.handleStepFinishedEvent(t);break;case"MESSAGES_SNAPSHOT":this.handleMessagesSnapshotEvent(t);break;case"CUSTOM":this.handleCustomEvent(t);break;case"RUN_STARTED":this.handleRunStartedEvent(t);break;case"REASONING_START":case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"REASONING_MESSAGE_CONTENT":this.handleReasoningMessageContentEvent(t);break;case"TOOL_CALL_RESULT":this.handleToolCallResultEvent(t);break;case"STEP_STARTED":this.handleStepStartedEvent(t)}}createMessageState(t,s){const n={id:t,role:s,totalTextContent:"",currentSegmentText:"",lastEmittedText:"",hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(t,n),n}getMessageState(t){return this.messageStates.get(t)}consumePendingThinkingStep(t){if(!this.pendingThinkingStepId)return;const s=this.pendingThinkingStepId;t.currentThinkingStepId=s,t.thinkingSteps.has(s)||(t.thinkingSteps.set(s,""),t.thinkingStepOrder.push(s)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){const t=Array.from(this.activeMessageIds).reverse();for(const s of t){const n=this.messageStates.get(s);if(n&&n.role==="assistant")return s}return null}ensureAssistantMessage(t){if(t){const o=this.getMessageState(t);if(o)return{messageId:t,state:o}}const s=this.getActiveAssistantMessageId();if(s){const o=this.getMessageState(s);if(o)return{messageId:s,state:o}}if(t){const o=this.messages.find(a=>a.id===t);if(o){const a=this.createMessageState(t,o.role);this.activeMessageIds.add(t);const u=o.parts.length>0?o.parts[o.parts.length-1]:null;return u&&u.type==="text"&&(a.currentSegmentText=u.content,a.lastEmittedText=u.content,a.totalTextContent=u.content),{messageId:t,state:a}}}const n=t||ve(),r={id:n,role:"assistant",parts:[],createdAt:new Date};this.messages=[...this.messages,r];const i=this.createMessageState(n,"assistant");return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}handleTextMessageStartEvent(t){const{messageId:s,role:n}=t,r=n==="user"||n==="system"?n:"assistant";if(this.pendingManualMessageId){const o=this.pendingManualMessageId;if(this.pendingManualMessageId=null,o!==s){this.messages=this.messages.map(u=>u.id===o?{...u,id:s}:u);const a=this.messageStates.get(o);a&&(a.id=s,this.messageStates.delete(o),this.messageStates.set(s,a)),this.activeMessageIds.delete(o),this.activeMessageIds.add(s)}this.messageStates.has(s)||(this.createMessageState(s,r),this.activeMessageIds.add(s)),this.emitMessagesChange();return}if(this.messages.find(o=>o.id===s)){this.activeMessageIds.add(s);const o=this.messageStates.get(s);o?o.hasToolCallsSinceTextStart&&(o.currentSegmentText!==o.lastEmittedText&&this.emitTextUpdateForMessage(s),o.currentSegmentText="",o.lastEmittedText="",o.hasToolCallsSinceTextStart=!1):this.createMessageState(s,r);return}const i={id:s,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(s,r),this.activeMessageIds.add(s),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(t){const{messageId:s}=t,n=this.getMessageState(s);n&&(n.isComplete||(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),this.completeAllToolCallsForMessage(s)))}handleMessagesSnapshotEvent(t){this.resetStreamState();const s=this.messages,n=t.messages.map(gc);this.messages=this.reconcileSnapshotToolCalls(n,s),this.emitMessagesChange()}reconcileSnapshotToolCalls(t,s){const n=new Map;for(const o of s)for(const a of o.parts)a.type==="tool-call"&&n.set(a.id,a);const r=new Set;for(const o of t)for(const a of o.parts)a.type==="tool-call"&&r.add(a.id);const i=[];for(const o of t){const a=o.role==="assistant"&&o.parts.length===1?o.parts.find(c=>c.type==="tool-result"):void 0;if(!a){i.push(o);continue}const u=i.findLast(c=>c.parts.some(d=>d.type==="tool-call"&&d.id===a.toolCallId))??i.findLast(c=>c.role==="assistant"&&!(c.parts.length===1&&c.parts[0]?.type==="tool-result"));if(!u){r.has(a.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${a.toolCallId}") will not be able to locate this call`),i.push(o);continue}const l=[...u.parts];if(!r.has(a.toolCallId)&&!l.some(c=>c.type==="tool-call"&&c.id===a.toolCallId)){const c=n.get(a.toolCallId);c?(l.push({...c}),r.add(c.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${a.toolCallId}") will not be able to locate this call`)}l.push(a),u.parts=l}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(t,s){const n=new Map;for(const r of t)for(const i of r.parts)i.type==="tool-result"&&n.set(i.toolCallId,i);return t.map(r=>{const i=r.parts.map(o=>{if(o.type!=="tool-call")return o;const a=s.get(o.id),u=n.get(o.id);let l=o;if(a&&(a.output!==void 0||a.state==="complete"||a.state==="error")&&(o.output===void 0||o.state==="input-complete"||o.state==="input-streaming"||o.state==="awaiting-input")&&(l={...o,...a.output!==void 0?{output:a.output}:{},state:a.state,...a.approval!==void 0?{approval:a.approval}:{},...a.metadata!==void 0?{metadata:a.metadata}:{}}),u&&l.output===void 0){let c;if(Array.isArray(u.content))c=u.content;else try{c=JSON.parse(u.content)}catch{c=u.content}const d=u.state==="error"?this.extractToolResultError(c):void 0;l={...l,output:d?{error:d}:c,state:u.state==="error"?"error":"complete"}}return l});return i.some((o,a)=>o!==r.parts[a])?{...r,parts:i}:r})}handleTextMessageContentEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(t.messageId);if(this.completeAllToolCallsForMessage(s),this.structuredMessageIds.has(s)){let c=t.delta||"";if(c===""&&t.content!==void 0&&t.content!==""){const d=(this.messages.find(h=>h.id===s)?.parts.find(h=>h.type==="structured-output")??{raw:""}).raw;t.content.startsWith(d)?c=t.content.slice(d.length):d.startsWith(t.content)?c="":c=t.content}c!==""&&(this.messages=_c(this.messages,s,c),n.totalTextContent+=c,this.queueStructuredOutputUpdate(s,c),this.emitMessagesChange());return}const r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(t,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),n.currentSegmentText="",n.lastEmittedText="",n.hasToolCallsSinceTextStart=!1);const i=n.currentSegmentText;let o=i;const a=t.delta||"";a!==""?o=i+a:t.content!==void 0&&t.content!==""&&(t.content.startsWith(i)?o=t.content:i.startsWith(t.content)?o=i:o=i+t.content);const u=o.slice(i.length);n.currentSegmentText=o,n.totalTextContent+=u;const l=t.delta||t.content||"";this.chunkStrategy.shouldEmit(l,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s)}handleToolCallStartEvent(t){const s=t.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(s??void 0);r.hasToolCallsSinceTextStart=!0;const i=t.toolCallId;if(!r.toolCalls.get(i)){const o="awaiting-input",a=t.toolCallName??t.toolName,u=t.metadata,l={id:t.toolCallId,name:a,arguments:"",state:o,parsedArguments:void 0,index:t.index??r.toolCalls.size,...u!==void 0&&{metadata:u}};r.toolCalls.set(i,l),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=Tt(this.messages,n,{id:t.toolCallId,name:a,arguments:"",state:o,...u!==void 0&&{metadata:u}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,t.toolCallId,o,"")}}handleToolCallArgsEvent(t){const s=t.toolCallId,n=this.toolCallToMessage.get(s);if(!n)return;const r=this.getMessageState(n);if(!r)return;const i=r.toolCalls.get(s);if(!i)return;const o=i.state==="awaiting-input";i.arguments+=t.delta||"",o&&t.delta&&(i.state="input-streaming"),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=Tt(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(t){const s=this.toolCallToMessage.get(t.toolCallId);if(!s)return;const n=this.getMessageState(s);if(!n)return;const r=n.toolCalls.get(t.toolCallId);if(r&&r.state!=="input-complete"){if(t.input!==void 0&&!r.arguments)try{r.arguments=JSON.stringify(t.input)}catch{}const i=n.toolCallOrder.indexOf(t.toolCallId);this.completeToolCall(s,i,r),t.input!==void 0&&(r.parsedArguments=t.input,this.messages=Tt(this.messages,s,{id:r.id,name:r.name,arguments:r.arguments,state:"input-complete",input:t.input,...r.metadata!==void 0&&{metadata:r.metadata}}),this.emitMessagesChange())}if(t.result){let i;if(Array.isArray(t.result))i=t.result;else try{i=JSON.parse(t.result)}catch{i=t.result}this.messages=ys(this.messages,t.toolCallId,i,t.state==="output-error"?"error":void 0);const o=t.state==="output-error"?"error":"complete";this.messages=Ss(this.messages,s,t.toolCallId,t.result,o,o==="error"?this.extractToolResultError(i):void 0),this.emitMessagesChange()}}extractToolResultError(t){return t&&typeof t=="object"&&"error"in t&&typeof t.error=="string"?t.error:typeof t=="string"?t:"Tool execution failed"}handleToolCallResultEvent(t){const s=this.toolCallToMessage.get(t.toolCallId);if(!s)return;let n;try{n=JSON.parse(t.content)}catch{n=t.content}this.messages=ys(this.messages,t.toolCallId,n,t.state==="output-error"?"error":void 0);const r=t.state==="output-error"?"error":"complete";this.messages=Ss(this.messages,s,t.toolCallId,t.content,r,r==="error"?this.extractToolResultError(n):void 0),this.emitMessagesChange()}handleRunStartedEvent(t){this.activeRuns.add(t.runId)}handleRunFinishedEvent(t){this.finishReason=t.finishReason??null,this.activeRuns.delete(t.runId),t.outcome?.type==="interrupt"&&this.handleInterrupts(t.outcome.interrupts),this.activeRuns.size===0&&(this.isDone=!0,this.completeAllToolCalls(),this.finalizeStream())}handleInterrupts(t){for(const s of t){const n=s.metadata&&typeof s.metadata=="object"?s.metadata:{},r=typeof n.kind=="string"?n.kind:void 0,i=s.toolCallId;if(!i)continue;const o=typeof n.toolName=="string"?n.toolName:this.findToolCallName(i),a=Object.hasOwn(n,"input")?n.input:{};if(r==="approval"||s.reason==="approval_required"){const u=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(i)??this.messages.find(l=>l.role==="assistant"&&l.parts.some(c=>c.type==="tool-call"&&c.id===i))?.id;u&&(this.messages=wr(this.messages,u,i,s.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:i,toolName:o,input:a,approvalId:s.id});continue}(r==="client_tool"||s.reason==="client_tool_input")&&this.events.onToolCall?.({toolCallId:i,toolName:o,input:a})}}findToolCallName(t){for(const s of this.messageStates.values()){const n=s.toolCalls.get(t);if(n)return n.name}return""}handleRunErrorEvent(t){this.hasError=!0;const s="runId"in t&&typeof t.runId=="string"?t.runId:void 0;s?this.activeRuns.delete(s):this.activeRuns.clear();const{messageId:n}=this.ensureAssistantMessage(),r=t.message||t.error?.message||"An error occurred";!t.message&&!t.error?.message&&console.error("[StreamProcessor] RUN_ERROR with no message; original chunk:",t),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=br(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,"error"),this.emitMessagesChange());const i=new Error(r),o=t.code??t.error?.code;o!==void 0&&Object.assign(i,{code:o}),t.rawEvent!==void 0&&Object.assign(i,{rawEvent:t.rawEvent}),this.events.onError?.(i)}handleStepStartedEvent(t){const s=t.stepId??ve(),n=this.getActiveAssistantMessageId();if(n){const r=this.getMessageState(n);if(r){r.currentThinkingStepId=s,r.thinkingSteps.has(s)||(r.thinkingSteps.set(s,""),r.thinkingStepOrder.push(s)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=s}handleStepFinishedEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);if(n.hasSeenReasoningEvents){if(t.signature){const a=n.currentThinkingStepId??t.stepId;if(!a)return;const u=n.thinkingSteps.get(a);u!==void 0&&(n.thinkingStepSignatures.set(a,t.signature),this.messages=Is(this.messages,s,a,u,t.signature),this.emitMessagesChange())}return}this.consumePendingThinkingStep(n);const r=n.currentThinkingStepId??t.stepId??ve();n.thinkingSteps.has(r)||(n.thinkingSteps.set(r,""),n.thinkingStepOrder.push(r),n.currentThinkingStepId=r);const i=n.thinkingSteps.get(r)??"";let o=i;t.delta&&t.delta!==""?o=i+t.delta:t.content&&t.content!==""&&(t.content.startsWith(i)?o=t.content:i.startsWith(t.content)?o=i:o=i+t.content),n.thinkingSteps.set(r,o),t.signature&&n.thinkingStepSignatures.set(r,t.signature),this.messages=Is(this.messages,s,r,o,n.thinkingStepSignatures.get(r)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(s,r,o)}handleReasoningMessageContentEvent(t){const{messageId:s,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;const r=t.delta||"";this.consumePendingThinkingStep(n);const i=n.currentThinkingStepId??t.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,""),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);const o=(n.thinkingSteps.get(i)??"")+r;n.thinkingSteps.set(i,o),this.messages=Is(this.messages,s,i,o,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(s,i,o)}handleCustomEvent(t){const s=this.getActiveAssistantMessageId();if(t.name==="structured-output.start"&&t.value){const n=t.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??s??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:"start",messageId:r,status:"streaming",raw:""}));return}if(t.name==="structured-output.complete"&&t.value){const n=t.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??s??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=Tc(this.messages,r,n.object,n.raw??"",n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,"complete"),this.emitMessagesChange())}if(t.name==="tool-input-available"&&t.value){const{toolCallId:n,toolName:r,input:i}=t.value;this.events.onToolCall?.({toolCallId:n,toolName:r,input:i});return}if(t.name==="approval-requested"&&t.value){const{toolCallId:n,toolName:r,input:i,approval:o}=t.value,a=s??this.toolCallToMessage.get(n);a&&(this.messages=wr(this.messages,a,n,o.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:o.id});return}if(t.name==="ui-resource"&&t.value){const n=t.value,r=this.toolCallToMessage.get(n.toolCallId)??s;if(r){const i={type:"ui-resource",resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(o=>o.id===r?{...o,parts:[...o.parts,i]}:o),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){const n=t.value&&typeof t.value=="object"?t.value.toolCallId:void 0;this.events.onCustomEvent(t.name,t.value,{toolCallId:n})}}isNewTextSegment(t,s){return t.content!==void 0&&(t.content.length<s.length||!t.content.startsWith(s)&&!s.startsWith(t.content))}completeAllToolCalls(){for(const t of this.activeMessageIds)this.completeAllToolCallsForMessage(t)}completeAllToolCallsForMessage(t){const s=this.getMessageState(t);s&&s.toolCalls.forEach((n,r)=>{if(n.state!=="input-complete"){const i=s.toolCallOrder.indexOf(r);this.completeToolCall(t,i,n)}})}completeToolCall(t,s,n){n.state="input-complete",n.parsedArguments=this.jsonParser.parse(n.arguments),!this.isToolCallPartErrored(n.id)&&(this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=Tt(this.messages,t,{id:n.id,name:n.name,arguments:n.arguments,state:"input-complete",...n.parsedArguments!==void 0&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(t,n.id,"input-complete",n.arguments)))}isToolCallPartAwaitingUserAction(t){return this.messages.some(s=>s.parts?.some(n=>n.type==="tool-call"&&n.id===t&&(n.state==="approval-requested"||n.state==="approval-responded")))}isToolCallPartErrored(t){return this.messages.some(s=>s.parts?.some(n=>n.type==="tool-call"&&n.id===t&&n.state==="error"))}emitTextUpdateForMessage(t){const s=this.getMessageState(t);s&&(s.lastEmittedText=s.currentSegmentText,this.messages=bc(this.messages,t,s.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(t,s.currentSegmentText))}queueStructuredOutputUpdate(t,s){const n=this.structuredOutputUpdateBatches.get(t),r={delta:`${n?.delta??""}${s}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(t,r),r.chunkCount>=Mc&&this.flushStructuredOutputUpdate(t)}flushStructuredOutputUpdate(t){const s=this.structuredOutputUpdateBatches.get(t);!s||s.chunkCount===0||(this.structuredOutputUpdateBatches.delete(t),this.emitStructuredOutputChange(t,"update",s.delta))}emitStructuredOutputChange(t,s,n){const r=this.messages.find(i=>i.id===t)?.parts.find(i=>i.type==="structured-output");r&&this.events.onStructuredOutputChange?.({phase:s,messageId:t,status:r.status,raw:r.raw,...r.partial!==void 0?{partial:r.partial}:{},...r.data!==void 0?{data:r.data}:{},...r.reasoning!==void 0?{reasoning:r.reasoning}:{},...r.errorMessage!==void 0?{errorMessage:r.errorMessage}:{},...n!==void 0?{delta:n}:{}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){let t;for(const s of this.activeMessageIds){const n=this.getMessageState(s);if(!n)continue;this.completeAllToolCallsForMessage(s),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(s),n.isComplete=!0;const r=this.messages.find(i=>i.id===s);r&&r.role==="assistant"&&(t=r)}for(const s of this.structuredMessageIds)this.flushStructuredOutputUpdate(s),this.messages=br(this.messages,s,"Stream ended without structured-output.complete"),this.emitStructuredOutputChange(s,"error");if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),t&&!this.hasError&&this.isWhitespaceOnlyMessage(t)){this.messages=this.messages.filter(s=>s.id!==t.id),this.emitMessagesChange();return}t&&this.events.onStreamEnd?.(t)}getCompletedToolCalls(){const t=[];for(const s of this.messageStates.values())for(const n of s.toolCalls.values())n.state==="input-complete"&&t.push({id:n.id,type:"function",function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return t}getResult(){const t=this.getCompletedToolCalls();let s="",n="";for(const r of this.messageStates.values()){s+=r.totalTextContent;for(const i of r.thinkingStepOrder)n+=r.thinkingSteps.get(i)??""}return{content:s,thinking:n||void 0,toolCalls:t.length>0?t:void 0,finishReason:this.finishReason}}getState(){let t="",s="";const n=new Map,r=[];for(const i of this.messageStates.values()){t+=i.totalTextContent;for(const o of i.thinkingStepOrder)s+=i.thinkingSteps.get(o)??"";for(const[o,a]of i.toolCalls)n.set(o,a);r.push(...i.toolCallOrder)}return{content:t,thinking:s,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:"1.0",timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(t){return t.parts.length===0?!1:t.parts.every(s=>s.type==="text"&&s.content.trim()==="")}static async replay(t,s){return new to(s).process(Pc(t))}};function Pc(e){return{async*[Symbol.asyncIterator](){for(const{chunk:t}of e.chunks)yield t}}}function Ac(e){const t=[];for(const s of e){const n=s.parts??[];if(s.role==="system"){t.push({...s,content:n.length>0?qs(n):s.content??""});continue}if(s.role==="user"){t.push({...s,content:n.length>0?Oc(n):s.content??""});continue}for(const o of n)o.type==="thinking"&&t.push({role:"reasoning",id:Lc(s.id,o),content:o.content});const r=qs(n),i=Fc(n);t.push({...s,...r!==""&&{content:r},...i&&{toolCalls:i}});for(const o of n)o.type==="tool-result"&&t.push({role:"tool",id:Nc(o.toolCallId),toolCallId:o.toolCallId,content:typeof o.content=="string"?o.content:JSON.stringify(o.content),...o.error!==void 0&&{error:o.error}})}return t}function qs(e){const t=[];for(const s of e)s.type==="text"?t.push(s.content):s.type==="structured-output"&&s.status==="complete"&&s.raw!==""&&t.push(s.raw);return t.join("")}function Oc(e){if(!e.some(s=>s.type==="image"||s.type==="audio"||s.type==="video"||s.type==="document"))return qs(e);const t=[];for(const s of e)s.type==="text"?t.push({type:"text",text:s.content}):(s.type==="image"||s.type==="audio"||s.type==="video"||s.type==="document")&&t.push(s);return t}function Fc(e){const t=[];for(const s of e)s.type==="tool-call"&&t.push({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments}});return t.length>0?t:void 0}function Lc(e,t){return`${e}-reasoning-${t.id??kc(t.content)}`}function Nc(e){return`tool-${e}`}function kc(e){let t=0;for(let s=0;s<e.length;s++)t=t*31+e.charCodeAt(s)|0;return Math.abs(t).toString(36)}var Qs=(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})({}),so=new WeakMap;function Z(e){return so.get(e)??("runId"in e&&typeof e.runId=="string"?e.runId:void 0)}var no=class extends Error{constructor(){super("Stream ended with unterminated trailing data — connection was likely cut short."),this.name="StreamTruncatedError"}},Sn=class extends Error{constructor(e){super("Stream response body read failed",{cause:e}),this.name="StreamReadError"}},Dc=class extends Error{constructor(){super("Durable run ended without a terminal event and could not resume — the run did not complete."),this.name="DurableStreamIncompleteError"}},$c=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name="StreamReconnectLimitError"}};function jc(e){const t=e?.maxAttempts??5,s=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw new Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(s)||s<0)throw new Error(`Invalid reconnect.delayMs: ${s}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:s}}function Uc(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(s=>{const n=()=>{clearTimeout(r),s()},r=setTimeout(()=>{t?.removeEventListener("abort",n),s()},e);t?.addEventListener("abort",n,{once:!0})})}function Er(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Mt(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 xt(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((s,n)=>{t[n]=s}),t}return e}var Bc="X-Run-Id";function Gc(e){return e===void 0?{}:{[Bc]:e}}function yn(e,t){const s=e.indexOf("#"),n=s===-1?"":e.slice(s),r=s===-1?e:e.slice(0,s),i=r.indexOf("?"),o=i===-1?r:r.slice(0,i),a=new URLSearchParams(i===-1?"":r.slice(i+1));for(const[l,c]of Object.entries(t))a.set(l,c);const u=a.toString();return`${o}${u.length===0?"":`?${u}`}${n}`}async function*Hc(e,t){try{const s=Hu();let n="";for(;!t?.aborted;){let r;try{r=await e.read()}catch(u){if(t?.aborted)return;throw new Sn(u)}const{done:i,value:o}=r;if(i)break;n+=s.decode(o,{stream:!0});const a=n.split(`
|
|
9
|
-
`);n=a.pop()||"";for(const u of a){const l=u.endsWith("\r")?u.slice(0,-1):u;l.trim()&&(yield l)}}if(n+=s.decode(),n.trim()&&!t?.aborted)throw new no}finally{e.releaseLock()}}async function*zc(e,t){let s,n,r,i;for await(const o of e){if(o==="id"||o.startsWith("id:")){const c=o==="id"?"":o.slice(3);i=c.startsWith(" ")?c.slice(1):c;continue}if(o.startsWith(":")||o.startsWith("event:")||o.startsWith("retry:"))continue;const a=zu(o);if(a==="[DONE]"){yield{chunk:{type:Qs.RUN_FINISHED,threadId:s??t?.threadId??"",runId:n??t?.runId??"",model:r??"",timestamp:Date.now(),finishReason:"stop"}};return}const u=JSON.parse(a);"threadId"in u&&typeof u.threadId=="string"&&(s=u.threadId),"runId"in u&&typeof u.runId=="string"&&(n=u.runId),"model"in u&&typeof u.model=="string"&&(r=u.model);const l=i;i=void 0,yield{chunk:u,...l!==void 0?{id:l}:{}}}}function In(e){if(!e.ok)throw new Error(`HTTP error! status: ${e.status} ${e.statusText}`)}async function Vc(e,t,s,n,r){const i=await e(yn(t,{threadId:r}),{method:"GET",headers:{Accept:"application/json",...s},credentials:n});In(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)?o.messages:[],activeRun:a,interrupts:u}}async function qc(e,t,s,n,r){const i=await e(yn(t,{threadId:r}),{method:"GET",headers:{Accept:"application/json",...s},credentials:n});In(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*Ws(e,t,s){In(e),yield*zc(Hc(Gu(e),t),s)}async function*Qc(e,t){for await(const{chunk:s}of Ws(e,t))yield s}function _r(e,t,s,n){return async function*(r,i){let o;try{o=await e(t,{...s,headers:{...s.headers,...r},...i?{signal:i}:{}})}catch(a){throw new Sn(a)}yield*n(o,i)}}async function*Tr(e,t,s){const n=new Set;let r;const i=jc(s);let o=0;async function a(u){if(u)o=0;else if(o+=1,o>i.maxAttempts)throw new $c(i.maxAttempts);await Uc(i.delayMs,t)}for(;;){if(t?.aborted)return;const u=r!==void 0?{"Last-Event-ID":r}:{};let l=!1,c=!1;try{for await(const{chunk:d,id:h}of e(u,t)){if(h!==void 0)if(h==="")r=void 0,n.clear();else{if(n.has(h))continue;n.add(h),r=h}c=!0,(d.type==="RUN_FINISHED"||d.type==="RUN_ERROR")&&(l=!0),yield d}}catch(d){if(t?.aborted)return;if((d instanceof no||d instanceof Sn)&&r!==void 0){await a(c);continue}throw d}if(t?.aborted||l)return;if(r!==void 0){if(c){await a(!0);continue}throw new Dc}return}}function Mr(e){if(!e)throw new Error("Connection adapter is required");const t="connect"in e,s="subscribe"in e,n="send"in e;if(t&&(s||n))throw new Error("Connection adapter must provide either connect or both subscribe and send, not both modes");if(s&&n){const a=e.joinRun?.bind(e),u=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...a?{joinRun:a}:{},...u?{hydrate:u}:{}}}if(!t)throw new Error("Connection adapter must provide either connect or both subscribe and send");let r=[],i=[];function o(a,u){u&&so.set(a,u);const l=i.shift();l?l(a):r.push(a)}return{subscribe(a){const u=r.splice(0),l=[];return r=u,i=l,(async function*(){for(;!a?.aborted;){let c;const d=u.shift();d!==void 0?c=d:c=await new Promise(h=>{const f=()=>h(null);l.push(p=>{a?.removeEventListener("abort",f),h(p)}),a?.addEventListener("abort",f,{once:!0})}),c!==null&&(yield c)}})()},async send(a,u,l,c){let d=!1,h,f;try{const p=e.connect(a,u,l,c);for await(const g of p)"threadId"in g&&typeof g.threadId=="string"&&(h=g.threadId),"runId"in g&&typeof g.runId=="string"&&(f=g.runId),(g.type==="RUN_FINISHED"||g.type==="RUN_ERROR")&&(d=!0),o(g,c?.runId);!l?.aborted&&!d&&o({type:Qs.RUN_FINISHED,threadId:Mt(h??c?.threadId,"threadId"),runId:Mt(f??c?.runId,"runId"),model:"connect-wrapper",timestamp:Date.now(),finishReason:"stop"},c?.runId)}catch(p){if(!l?.aborted&&!d)try{const g=p instanceof Error?p.message:"Unknown error in connect()";o({type:Qs.RUN_ERROR,threadId:Mt(h??c?.threadId,"threadId"),runId:Mt(f??c?.runId,"runId"),timestamp:Date.now(),message:g},c?.runId)}catch{}throw p}},...typeof e.joinRun=="function"?{joinRun:(a,u)=>e.joinRun(a,u)}:{},...(()=>{const a=e.hydrate;return typeof a=="function"?{hydrate:u=>a(u)}:{}})()}}function Wc(e,t,s,n){const r=Ac(e),i={...n.body,...s?.forwardedProps??{},...t};return{threadId:s?.threadId??Er("thread"),runId:s?.runId??Er("run"),...s?.parentRunId!==void 0&&{parentRunId:s.parentRunId},...s?.resume!==void 0&&{resume:s.resume},state:{},messages:r,tools:s?.clientTools??[],context:[],forwardedProps:i,data:{...i}}}function ph(e,t={}){return{async*connect(s,n,r,i){const o=typeof e=="function"?e():e,a=typeof t=="function"?await t():t,u={"Content-Type":"application/json",...xt(a.headers),...Gc(i?.runId)},l=Wc(s,n,i,a),c=a.fetchClient??fetch,d=r||a.signal;yield*Tr(_r(c,o,{method:"POST",headers:u,body:JSON.stringify(l),credentials:a.credentials||"same-origin"},(h,f)=>Ws(h,f,{...i?.threadId!==void 0?{threadId:i.threadId}:{},...i?.runId!==void 0?{runId:i.runId}:{}})),d,a.reconnect)},async*joinRun(s,n){const r=typeof e=="function"?e():e,i=typeof t=="function"?await t():t,o=yn(r,{offset:"-1",runId:s}),a={...xt(i.headers)},u=i.fetchClient??fetch,l=n||i.signal;yield*Tr(_r(u,o,{method:"GET",headers:a,credentials:i.credentials||"same-origin"},(c,d)=>Ws(c,d,{runId:s})),l,i.reconnect)},async hydrate(s){const n=typeof e=="function"?e():e,r=typeof t=="function"?await t():t;return Vc(r.fetchClient??fetch,n,xt(r.headers),r.credentials||"same-origin",s)},async hydrateGeneration(s){const n=typeof e=="function"?e():e,r=typeof t=="function"?await t():t;return qc(r.fetchClient??fetch,n,xt(r.headers),r.credentials||"same-origin",s)}}}function Kc(e){return{async*connect(t,s,n,r){if(!n)throw new Error("fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.");if(!r)throw new Error("fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.");const i=await e({messages:t,data:s,threadId:r.threadId,runId:r.runId},{signal:n});i instanceof Response?yield*Qc(i,n):yield*Jc(i,n)}}}async function*Jc(e,t){if(t.aborted)return;const s=e[Symbol.asyncIterator](),n=new Promise(r=>{t.addEventListener("abort",()=>r({done:!0,value:void 0}),{once:!0})});try{for(;;){const r=await Promise.race([s.next(),n]);if(r.done)return;yield r.value}}finally{await s.return?.()}}var Xc=new Set(["invalid-payload","invalid-edited-args","invalid-tool-output","invalid-response-schema","unknown-interrupt","expired","stale","conflict","legacy-unsupported"]),Yc=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 Re(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ro(e){return Re(e)&&e.kind==="approval"&&typeof e.toolName=="string"&&"input"in e}function io(e){return Re(e)&&e.kind==="client_tool"&&typeof e.toolName=="string"&&"input"in e}function Zc(e){return ro(e.metadata)||io(e.metadata)}function ed(e){return(e.v===void 0||e.v===1)&&typeof e.kind=="string"&&typeof e.interruptId=="string"&&typeof e.interruptedRunId=="string"&&typeof e.generation=="number"&&Number.isInteger(e.generation)&&e.generation>=0&&typeof e.responseSchemaHash=="string"&&(e.expiresAt===void 0||typeof e.expiresAt=="string"&&Number.isFinite(Date.parse(e.expiresAt)))}function td(e){if(!Re(e)||!ed(e))return;const t=typeof e.expiresAt=="string"?e.expiresAt:void 0;if(e.kind==="generic")return{v:1,kind:"generic",interruptId:String(e.interruptId),interruptedRunId:String(e.interruptedRunId),generation:Number(e.generation),responseSchemaHash:String(e.responseSchemaHash),...t!==void 0?{expiresAt:t}:{}};if(e.kind==="client-tool-execution"&&typeof e.toolName=="string"&&typeof e.toolCallId=="string"&&typeof e.outputSchemaHash=="string")return{v:1,kind:"client-tool-execution",interruptId:String(e.interruptId),interruptedRunId:String(e.interruptedRunId),generation:Number(e.generation),toolName:e.toolName,toolCallId:e.toolCallId,outputSchemaHash:e.outputSchemaHash,responseSchemaHash:String(e.responseSchemaHash),...t!==void 0?{expiresAt:t}:{}};if(e.kind==="tool-approval"&&typeof e.toolName=="string"&&typeof e.toolCallId=="string"&&typeof e.inputSchemaHash=="string"&&typeof e.approvalSchemaHash=="string"&&"originalArgs"in e)return{v:1,kind:"tool-approval",interruptId:String(e.interruptId),interruptedRunId:String(e.interruptedRunId),generation:Number(e.generation),toolName:e.toolName,toolCallId:e.toolCallId,originalArgs:e.originalArgs,inputSchemaHash:e.inputSchemaHash,approvalSchemaHash:e.approvalSchemaHash,responseSchemaHash:String(e.responseSchemaHash),...t!==void 0?{expiresAt:t}:{}}}function sd(e){const t=e.metadata?.[rc];return td(t)}function nd(e){return e==="tanstack:client_tool_execution"||e==="client_tool_input"}function oo(e){if(e.responseSchema!==void 0)try{return Ke(We(e.responseSchema))}catch{return}}function He(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"then"in e&&typeof e.then=="function"}function Pt(e,t,s){if(e===void 0)return{valid:!0,payload:t};if(be(e)){const n=e["~standard"].validate(t),r=i=>i.issues?{code:s,message:i.issues[0]?.message??"Schema validation failed."}:{valid:!0,payload:i.value};return He(n)?Promise.resolve(n).then(r):r(n)}return{valid:!0,payload:t}}function rd(e){for(const t of Xc)if(t===e)return!0;return!1}function id(e){for(const t of Yc)if(t===e)return!0;return!1}function xr(e){if(!Re(e))return!1;const t=e.scope,s=e.code;return typeof s=="string"&&typeof e.message=="string"&&typeof e.retryable=="boolean"&&typeof e.threadId=="string"&&typeof e.interruptedRunId=="string"&&typeof e.generation=="number"?t==="item"?rd(s)&&typeof e.interruptId=="string"&&(e.source==="client"||e.source==="server"):t==="batch"&&id(s)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(n=>typeof n=="string")&&(e.source==="client"||e.source==="server"||e.source==="transport"):!1}function od(e){return xr(e)?[e]:!Re(e)||!Array.isArray(e.errors)?[]:e.errors.every(xr)?e.errors:[]}function ao(e,t){if(e.length!==t.length)return!1;const s=[...e].sort(),n=[...t].sort();return s.every((r,i)=>r===n[i])}function Pr(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&ao(e.interruptIds,t.interruptIds)}function ad(e,t,s){const n=s.filter(a=>a.source!=="transport"),r=a=>t.includes(a)&&n.some(u=>Pr(a,u)),i=e.filter(a=>!r(a)),o=t.filter(a=>!n.some(u=>Pr(a,u)));return Object.freeze({rootErrors:Object.freeze([...i,...s]),submissionRootErrors:Object.freeze([...o,...n])})}function ld(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;const s=t.resolutions.map(n=>n.interruptId);return e.scope==="item"?s.includes(e.interruptId):ao(e.interruptIds,s)}function ud(e,t,s){return z({v:1,kind:"generic",interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,responseSchemaHash:oo(e)??s?.responseSchemaHash??"invalid",...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}})}function cd(e,t,s,n){const r=z(e.descriptor),i=e.error===void 0?Object.freeze([]):Object.freeze([z(e.error)]),o=i[0];return{id:r.id,interruptId:r.id,reason:r.reason,...r.message!==void 0?{message:r.message}:{},...r.responseSchema!==void 0?{responseSchema:r.responseSchema}:{},...r.expiresAt!==void 0?{expiresAt:r.expiresAt}:{},...r.metadata!==void 0?{metadata:r.metadata}:{},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:i,...o!==void 0?{error:o}:{},canResolve:e.canResolve,cancel:s,clearResolution:n}}var dd=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;retrySubmission;resuming=!1;tools;constructor(e){this.options=e,this.tools=e.tools}updateTools(e){this.tools=e}hydrate(e){this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:z(e.interrupts)},this.items=e.interrupts.map(t=>this.hydrateInterrupt(t,e)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish()}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}reset(e){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?.()}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)e.validationGeneration++,e.resolution=Object.freeze({interruptId:e.descriptor.id,status:"cancelled"}),e.status="staged",e.error=void 0;this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw new Error("Interrupt submission is already active.");const e=this.retrySubmission;if(!e){this.addRootError("transport","There is no retryable interrupt submission.",!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){const s=this.items.find(n=>n.kind==="client-tool-execution"&&n.binding?.kind==="client-tool-execution"&&n.binding.toolCallId===e||n.kind==="generic"&&nd(n.descriptor.reason)&&n.descriptor.toolCallId===e&&io(n.descriptor.metadata));return s?(this.resolveItem(s.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){const s=this.items.find(n=>n.descriptor.id===e&&(n.kind==="tool-approval"||n.kind==="generic"&&n.descriptor.reason==="approval_required"&&ro(n.descriptor.metadata)));return s?(this.resolveItem(s.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t){const s=z(e),n=sd(s);if(n===void 0&&!Zc(s))return{descriptor:s,binding:void 0,kind:"unbound",status:"pending",canResolve:!1,validationGeneration:0};const r=n!==void 0&&n.interruptId===s.id&&n.interruptedRunId===t.interruptedRunId&&n.generation===t.generation&&n.responseSchemaHash===(oo(s)??n.responseSchemaHash);if(r&&n.kind==="tool-approval"){const i=this.tools?.find(o=>o.name===n.toolName);if(i?.needsApproval===!0&&s.toolCallId===n.toolCallId)try{const o=nc(i.approvalSchema,i.inputSchema);if(yr(i.inputSchema)===n.inputSchemaHash&&o.approvalSchemaHash===n.approvalSchemaHash&&o.responseSchemaHash===n.responseSchemaHash)return{descriptor:s,binding:z(n),kind:"tool-approval",status:"pending",canResolve:!0,tool:i,validationGeneration:0}}catch{}}if(r&&n.kind==="client-tool-execution"){const i=this.tools?.find(o=>o.name===n.toolName);if(i!==void 0&&s.toolCallId===n.toolCallId&&yr(i.outputSchema)===n.outputSchemaHash)return{descriptor:s,binding:z(n),kind:"client-tool-execution",status:"pending",canResolve:!0,tool:i,validationGeneration:0}}return{descriptor:s,binding:ud(s,t,n),kind:"generic",status:"pending",canResolve:!0,validationGeneration:0}}buildSnapshot(e){const t=this.requireHydration(),s=this.items.filter(n=>n.kind!=="client-tool-execution"&&n.status!=="submitting").map(n=>{const r=cd(n,t,()=>this.cancelItem(n.descriptor.id,e),()=>this.clearItem(n.descriptor.id,e));if(n.kind==="unbound"||n.binding===void 0){const a={...r,kind:"unbound",canResolve:!1};return Object.freeze(a)}if(n.kind==="tool-approval"&&n.binding.kind==="tool-approval"){const a=z(n.binding),u={...r,kind:"tool-approval",binding:a,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:z(n.binding.originalArgs),resolveInterrupt:(l,c)=>{const d=Re(c)?c:void 0;this.resolveItem(n.descriptor.id,{approved:l,...l&&d?.editedArgs!==void 0?{editedArgs:d.editedArgs}:{},...d?.payload!==void 0?{payload:d.payload}:{}},e)}};return Object.freeze(u)}const i=n.binding.kind==="generic"?z(n.binding):z({v:1,kind:"generic",interruptId:n.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,responseSchemaHash:typeof n.binding.responseSchemaHash=="string"?n.binding.responseSchemaHash:"none"}),o={...r,kind:"generic",binding:i,resolveInterrupt:a=>this.resolveItem(n.descriptor.id,a,e)};return Object.freeze(o)});return Object.freeze(s)}publish(){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?.();return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.()}resolveItem(e,t,s){this.assertItemMutable(s);const n=this.findItem(e);if(this.invalidateRetry(),!n.canResolve){n.status="error",n.error=this.itemError(e,"invalid-response-schema","The interrupt response schema is invalid and cannot be resolved."),s||this.publish();return}const r=++n.validationGeneration,i=this.validateCandidate(n,t);if(He(i)){n.status="validating",n.error=void 0,s||this.publish(),Promise.resolve(i).then(o=>{r===n.validationGeneration&&this.applyValidation(n,o,s)}).catch(o=>{r===n.validationGeneration&&this.applyValidation(n,{code:this.validationCode(n),message:o instanceof Error?o.message:String(o)},s)});return}this.applyValidation(n,i,s)}cancelItem(e,t){this.assertItemMutable(t);const s=this.findItem(e);this.invalidateRetry(),s.validationGeneration++,s.resolution=Object.freeze({interruptId:e,status:"cancelled"}),s.status="staged",s.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);const s=this.findItem(e);this.invalidateRetry(),s.validationGeneration++,s.resolution=void 0,s.error=void 0,s.status="pending",t||this.publish()}maybeSubmit(){const e=this.items.filter(r=>r.kind!=="unbound");if(e.length===0||e.some(r=>r.resolution===void 0||r.status!=="staged"))return;const t=this.requireHydration(),s=Wu(e.map(r=>r.resolution).filter(r=>r!==void 0)),n=Object.freeze({threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,resolutions:s.resolutions,canonicalResolutions:s.canonicalResolutions,fingerprint:s.fingerprint});this.submitBatch(n)}applyValidation(e,t,s){if(!("valid"in t)){e.status="error";const n=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=n,e.kind==="client-tool-execution"&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(r=>!(r.code==="item-validation-failed"&&r.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:"batch",code:"item-validation-failed",message:n.message,source:"client",retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation})])),s||this.publish();return}e.resolution=z({interruptId:e.descriptor.id,status:"resolved",payload:t.payload}),e.status="staged",e.error=void 0,s||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){return e.kind==="generic"?Pt(e.descriptor.responseSchema,t,"invalid-payload"):e.kind==="client-tool-execution"?Pt(e.tool?.outputSchema,t,"invalid-tool-output"):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!Re(t)||typeof t.approved!="boolean")return{code:"invalid-payload",message:"Tool approval resolutions require an approved boolean."};const s=t.approved,n=t.editedArgs;if(!s&&n!==void 0)return{code:"invalid-edited-args",message:"Rejected tool approvals cannot edit tool arguments."};if(s&&n!==void 0){const r=Pt(e.tool?.inputSchema,n,"invalid-edited-args");return He(r)?Promise.resolve(r).then(i=>"valid"in i?this.validateApprovalPayload(e,t,i.payload):i):"valid"in r?this.validateApprovalPayload(e,t,r.payload):r}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,s){const n=t.approved===!0,r=this.approvalBranchSchema(e.tool,n),i=t.payload;if(r===void 0&&i!==void 0)return{code:"invalid-payload",message:"This approval branch does not accept a payload."};if(r!==void 0&&i===void 0)return{code:"invalid-payload",message:"This approval branch requires a payload."};const o=Pt(r,i,"invalid-payload"),a=u=>"valid"in u?{valid:!0,payload:{approved:n,...s!==void 0?{editedArgs:s}:{},...r!==void 0?{payload:u.payload}:{}}}:u;return He(o)?Promise.resolve(o).then(a):a(o)}approvalBranchSchema(e,t){const s=e?.approvalSchema;return!Re(s)||!("approve"in s||"reject"in s)?s:t?s.approve:s.reject}validationCode(e){return e.kind==="client-tool-execution"?"invalid-tool-output":"invalid-payload"}resolveBooleanBulk(e){const t=this.items.filter(s=>s.kind!=="client-tool-execution");if(!t.every(s=>s.kind==="tool-approval"&&this.approvalBranchSchema(s.tool,e)===void 0)||t.length===0){this.addRootError("unsupported-bulk-operation","Boolean bulk resolution requires payloadless tool approvals.",!1);return}this.invalidateRetry();for(const s of t)s.validationGeneration++,s.resolution=z({interruptId:s.descriptor.id,status:"resolved",payload:{approved:e}}),s.status="staged",s.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){const t=this.items.map(i=>({status:i.status,...i.resolution!==void 0?{resolution:i.resolution}:{},...i.error!==void 0?{error:i.error}:{},validationGeneration:i.validationGeneration})),s={active:!0};this.activeTransaction=s;const n=this.buildSnapshot(s);let r;try{for(const i of n){const o=e(i);if(o!==void 0){r={code:He(o)?"async-resolver":"inactive-transaction",message:He(o)?"Interrupt transaction resolvers must be synchronous.":"Interrupt transaction resolvers must return literal undefined."};break}}r===void 0&&this.items.some(i=>i.kind!=="client-tool-execution"&&(i.resolution===void 0||i.status!=="staged"))&&(r={code:"incomplete-batch",message:"Interrupt transaction did not resolve every item."})}catch(i){r={code:"item-validation-failed",message:i instanceof Error?i.message:String(i)}}finally{s.active=!1,this.activeTransaction=void 0}if(r){this.restoreCheckpoints(t),this.addRootError(r.code,r.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,s)=>{const n=e[s];n&&(t.status=n.status,t.resolution=n.resolution,t.error=n.error,t.validationGeneration=n.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active)throw new Error("Interrupt transaction is inactive.");if(this.activeTransaction&&e!==this.activeTransaction)throw new Error("Interrupt transaction is inactive.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}assertRootMutable(){if(this.activeTransaction)throw new Error("Interrupt transaction is already active.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){this.resuming=!0,this.retrySubmission=void 0;for(const t of this.items)t.status="submitting";this.publish(),this.performSubmission(e)}async performSubmission(e){try{await this.options.submit(e)}catch(t){this.handleSubmissionFailure(t,e)}finally{this.resuming=!1,this.publish()}}handleSubmissionFailure(e,t){const s=od(e);if(s.length===0){const u=e instanceof Error?e.message:String(e);this.addRootError("transport",u,!0,"transport"),this.retrySubmission=t;for(const l of this.items)l.status="error";return}const n=s.filter(u=>ld(u,t));n.length!==s.length&&this.addRootError("protocol","Interrupt submission errors did not match the active batch.",!1);let r=!1,i=!1;const o=[];for(const u of n)if((u.code==="stale"||u.code==="expired"||u.code==="conflict")&&(r=!0),i||=u.retryable,u.scope==="item"){const l=this.items.find(c=>c.descriptor.id===u.interruptId);l&&(l.status="error",l.error=z(u))}else o.push(z(u));const a=ad(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=a.rootErrors,this.submissionRootErrors=a.submissionRootErrors;for(const u of this.items)u.status==="submitting"&&(u.status="error");this.retrySubmission=i&&!r?t:void 0}addRootError(e,t,s,n="client"){const r=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:"batch",code:e,message:t,source:n,retryable:s,interruptIds:Object.freeze(this.items.map(i=>i.descriptor.id)),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})]),this.publish()}findItem(e){const t=this.items.find(s=>s.descriptor.id===e);if(!t)throw new Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw new Error("InterruptManager is not hydrated.");return this.hydration}itemError(e,t,s,n){const r=this.requireHydration();return Object.freeze({scope:"item",interruptId:e,code:t,message:s,...n!==void 0?{path:Object.freeze([...n])}:{},source:"client",retryable:!1,threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})}};function hd(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():Math.random().toString(36).slice(2)}var At;function Ar(){return At!==void 0||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__=hd()),At=globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__),At}var fd=0;function oe(e){return e==null||e===""?"missing":`value-${encodeURIComponent(String(e))}`}function Ks(e){const t=e.runtimeId??Ar(),s=e.eventId&&e.eventId.length>0?e.eventId:[e.source,e.eventType,oe(t),oe(e.clientId),oe(e.requestId),oe(e.streamId),oe(e.hookId),oe(e.threadId),oe(e.runId),oe(e.messageId),oe(e.toolCallId),oe(e.sequence),e.timestamp,Ar(),fd++].join(":");return{...e,runtimeId:t,eventId:s}}var gd=class{#t=!0;#e;#s;#n;#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.#s().removeEventListener("tanstack-connect-success",this.#h)};#g=()=>{if(this.#f<this.#l){this.#f++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#s().removeEventListener("tanstack-connect",this.#g),this.#d=!0,this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};#p=()=>{this.#c||(this.#c=!0,this.#s().addEventListener("tanstack-connect-success",this.#h),this.#g())};constructor({pluginId:e,debug:t=!1,enabled:s=!0,reconnectEveryMs:n=300}){this.#e=e,this.#t=s,this.#s=this.getGlobalTarget,this.#n=t,this.debugLog(" Initializing event subscription for plugin",this.#e),this.#i=[],this.#r=!1,this.#d=!1,this.#o=null,this.#a=n}startConnectLoop(){this.#o!==null||this.#r||(this.debugLog(`Starting connect loop (every ${this.#a}ms)`),this.#o=setInterval(this.#g,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.#n&&console.log(`🌴 [tanstack-devtools:${this.#e}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<"u"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<"u"&&typeof window.addEventListener<"u")return this.debugLog("Using window as event target"),window;const e=typeof EventTarget<"u"?new EventTarget:void 0;return typeof e>"u"||typeof e.addEventListener>"u"?(this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog("Using new EventTarget as fallback"),e)}getPluginId(){return this.#e}dispatchCustomEventShim(e,t){try{const s=new Event(e,{detail:t});this.#s().dispatchEvent(s)}catch{this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(e,t){try{this.#s().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog("Emitting event to client bus",e),this.dispatchCustomEvent("tanstack-dispatch-event",e)}createEventPayload(e,t){return{type:`${this.#e}:${e}`,payload:t,pluginId:this.#e}}emit(e,t){if(!this.#t){this.debugLog("Event bus client is disabled, not emitting event",e,t);return}if(this.#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.#p(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,s){const n=s?.withEventTarget??!1,r=`${this.#e}:${e}`;if(n&&(this.#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.#s().addEventListener(r,i),this.debugLog("Registered event to bus",r),()=>{n&&this.#u?.removeEventListener(r,i),this.#s().removeEventListener(r,i)}}onAll(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=s=>{const n=s.detail;e(n)};return this.#s().addEventListener("tanstack-devtools-global",t),()=>this.#s().removeEventListener("tanstack-devtools-global",t)}onAllPluginEvents(e){if(!this.#t)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};const t=s=>{const n=s.detail;this.#e&&n.pluginId!==this.#e||e(n)};return this.#s().addEventListener("tanstack-devtools-global",t),()=>this.#s().removeEventListener("tanstack-devtools-global",t)}},pd=class extends gd{constructor(){super({pluginId:"tanstack-ai-devtools"})}},Or=Symbol.for("tanstack.ai.devtools.eventClient");function md(){const e=globalThis,t=e[Or];if(t)return t;const s=new pd;return e[Or]=s,s}var ft=md();function ce(e,t){ft.emit(e,t)}var lo=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent("client:created",{initialMessageCount:e})}loadingChanged(e){this.emitEvent("client:loading:changed",{isLoading:e})}errorChanged(e){this.emitEvent("client:error:changed",{error:e})}textUpdated(e,t,s,n){this.emitEvent("text:chunk:content",{streamId:e,messageId:t,content:s,...n})}toolCallStateChanged(e,t,s,n,r,i,o){this.emitEvent("tools:call:updated",{streamId:e,messageId:t,toolCallId:s,toolName:n,state:r,arguments:i,...o})}thinkingUpdated(e,t,s,n,r){this.emitEvent("text:chunk:thinking",{streamId:e,messageId:t,content:s,delta:n,...r})}structuredOutputChanged(e,t,s,n,r){this.emitEvent(e,{streamId:t,messageId:s,...n,...r})}approvalRequested(e,t,s,n,r,i,o){this.emitEvent("tools:approval:requested",{streamId:e,messageId:t,toolCallId:s,toolName:n,input:r,approvalId:i,...o})}messageAppended(e,t,s){const n=e.parts.filter(r=>r.type==="text").map(r=>r.content).join(" ");this.emitEvent("text:message:created",{streamId:t,messageId:e.id,role:e.role,content:n,parts:e.parts,...s})}messageSent(e,t){const s=typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.content).join("");this.emitEvent("text:message:created",{messageId:e,role:"user",content:s,...Array.isArray(t)&&{parts:t}}),this.emitEvent("text:message:user",{messageId:e,role:"user",content:s,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent("client:reloaded",{fromMessageIndex:e})}stopped(){this.emitEvent("client:stopped")}messagesCleared(){this.emitEvent("client:messages:cleared")}toolResultAdded(e,t,s,n,r){this.emitEvent("tools:result:added",{toolCallId:e,toolName:t,output:s,state:n,...r})}toolApprovalResponded(e,t,s,n){this.emitEvent("tools:approval:responded",{approvalId:e,toolCallId:t,approved:s,...n})}toolFixtureApplied(e){this.emitEvent("devtools:tool-fixture:applied",{...e})}},vd=class extends lo{emitEvent(e,t){const s=Date.now(),n=e.startsWith("text:")||e.startsWith("tools:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",r=e.startsWith("client:")||e.startsWith("tools:")||e.startsWith("text:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",i=n?"user-visible":"client-state",o={hookId:this.clientId,...typeof t?.threadId=="string"?{threadId:t.threadId}:{},...typeof t?.runId=="string"?{runId:t.runId}:{},...typeof t?.streamId=="string"?{streamId:t.streamId}:{},...typeof t?.messageId=="string"?{messageId:t.messageId}:{},...typeof t?.toolCallId=="string"?{toolCallId:t.toolCallId}:{}};if(r){const a=Ks({eventType:e,clientId:this.clientId,...o,source:"client",visibility:i,timestamp:s});ft.emit(e,{...t,...a})}else{const a=Ks({eventType:e,source:"client",visibility:"client-state",timestamp:s});ft.emit(e,{...t,...a})}}},Sd=class extends lo{emitEvent(){}},yd=class{events;constructor(e){this.events=new Sd(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,s,n){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return""}observeChunk(e){}recordMemoryState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Id=e=>new yd(e);function Fr(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function Lr(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function Nr(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function Rd(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var Cd=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,s,n){this.adapter=e,this.id=t,this.applyMessages=s,this.applyResume=n}writeState(){const e=[...this.lastMessages];if(e.length===0&&!this.lastResume){const n=this.generation;this.runOperation(()=>{if(n===this.generation)return this.adapter.removeItem(this.id)});return}const t=this.generation,s={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,s)})}readInitial(){try{const e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(Fr).catch(()=>{});const t=Fr(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;const t=this.messagesGeneration;e.then(s=>{!s||this.messagesGeneration!==t||(this.lastResume=s.resume??null,this.lastMessages=s.messages,this.applyMessages(s.messages),s.resume&&this.applyResume&&this.applyResume(s.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;const e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){const t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{const t=e();if(t instanceof Promise){this.queuePending=!0;const s=t.catch(()=>{});this.queue=s,s.finally(()=>{this.queue===s&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){const t=Z(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const s=Lr(e);if(s&&this.clearedToolCallIds.has(s))return!0;const n=Rd(e);if(n&&this.clearedMessageIds.has(n))return s&&this.clearedToolCallIds.add(s),!0;const r=Nr(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=Nr(e);t&&this.clearedMessageIds.add(t);const s=Lr(e);s&&this.clearedToolCallIds.add(s)}isRunlessChunkFromIgnoredRun(e){return Z(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 kr(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function Dr(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function wd(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var bd=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=Z(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const s=kr(e);if(s&&this.clearedToolCallIds.has(s))return!0;const n=wd(e);if(n&&this.clearedMessageIds.has(n))return s&&this.clearedToolCallIds.add(s),!0;const r=Dr(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=Dr(e);t&&this.clearedMessageIds.add(t);const s=kr(e);s&&this.clearedToolCallIds.add(s)}isRunlessChunkFromIgnoredRun(e){return Z(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 $r(e){const{connection:t,fetcher:s}=e;if(t&&s)throw new Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(s)return Kc(s);throw new Error("ChatClient: either `connection` or `fetcher` is required.")}function jr(e){const t={whenBusy:"queue",drain:"fifo",onOverflow:"reject"};if(!e)return t;if(typeof e=="string")return{...t,whenBusy:e};if(typeof e=="function")return{...t,strategy:e};const s=e.maxSize;if(s!==void 0&&(!Number.isInteger(s)||s<0))throw new Error("ChatClient: queue.maxSize must be a non-negative integer");return{whenBusy:e.whenBusy??"queue",drain:e.drain??"fifo",onOverflow:e.onOverflow??"reject",...s!==void 0?{maxSize:s}:{}}}function Ed(e){const t=e.at(-1)?.body,s=[];for(const r of e){if(typeof r.content!="string")break;s.push(r.content)}if(s.length===e.length)return{content:s.join(`
|
|
10
|
-
`),...t!==void 0?{body:t}:{}};const n=[];for(const r of e)typeof r.content=="string"?n.push({type:"text",content:r.content}):typeof r.content.content=="string"?n.push({type:"text",content:r.content.content}):n.push(...r.content.content);return{content:{content:n},...t!==void 0?{body:t}:{}}}function _d(e){if(!(e===null||typeof e!="object"||Array.isArray(e))&&!(!("approved"in e)||typeof e.approved!="boolean"))return e.approved}function Td(e){const t=e;if(t===null||typeof t!="object"||!("resumeState"in t))return;const s=t.resumeState;if(!(s===null||typeof s!="object"||!("threadId"in s)||typeof s.threadId!="string"||s.threadId.length===0||!("runId"in s)||typeof s.runId!="string"||s.runId.length===0))return{threadId:s.threadId,runId:s.runId}}var Md=2e3,xd=new Set(["TEXT_MESSAGE_START","TEXT_MESSAGE_CONTENT","TOOL_CALL_START","MESSAGES_SNAPSHOT"]),Pd=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new bd;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};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;errorReportedGeneration=null;streamGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){this.threadId=e.threadId||this.generateUniqueId("thread"),this.uniqueId=e.id||this.threadId;let t=!0;if(e.persistence===!0)t=!1;else if(e.persistence){const o=e.id??this.threadId;this.persistor=new Cd(e.persistence,o,a=>this.processor.setMessages(a),a=>this.applyPersistedResume(a))}if(this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.context=e.context,this.queueConfig=jr(e.queue),this.connection=Mr($r(e)),this.clientToolsRef={current:new Map},e.tools)for(const o of e.tools)this.clientToolsRef.current.set(o.name,o);this.devtoolsBridge=(e.devtoolsBridgeFactory??Id)(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 dd({...e.tools!==void 0?{tools:e.tools}:{},submit:o=>this.submitInterruptBatch(o),onChange:()=>this.notifyResumeStateChange()}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);const s=this.persistor?.readInitial(),n=s instanceof Promise?void 0:s,r=n?n.messages:e.initialMessages;let i=null;if(n?.resume){const o=n.resume;Array.isArray(o.pendingInterrupts)&&o.pendingInterrupts.length>0?this.applyResumeSnapshot(o):o.resumeState.runId&&(i=o.resumeState.runId)}if(!i&&e.initialResumeSnapshot){const o=e.initialResumeSnapshot;!(Array.isArray(o.pendingInterrupts)&&o.pendingInterrupts.length>0)&&o.resumeState.runId&&(i=o.resumeState.runId)}this.processor=new xc({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...r?{initialMessages:r}:{},events:{onMessagesChange:o=>{this.persistor?.notifyMessagesChanged(o),this.callbacksRef.current.onMessagesChange(o)},onStreamStart:()=>{this.setStatus("streaming");const o=this.processor.getCurrentAssistantMessageId();if(!o)return;const a=this.processor.getMessages().find(u=>u.id===o);a&&(this.currentMessageId=a.id,this.events.messageAppended(a,this.currentStreamId||void 0))},onStreamEnd:o=>{this.callbacksRef.current.onFinish(o),this.setStatus("ready"),this.resolveProcessing()},onError:o=>{this.reportStreamError(o)},onTextUpdate:(o,a)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,o,a)},onThinkingUpdate:(o,a)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,o,a,void 0)},onStructuredOutputChange:o=>{const a=this.devtoolsBridge.resolveStreamId(),u=o.phase==="start"?"structured-output:started":o.phase==="complete"?"structured-output:completed":o.phase==="error"?"structured-output:errored":"structured-output:updated";this.currentMessageId=o.messageId,this.events.structuredOutputChanged(u,a,o.messageId,{status:o.status,raw:o.raw,...o.partial!==void 0?{partial:o.partial}:{},...o.data!==void 0?{data:o.data}:{},...o.reasoning!==void 0?{reasoning:o.reasoning}:{},...o.errorMessage!==void 0?{errorMessage:o.errorMessage}:{},...o.delta!==void 0?{delta:o.delta}:{}})},onToolCallStateChange:(o,a,u,l)=>{const c=this.processor.getMessages().find(d=>d.id===o)?.parts.find(d=>d.type==="tool-call"&&d.id===a)?.name||"unknown";this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,o,a,c,u,l)},onToolCall:o=>{const a=(this.activeClientTools??this.clientToolsRef.current).get(o.toolName),u=a?.execute;if(u){const l=this.devtoolsBridge.getCurrentRunEventContext(),c=(async()=>{try{const d=this.activeClientTools===null?this.context:this.activeContext,h=await u(o.input,{toolCallId:o.toolCallId,context:d,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:o.toolCallId,tool:o.toolName,output:h,state:"output-available"},a,l)}catch(d){await this.addToolResultForClientTool({toolCallId:o.toolCallId,tool:o.toolName,output:null,state:"output-error",errorText:d.message},a,l)}finally{this.pendingToolExecutions.delete(o.toolCallId)}})();this.pendingToolExecutions.set(o.toolCallId,c)}},onApprovalRequest:o=>{const a=this.devtoolsBridge.resolveStreamId(),u=this.findMessageIdForToolCall(o.toolCallId)??this.currentMessageId??"";this.events.approvalRequested(a,u,o.toolCallId,o.toolName,o.input,o.approvalId)},onCustomEvent:(o,a,u)=>{o==="memory:state"&&this.devtoolsBridge.recordMemoryState(a),this.callbacksRef.current.onCustomEvent(o,a,u)}}}),this.persistor?.hydrateAsync(s),this.rejoinRunId=i,this.cachesMessages=t}attach(){this.disposed||this.tailing||(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=Td(e);if(t===void 0){this.interruptManager.reset();return}this.lastResume=t;const s=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(s.length===0){this.interruptManager.reset();return}const n=this.interruptGeneration(s);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:n,interrupts:s})}applyPersistedResume(e){this.applyResumeSnapshot(e);const t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,s=e.resumeState?.runId;!t&&s&&this.maybeRejoinInFlight(s)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){const e=this.connection.hydrate;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(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.devtoolsMounted||(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}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=Z(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),Z(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type==="RUN_STARTED"){const n=Z(e)??e.runId;this.activeResumeThreadId="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=n,this.activeRunIds.add(n),this.clearedStreamTracker.onRunStarted(n),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:n});return}if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const s=Z(e);s?(this.activeRunIds.delete(s),this.clearedStreamTracker.onRunSettled(s)):e.type==="RUN_ERROR"&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0),t?.resolveProcessing!==!1&&this.resolveProcessing()}observeInterruptState(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR"||this.activeInterruptSubmission&&e.type==="RUN_ERROR")return;const t=Z(e),s="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:s??this.threadId,runId:l},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:l,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts});return}const n=e.type==="RUN_ERROR"&&!t,r=!!(t&&this.lastResume?.runId===t),i=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),a=this.isLoading&&e.type==="RUN_FINISHED"&&!t,u=!!(this.activeInterruptSubmission&&this.isLoading&&e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt");if(n||r||i||o||a||u){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange()}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e=="boolean"){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){const s=t??this.lastResume;return s?this.isLoading?new Promise((n,r)=>{this.queuePostStreamAction(async()=>{try{n(await this.resumeInterruptsUnsafe(e,s))}catch(i){r(i)}})}):(this.pendingResumeThreadId=s.threadId,this.pendingResumeParentRunId=s.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(const n of e.resolutions){const r=_d(n.payload);if(r===void 0)continue;const i=n.interruptId;this.processor.addToolApprovalResponse(i,r)}const t=await this.resumeInterruptsUnsafe([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId}).finally(()=>{this.activeInterruptSubmission=void 0}),s=this.takeInterruptSubmissionFailure();if(s!==void 0)throw{errors:s.errors};if(!t)throw new Error("Interrupt continuation could not be started.");this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){const e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(const s of e){const n=s.metadata?.["tanstack:interruptBinding"];if(n===null||typeof n!="object"||!("generation"in n)||typeof n.generation!="number"||!Number.isInteger(n.generation)||n.generation<0||t!==void 0&&t!==n.generation)return 0;t=n.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(){const e=this.getResumeState();this.persistResumeSnapshot(e),this.callbacksRef.current.onResumeStateChange(e,this.interruptManager.getInterrupts()),this.callbacksRef.current.onInterruptStateChange(this.interruptManager.getState())}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){return{hookId:this.uniqueId,clientId:this.uniqueId,threadId:this.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:t=>{this.processor.setMessages(t)},addToolResult:(t,s,n)=>{this.processor.addToolResult(t,s,n)},generateId:t=>this.generateUniqueId(t)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){const t=this.processor.getMessages();for(const s of t)if(s.parts.find(n=>n.type==="tool-call"&&n.id===e))return s.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus("ready")}reportStreamError(e){const t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status==="submitted"||this.status==="streaming")&&this.setStatus("error"),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;const e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(t=>{t instanceof Error&&t.name!=="AbortError"&&(this.setConnectionStatus("error"),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(t)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!=="error"&&this.setConnectionStatus("disconnected")))})}async consumeSubscription(e){const t=this.connection.subscribe(e);for await(const s of t){if(e.aborted)break;await this.processIncomingChunk(s)}}resumeInFlightRun(e){const t=this.connection.joinRun;if(!t)return;const s=new AbortController;this.abortController=s,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.setIsLoading(!0),this.setStatus("streaming"),(async()=>{let n=!1,r=!1,i=!1;const o=setTimeout(()=>{r||s.abort()},Md);try{for await(const a of t(e,s.signal)){if(s.signal.aborted)break;r||(r=!0,clearTimeout(o)),!n&&xd.has(a.type)&&(n=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}}catch(a){const u=a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError");!r&&!u&&(i=!0),r&&!u&&this.reportStreamError(a instanceof Error?a:new Error(String(a)))}finally{clearTimeout(o),!r&&i&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===s&&(this.abortController=null,this.setIsLoading(!1),this.status==="streaming"&&this.setStatus("ready"))}})()}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.type==="RUN_ERROR"&&this.isActiveInterruptSubmissionFailure(e)&&(this.interruptSubmissionFailure={errors:e["tanstack:interruptErrors"]??[]}),this.connectionStatus==="connecting"&&this.setConnectionStatus("connected"),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR")&&(Z(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&&await new Promise(s=>setTimeout(s,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){const t=this.activeInterruptSubmission,s=e["tanstack:interruptErrors"];if(!t||!s||s.length===0)return!1;const n=Z(e);return n!==void 0&&n!==this.currentRunId||typeof e.threadId=="string"&&e.threadId!==t.threadId?!1:s.every(r=>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=Z(e);if(t===void 0)return;const s=this.joinedRunWaiters.get(t);s!==void 0&&(this.joinedRunWaiters.delete(t),s())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,s){if(this.mountDevtools(),!(typeof e=="string"&&!e.trim())){if(this.hasBlockingInterrupts())throw new Error("ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.");if(this.isSendBusy()){const{action:n,id:r}=this.decideWhenBusy(e,s);if(n==="drop")return;if(n==="queue"){this.enqueueMessage(e,t,r);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,t)}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 s=this.normalizeMessageInput(e);this.pendingMessageBody=t;const n=this.processor.addUserMessage(s.content,s.id);return this.events.messageSent(n.id,s.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){const s=this.generateUniqueId("queued");if(t?.whenBusy)return{action:t.whenBusy,id:s};const{strategy:n,whenBusy:r}=this.queueConfig;if(n){const{action:i}=n({pending:{id:s,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:i,id:s}}return{action:r,id:s}}enqueueMessage(e,t,s){const{maxSize:n,onOverflow:r}=this.queueConfig;if(n!==void 0&&this.messageQueue.length>=n){if(r==="reject"||n===0)return;this.messageQueue.shift()}this.messageQueue.push({id:s??this.generateUniqueId("queued"),content:e,createdAt:Date.now(),...t!==void 0?{body:t}:{}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e=="string"?{content:e.trim()}:{content:e.content,id:e.id}}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=mc(e,ve);if(t.role==="system")return;const s=t;this.events.messageAppended(s);const n=this.processor.getMessages();if(this.processor.setMessages([...n,s]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;const e=++this.streamGeneration,t=this.pendingResumeThreadId,s=this.pendingResumeParentRunId,n=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;const r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(r),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=r,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus("submitted"),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;const i=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,a=null,u=!1;try{const l=this.processor.getMessages(),c=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),i.aborted)return!1;const h={...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=d,this.processor.prepareAssistantMessage(),this.ensureSubscription();const f=this.waitForProcessing(),p={threadId:t??this.threadId,runId:r,...s!==null?{parentRunId:s}:{},clientTools:Array.from(c.values()).map(g=>({name:g.name,description:g.description,parameters:g.inputSchema?zs(g.inputSchema):{type:"object"}})),forwardedProps:{...h},...n?{resume:n}:{}};if(this.devtoolsBridge.beginRun(p.runId,p.threadId),a=p.runId,this.devtoolsBridge.emitRunLifecycle("run:created",p.runId,"created"),this.devtoolsBridge.emitRunLifecycle("run:started",p.runId,"started"),this.devtoolsBridge.emitSnapshot(),await this.connection.send(l,h,i,p),e!==this.streamGeneration||i.aborted||(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){if(l instanceof Error){if(l.name==="AbortError")return a&&(this.devtoolsBridge.emitRunLifecycle("run:cancelled",a,"cancelled"),u=!0),!1;e===this.streamGeneration&&(this.reportStreamError(l),a&&(this.devtoolsBridge.emitRunLifecycle("run:errored",a,"errored",{error:l.message}),u=!0))}}finally{if(e===this.streamGeneration)if(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){const l=this.processor.getMessages().at(-1)?.parts.at(-1),{finishReason:c}=this.processor.getState();if(l?.type==="tool-result"&&c!=="stop"&&this.shouldAutoSend())try{await this.checkForContinuation()}catch(d){console.error("Failed to continue flow after tool result:",d),await this.drainQueue()}else this.status!=="ready"&&this.setStatus("ready"),this.messageQueueDraining||await this.drainQueue()}else this.flushQueue()}return o}subscribe(e){const t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus("connecting"),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected")}async reload(){const e=this.processor.getMessages();if(e.length===0)return;const t=e.findLastIndex(s=>s.role==="user");t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){const e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),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)}async addToolResultForClientTool(e,t,s){if(t&&e.state!=="output-error")try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(n){e={...e,output:null,state:"output-error",errorText:n.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||"output-available",s),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(()=>this.checkForContinuation());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&be(e.outputSchema)?Yu(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;const t=this.processor.getMessages();let s;for(const n of t){const r=n.parts.find(i=>i.type==="tool-call"&&i.approval?.id===e.id);if(r){s=r.id;break}}if(s&&this.events.toolApprovalResponded(e.id,s,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){this.postStreamActions.push(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.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(){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=Ed(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:s})=>({id:e,content:t,createdAt:s}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){const t=this.messageQueue.findIndex(s=>s.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){const t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected"),this.connection=Mr($r({connection:e.connection,fetcher:e.fetcher})),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),"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=jr(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}},Ur=Symbol.for("tanstack.ai.devtools.activeBridgeByHookId");function Br(){const e=globalThis,t=e[Ur];if(t)return t;const s=new Map;return e[Ur]=s,s}var Ad=class{options;bridgeId;unsubscribers=[];disposed=!1;superseded=!1;registered=!1;constructor(e){this.options=e,this.bridgeId=Od(e.hookId)}emitRegistered(){this.prepareForMountEmit()&&(this.registered=!0,ce("hook:registered",{...this.createEnvelope("hook:registered"),...this.createMetadataPayload(),lifecycle:"mounted"}))}emitUpdated(){this.prepareForEmit()&&ce("hook:updated",{...this.createEnvelope("hook:updated"),...this.createMetadataPayload(),lifecycle:"active"})}emitSnapshot(){this.prepareForEmit()&&ce("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?zs(t.inputSchema):{type:"object"},outputSchema:t.outputSchema?zs(t.outputSchema):void 0,needsApproval:t.needsApproval,metadata:t.metadata})):[];ce("tools:registered",{...this.createEnvelope("tools:registered"),...this.createMetadataPayload(),tools:e})}emitRunLifecycle(e,t,s,n={}){this.prepareForEmit()&&ce(e,{...this.createEnvelope(e,"client-state",{runId:t}),runId:t,status:s,...n.error?{error:n.error}:{}})}deactivate(){const e=Br();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}const e={...this.createEnvelope("hook:unregistered"),...this.createMetadataPayload(),reason:"disposed"};ce("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=Br(),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(ft.on("devtools:request-state",s=>{this.handleRequestState(s)})),this.options.applyToolFixture&&this.unsubscribers.push(ft.on("devtools:tool-fixture:apply",s=>{this.handleToolFixtureApply(s)})))}handleRequestState(e){if(this.disposed||this.superseded)return;const t=e.payload.targetHookId;t&&t!==this.options.hookId||(this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot(),this.onReplayState())}onReplayState(){}async handleToolFixtureApply(e){const t=e.payload;this.matchesFixtureTarget(t)&&await this.options.applyToolFixture?.(t)}matchesFixtureTarget(e){return!e.hookId&&!e.threadId?!1:e.hookId?e.hookId===this.options.hookId:!(e.threadId&&(!this.options.threadId||e.threadId!==this.options.threadId))}createEnvelope(e,t="client-state",s={}){return Ks({eventType:e,source:"client",visibility:t,clientId:this.options.clientId,hookId:this.options.hookId,correlationId:this.bridgeId,...this.options.threadId?{threadId:this.options.threadId}:{},...s.runId?{runId:s.runId}:{},timestamp:Date.now()})}createMetadataPayload(){return{hookId:this.options.hookId,hookName:this.options.metadata.hookName,...this.options.metadata.name?{displayName:this.options.metadata.name}:{},...this.options.metadata.outputKind?{outputKind:this.options.metadata.outputKind}:{},...this.options.metadata.framework?{framework:this.options.metadata.framework}:{}}}},Gr=0;function Od(e){const t=globalThis.crypto;return t?.randomUUID?`bridge:${e}:${t.randomUUID()}`:(Gr+=1,`bridge:${e}:${Gr}`)}var Fd=class extends Ad{events;chatOptions;currentRunId=null;currentRunThreadId=null;currentStreamId=null;lastStreamId=null;lastRunEventContext;lastMemoryStateValue=null;constructor(e){super({...e,applyToolFixture:t=>this.applyFixture(t)}),this.chatOptions=e,this.events=new jd(e.clientId,this)}setCurrentStreamId(e){this.currentStreamId=e,e&&(this.lastStreamId=e)}recordStreamId(e){e&&(this.lastStreamId=e)}mountWithTools(e){this.events.clientCreated(e),this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot()}notifyToolsChanged(){this.emitToolsRegistered(),this.emitSnapshot()}getCurrentStreamId(){return this.currentStreamId}getLastStreamId(){return this.lastStreamId}resolveStreamId(){return this.currentStreamId??this.lastStreamId??this.chatOptions.generateId("stream")}beginRun(e,t){this.currentRunId=e,this.currentRunThreadId=t,this.lastRunEventContext={runId:e,threadId:t}}observeChunk(e){if(e.type==="RUN_STARTED"){this.beginRun(e.runId,e.threadId);return}if(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR"){const t=(e.type==="RUN_FINISHED",e.runId);if(!t||t===this.currentRunId){const s=this.getCurrentRunEventContext();s&&(this.lastRunEventContext=s),this.currentRunId=null,this.currentRunThreadId=null}}}recordMemoryState(e){this.lastMemoryStateValue=e,this.emitMemoryState(e)}emitMemoryState(e){if(!e||typeof e!="object")return;const t=e,s=t.scope,n=t.adapter;if(!s||typeof n!="string")return;const r=this.currentRunId?{runId:this.currentRunId}:{};ce("memory:retrieve:started",{...this.createEnvelope("memory:retrieve:started","client-state",r),scope:s,adapter:n,query:t.query??""}),t.recall&&ce("memory:retrieve:completed",{...this.createEnvelope("memory:retrieve:completed","client-state",r),scope:s,adapter:n,fragmentCount:t.recall.fragmentCount??0,hasTools:!!t.recall.hasTools,systemPromptChars:t.recall.systemPromptChars??0,durationMs:t.recall.durationMs??0}),t.snapshot&&ce("memory:snapshot",{...this.createEnvelope("memory:snapshot","client-state",r),scope:s,adapter:n,takenAt:t.snapshot.takenAt,data:t.snapshot.data,facts:t.snapshot.facts??[]})}onReplayState(){this.lastMemoryStateValue!=null&&this.emitMemoryState(this.lastMemoryStateValue)}getCurrentRunEventContext(){if(this.currentRunId)return{threadId:this.currentRunThreadId??this.chatOptions.threadId??"",runId:this.currentRunId}}getCurrentOrLastRunEventContext(){return this.getCurrentRunEventContext()??this.lastRunEventContext}findToolCallContext(e){const t={toolCallId:e},s=this.getCurrentRunEventContext();return s?{threadId:s.threadId,runId:s.runId,toolCallId:e}:this.chatOptions.threadId?{threadId:this.chatOptions.threadId,toolCallId:e}:t}async applyFixture(e){const t=this.chatOptions.getMessages(),s=e.threadId??this.chatOptions.threadId??"";if(e.execute){await this.executeFixture(e,t,s);return}const{message:n,toolCallId:r}=this.createReplayMessageFromFixture(e,t),i=n.id;this.events.messageAppended(n,void 0,{threadId:s,toolCallId:r,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,n]),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:s,...e.runId?{runId:e.runId}:{},toolName:e.toolName,input:e.input,output:e.output,messageId:i,toolCallId:r,...e.execute!==void 0?{execute:e.execute}:{},...e.message?{message:e.message}:{},...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}async executeFixture(e,t,s){const n=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i={id:r,role:"assistant",parts:[{type:"tool-call",id:n,name:e.toolName,arguments:Rs(e.input),input:e.input,state:"input-complete"}],createdAt:new Date};this.events.messageAppended(i,void 0,{threadId:s,toolCallId:n,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,i]),this.emitSnapshot();const o=this.findClientTool(e.toolName)?.execute;if(!o){console.warn(`[ai-devtools] tool fixture "${e.toolName}" requested execute=true but no client tool implementation is registered; replaying saved output instead.`),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:e.output,errorText:e.errorText});return}let a;try{a=await o(e.input)}catch(u){console.error(`[ai-devtools] tool fixture "${e.toolName}" execute threw`,u),this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:null,errorText:u instanceof Error?`${u.name}: ${u.message}`:`Tool execution failed: ${String(u)}`});return}this.addToolResultForFixture({fixture:e,messageId:r,toolCallId:n,threadId:s,output:a})}addToolResultForFixture(e){const t=e.errorText?"output-error":"output-available";this.events.toolResultAdded(e.toolCallId,e.fixture.toolName,e.output,t,{threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolCallId:e.toolCallId}),this.chatOptions.addToolResult(e.toolCallId,e.output,e.errorText),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolName:e.fixture.toolName,input:e.fixture.input,output:e.output,execute:!0,messageId:e.messageId,toolCallId:e.toolCallId,...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}createReplayMessageFromFixture(e,t){const s=this.cloneFixtureSourceMessage(e,t);if(s)return s;const n=this.resolveFixtureToolCallId(e.toolCallId,t),r=this.resolveFixtureMessageId(e.messageId,t),i=e.errorText?"error":"complete";return{toolCallId:n,message:{id:r,role:"assistant",parts:[{type:"tool-call",id:n,name:e.toolName,arguments:Rs(e.input),input:e.input,state:"input-complete",output:e.output},{type:"tool-result",toolCallId:n,content:Rs(e.output),state:i,...e.errorText?{error:e.errorText}:{}}],createdAt:new Date}}}cloneFixtureSourceMessage(e,t){const s=e.message;if(!s||!Array.isArray(s.parts))return;const n=this.createFixtureToolCallIdMap(s.parts,t),r=s.parts.map(a=>Nd(a,n)).filter(a=>!!a),i=e.toolCallId?n.get(e.toolCallId):void 0;if(Dd(r,{...i?{mappedToolCallId:i}:{},output:e.output}),r.length===0)return;const o=(e.toolCallId?n.get(e.toolCallId):void 0)??kd(r);if(o)return{toolCallId:o,message:{id:this.resolveFixtureMessageId(s.id,t),role:s.role,parts:r,createdAt:new Date}}}createFixtureToolCallIdMap(e,t){const s=new Map;for(const n of e)!uo(n)||n.type!=="tool-call"||typeof n.id=="string"&&s.set(n.id,this.resolveFixtureToolCallId(n.id,t));return s}resolveFixtureMessageId(e,t){return e&&!t.some(s=>s.id===e)?e:this.chatOptions.generateId("fixture-msg")}resolveFixtureToolCallId(e,t){return e&&!$d(t,e)?e:this.chatOptions.generateId("fixture-tool-call")}findClientTool(e){const t=this.chatOptions.getTools?.();if(t){for(const s of t)if(s.name===e)return s}}};function uo(e){return typeof e=="object"&&e!==null}function Rs(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 Ld(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 Nd(e,t){if(!uo(e)||typeof e.type!="string")return;const s={...e};return e.type==="tool-call"&&typeof e.id=="string"&&(s.id=t.get(e.id)??e.id),e.type==="tool-result"&&typeof e.toolCallId=="string"&&(s.toolCallId=t.get(e.toolCallId)??e.toolCallId),s}function kd(e){const t=e.find(s=>s.type==="tool-call");return t?.type==="tool-call"?t.id:void 0}function Dd(e,t){for(const s of e){if(s.type!=="tool-result")continue;const n=e.find(r=>r.type==="tool-call"&&r.id===s.toolCallId&&r.output===void 0);n&&(n.output=Array.isArray(s.content)?s.content:Ld(s.content))}if(t.mappedToolCallId&&t.output!==void 0){const s=e.find(n=>n.type==="tool-call"&&n.id===t.mappedToolCallId&&n.output===void 0);s&&(s.output=t.output)}}function $d(e,t){return e.some(s=>s.parts.some(n=>n.type==="tool-call"?n.id===t:n.type==="tool-result"?n.toolCallId===t:!1))}var jd=class extends vd{helper;constructor(e,t){super(e),this.helper=t}afterEmit(e){e&&this.helper.recordStreamId(e),this.helper.emitSnapshot()}textUpdated(e,t,s,n){super.textUpdated(e,t,s,n??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}thinkingUpdated(e,t,s,n,r){super.thinkingUpdated(e,t,s,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}messageAppended(e,t,s){super.messageAppended(e,t,s??this.helper.getCurrentRunEventContext()),this.afterEmit(t)}toolCallStateChanged(e,t,s,n,r,i,o){super.toolCallStateChanged(e,t,s,n,r,i,o??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}structuredOutputChanged(e,t,s,n,r){super.structuredOutputChanged(e,t,s,n,r??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(t)}approvalRequested(e,t,s,n,r,i,o){super.approvalRequested(e,t,s,n,r,i,o??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(e)}toolResultAdded(e,t,s,n,r){super.toolResultAdded(e,t,s,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit()}toolApprovalResponded(e,t,s,n){super.toolApprovalResponded(e,t,s,n??this.helper.getCurrentRunEventContext()),this.afterEmit()}clientCreated(e){super.clientCreated(e),this.afterEmit()}loadingChanged(e){super.loadingChanged(e),this.afterEmit()}errorChanged(e){super.errorChanged(e),this.afterEmit()}reloaded(e){super.reloaded(e),this.afterEmit()}stopped(){super.stopped(),this.afterEmit()}messagesCleared(){super.messagesCleared(),this.afterEmit()}messageSent(e,t){super.messageSent(e,t),this.afterEmit()}toolFixtureApplied(e){super.toolFixtureApplied(e),this.afterEmit()}};function Ud(e){return new Fd(e)}var Hr=Object.freeze([]),Bd=Object.freeze([]);function mh(e){const t=(0,I.useId)(),s=e.threadId??t,[n,r]=(0,I.useState)(e.initialMessages||[]),[i,o]=(0,I.useState)(!1),[a,u]=(0,I.useState)(void 0),[l,c]=(0,I.useState)("ready"),[d,h]=(0,I.useState)(!1),[f,p]=(0,I.useState)("disconnected"),[g,m]=(0,I.useState)(!1),[v,S]=(0,I.useState)([]),[C,b]=(0,I.useState)(null),[w,R]=(0,I.useState)(()=>({interrupts:Hr,pendingInterrupts:Hr,interruptErrors:Bd,resuming:!1})),y=(0,I.useRef)(e.initialMessages||[]),_=(0,I.useRef)(!0),T=(0,I.useRef)(!1),E=(0,I.useRef)(null),x=(0,I.useRef)(null),L=(0,I.useRef)(null);y.current=n;const F=(0,I.useRef)(e);F.current=e;const $=(0,I.useCallback)(k=>{k&&(b(k.getCurrentRunId()),R(k.getInterruptState()))},[]),M=(0,I.useMemo)(()=>{const k=e.initialMessages||[];_.current=!1;const D=F.current,q=D.connection?{connection:D.connection}:{fetcher:D.fetcher},ne={current:void 0},U=()=>{const N=ne.current;if(!(!N||E.current!==N))return N},De=[],_e=new Pd({devtoolsBridgeFactory:Ud,...q,initialMessages:k,...D.body!==void 0&&{body:D.body},...D.threadId!==void 0&&{threadId:D.threadId},...D.forwardedProps!==void 0&&{forwardedProps:D.forwardedProps},...D.persistence!==void 0&&{persistence:D.persistence},...D.initialResumeSnapshot!==void 0&&{initialResumeSnapshot:D.initialResumeSnapshot},...D.context!==void 0&&{context:D.context},devtools:{...D.devtools,framework:"react",hookName:"useChat",outputKind:D.outputSchema?"structured":"chat"},onResponse:N=>{U()&&F.current.onResponse?.(N)},onChunk:N=>{U()&&F.current.onChunk?.(N)},onFinish:N=>{U()&&F.current.onFinish?.(N)},onError:N=>{const K=ne.current;if(!K){De.push(N);return}E.current===K&&F.current.onError?.(N)},...D.tools!==void 0&&{tools:D.tools},onCustomEvent:(N,K,B)=>{U()&&F.current.onCustomEvent?.(N,K,B)},...e.streamProcessor!==void 0&&{streamProcessor:e.streamProcessor},onMessagesChange:N=>{U()&&r(N)},onLoadingChange:N=>{const K=U();K&&(o(N),$(K))},onErrorChange:N=>{U()&&u(N)},onStatusChange:N=>{U()&&c(N)},onSubscriptionChange:N=>{U()&&h(N)},onConnectionStatusChange:N=>{U()&&p(N)},onSessionGeneratingChange:N=>{U()&&m(N)},...F.current.queue!==void 0&&{queue:F.current.queue},onQueueChange:N=>{E.current===_e&&S(N)},onRunIdChange:N=>{U()&&b(N)},onResumeStateChange:(N,K)=>{U()&&R(B=>({...B,interrupts:K,pendingInterrupts:K}))},onInterruptStateChange:N=>{U()&&(R(N),F.current.onInterruptStateChange?.(N))}});ne.current=_e,E.current=_e;for(const N of De){if(E.current!==_e)break;F.current.onError?.(N)}return _e},[s,$]);(0,I.useEffect)(()=>{const k=M.getMessages();k!==y.current&&r(k)},[M]),(0,I.useEffect)(()=>{M.updateOptions({body:e.body})},[M,e.body]),(0,I.useEffect)(()=>{e.forwardedProps!==void 0&&M.updateOptions({forwardedProps:e.forwardedProps})},[M,e.forwardedProps]),(0,I.useEffect)(()=>{e.tools!==void 0&&M.updateOptions({tools:e.tools})},[M,e.tools]),(0,I.useEffect)(()=>{M.updateOptions({context:e.context})},[M,e.context]),(0,I.useEffect)(()=>{e.queue!==void 0&&M.updateOptions({queue:e.queue})},[M,e.queue]),(0,I.useEffect)(()=>{e.live?(M.subscribe(),T.current=!0):T.current&&(M.unsubscribe(),T.current=!1)},[M,e.live]),(0,I.useEffect)(()=>(M.attach(),()=>{M.detach()}),[M]),(0,I.useEffect)(()=>(L.current?.client===M&&(clearTimeout(L.current.timeout),L.current=null),x.current&&(clearTimeout(x.current),x.current=null),E.current=M,M.mountDevtools(),$(M),()=>{x.current=setTimeout(()=>{E.current===M&&(E.current=null),x.current=null},0);const k={client:M,timeout:setTimeout(()=>{F.current.live?M.unsubscribe():M.stop(),M.dispose(),L.current===k&&(L.current=null)},0)};L.current=k}),[M,$]);const Ne=(0,I.useCallback)(async(k,D)=>{try{await M.sendMessage(k,void 0,D)}finally{$(M)}},[M,$]),Rn=(0,I.useCallback)(k=>{M.cancelQueued(k)},[M,$]),Cn=(0,I.useCallback)(async k=>{try{await M.append(k)}finally{$(M)}},[M,$]),wn=(0,I.useCallback)(async()=>{try{await M.reload()}finally{$(M)}},[M,$]),bn=(0,I.useCallback)(()=>{M.stop()},[M]),gt=(0,I.useCallback)(()=>{M.clear(),$(M)},[M,$]),pt=(0,I.useCallback)(k=>{M.setMessagesManually(k)},[M]),es=(0,I.useCallback)(async k=>{await M.addToolResult(k)},[M]),ts=(0,I.useCallback)(async k=>{await M.addToolApprovalResponse(k),$(M)},[M,$]),mt=(0,I.useCallback)(async(k,D)=>{const q=await M.resumeInterrupts(k,D??void 0);return $(M),q},[M,$]),Ee=(0,I.useCallback)(k=>{M.resolveInterrupts(k)},[M]),ss=(0,I.useCallback)(()=>{M.cancelInterrupts()},[M]),ns=(0,I.useCallback)(()=>{M.retryInterrupts()},[M]),Ye=(0,I.useCallback)((k,D)=>M.resumeInterruptsUnsafe(k,D),[M]),se=M.getMessages(),W=(0,I.useMemo)(()=>{let k=-1;for(let D=se.length-1;D>=0;D--)if(se[D]?.role==="user"){k=D;break}if(k===-1)return null;for(let D=se.length-1;D>k;D--){const q=se[D];if(q?.role!=="assistant")continue;const ne=q.parts.find(U=>U.type==="structured-output");if(ne)return ne}return null},[se]),ke=(0,I.useMemo)(()=>W?W.partial??W.data??{}:{},[W]),vt=(0,I.useMemo)(()=>!W||W.status!=="complete"?null:W.data,[W]);return{messages:se,sendMessage:Ne,append:Cn,reload:wn,stop:bn,isLoading:i,error:a,status:l,isSubscribed:d,connectionStatus:f,sessionGenerating:g,setMessages:pt,clear:gt,addToolResult:es,addToolApprovalResponse:ts,queue:v,cancelQueued:Rn,runId:C,interrupts:w.interrupts,pendingInterrupts:w.pendingInterrupts,interruptErrors:w.interruptErrors,resuming:w.resuming,resolveInterrupts:Ee,cancelInterrupts:ss,retryInterrupts:ns,resumeInterruptsUnsafe:Ye,resumeInterrupts:mt,partial:ke,final:vt}}var vh=new Uint8Array(128).fill(128);export{si as C,Yd as S,Jd as T,fn as _,fh as a,th as b,uh as c,Fl as d,oh as f,nh as g,Li as h,hh as i,lh as l,rh as m,ph as n,ch as o,ih as p,gh as r,dh as s,mh as t,ah as u,Ai as v,Xd as w,eh as x,sh as y};
|