teodor-new-chat-ui 3.0.147 → 3.0.149
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.esm.js +1222 -1217
- package/dist/index.umd.js +2 -2
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -35,7 +35,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
35
35
|
`+i):r.stack=i}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=Bn(this.defaults,n);const{transitional:r,paramsSerializer:a,headers:i}=n;r!==void 0&&ya.assertOptions(r,{silentJSONParsing:an.transitional(an.boolean),forcedJSONParsing:an.transitional(an.boolean),clarifyTimeoutError:an.transitional(an.boolean)},!1),a!=null&&(G.isFunction(a)?n.paramsSerializer={serialize:a}:ya.assertOptions(a,{encode:an.function,serialize:an.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ya.assertOptions(n,{baseUrl:an.spelling("baseURL"),withXsrfToken:an.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=i&&G.merge(i.common,i[n.method]);i&&G.forEach(["delete","get","head","post","put","patch","common"],E=>{delete i[E]}),n.headers=At.concat(o,i);const s=[];let l=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(n)===!1||(l=l&&f.synchronous,s.unshift(f.fulfilled,f.rejected))});const c=[];this.interceptors.response.forEach(function(f){c.push(f.fulfilled,f.rejected)});let d,_=0,p;if(!l){const E=[U_.bind(this),void 0];for(E.unshift(...s),E.push(...c),p=E.length,d=Promise.resolve(n);_<p;)d=d.then(E[_++],E[_++]);return d}p=s.length;let m=n;for(;_<p;){const E=s[_++],f=s[_++];try{m=E(m)}catch(g){f.call(this,g);break}}try{d=U_.call(this,m)}catch(E){return Promise.reject(E)}for(_=0,p=c.length;_<p;)d=d.then(c[_++],c[_++]);return d}getUri(e){e=Bn(this.defaults,e);const n=O_(e.baseURL,e.url,e.allowAbsoluteUrls);return f_(n,e.params,e.paramsSerializer)}};G.forEach(["delete","get","head","options"],function(e){Gn.prototype[e]=function(n,r){return this.request(Bn(r||{},{method:e,url:n,data:(r||{}).data}))}}),G.forEach(["post","put","patch"],function(e){function n(r){return function(i,o,s){return this.request(Bn(s||{},{method:e,headers:r?{"Content-Type":"multipart/form-data"}:{},url:i,data:o}))}}Gn.prototype[e]=n(),Gn.prototype[e+"Form"]=n(!0)});let Av=class aR{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(i){n=i});const r=this;this.promise.then(a=>{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](a);r._listeners=null}),this.promise.then=a=>{let i;const o=new Promise(s=>{r.subscribe(s),i=s}).then(a);return o.cancel=function(){r.unsubscribe(i)},o},e(function(i,o,s){r.reason||(r.reason=new sr(i,o,s),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new aR(function(a){e=a}),cancel:e}}};function xv(t){return function(n){return t.apply(null,n)}}function Dv(t){return G.isObject(t)&&t.isAxiosError===!0}const fo={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(fo).forEach(([t,e])=>{fo[e]=t});function G_(t){const e=new Gn(t),n=n_(Gn.prototype.request,e);return G.extend(n,Gn.prototype,e,{allOwnKeys:!0}),G.extend(n,e,null,{allOwnKeys:!0}),n.create=function(a){return G_(Bn(t,a))},n}const st=G_(Mr);st.Axios=Gn,st.CanceledError=sr,st.CancelToken=Av,st.isCancel=C_,st.VERSION=F_,st.toFormData=Ca,st.AxiosError=Le,st.Cancel=st.CanceledError,st.all=function(e){return Promise.all(e)},st.spread=xv,st.isAxiosError=Dv,st.mergeConfig=Bn,st.AxiosHeaders=At,st.formToJSON=t=>T_(G.isHTMLForm(t)?new FormData(t):t),st.getAdapter=k_.getAdapter,st.HttpStatusCode=fo,st.default=st;const{Axios:k0,AxiosError:U0,CanceledError:F0,isCancel:B0,CancelToken:G0,VERSION:Y0,all:H0,Cancel:q0,isAxiosError:V0,spread:z0,toFormData:$0,AxiosHeaders:W0,HttpStatusCode:K0,formToJSON:Q0,getAdapter:j0,mergeConfig:X0}=st,Y_=typeof window<"u"?window.__API_BASE_URL__:void 0,So=Y_?Y_.replace(/\/+$/,""):void 0;!So&&typeof window<"u"&&console.warn("API base URL is not configured. The API client will need to be configured via apiConfig prop or window.__API_BASE_URL__.");let Ia=null;const bo=new Set;function H_(){return Ia}function To(t){Ia=t,bo.forEach(e=>e(t))}function q_(t){return bo.add(t),()=>bo.delete(t)}const Bt=st.create({...So?{baseURL:So}:{},timeout:3e4,withCredentials:!0});Bt.interceptors.request.use(t=>(Ia&&(t.headers.Authorization=`Bearer ${Ia}`),t)),Bt.interceptors.response.use(t=>t,t=>Promise.reject(t));async function Gt(t,e){return Bt.defaults.baseURL?(await Bt.get(t,e)).data:Promise.reject(new Error("API base URL is not configured"))}async function V_(t,e,n){return Bt.defaults.baseURL?(await Bt.post(t,e,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function z_(t,e,n){return Bt.defaults.baseURL?(await Bt.put(t,e,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function $_(t,e){return Bt.defaults.baseURL?(await Bt.delete(t,e)).data:Promise.reject(new Error("API base URL is not configured"))}function Yt(t){return t&&typeof t=="object"&&"data"in t?t.data:t}class Aa{get baseUrl(){const e=Bt.defaults.baseURL||"";return String(e).replace(/\/+$|^\s+|\s+$/g,"")}updateConfig(e){e.baseUrl&&(Bt.defaults.baseURL=String(e.baseUrl).replace(/\/+$/g,"")),e.authToken!==void 0&&To(e.authToken)}getAuthToken(){return H_()}setAuthToken(e){To(e)}onTokenChange(e){return q_(e)}async listThreads(){const e=await Gt("/chat/threads"),n=Yt(e);return(n==null?void 0:n.items)??(e==null?void 0:e.items)??[]}async createThread(e){const r=await V_("/chat/threads",e?{title:e}:void 0);return Yt(r)}async updateThread(e,n){const r=await z_(`/chat/threads/${e}`,{title:n});return Yt(r)}async deleteThread(e){const n=await $_(`/chat/threads/${e}`);return Yt(n)}async threadInfo(e){const n=await Gt(`/chat/threads/${e}/info`);return Yt(n)}async listAgents(){const e=await Gt("/chat/agents"),n=Yt(e);return(n==null?void 0:n.items)??[]}async getAgent(e){const n=await Gt(`/chat/agents/${e}`);return Yt(n)}async getAgentSchema(e){const n=await Gt(`/chat/agents/${e}/schema`);return Yt(n)}async getMessages(e){const n=await Gt(`/chat/threads/${e.threadId}/messages`,{params:{thread_id:e.threadId,checkpoint_id:e.checkpointId,checkpoint_ns:e.checkpointNs,limit:e.limit,before_id:e.beforeId??void 0}});return Yt(n)}async getState(e){const n=await Gt(`/chat/threads/${e.threadId}/state`,{params:{thread_id:e.threadId,checkpoint_id:e.checkpointId,checkpoint_ns:e.checkpointNs}});return Yt(n)}async getStateHistory(e){const n=await Gt(`/chat/threads/${e.threadId}/state/history`,{params:{thread_id:e.threadId,checkpoint_id:e.checkpointId,checkpoint_ns:e.checkpointNs}});return Yt(n)}async listCheckpoints(e){const n=await Gt(`/chat/threads/${e}/checkpoints`,{params:{thread_id:e}});return Yt(n)}}const En=new Aa;function W_(t={}){const e=t.baseUrl??"/api/chat",n=t.streamPath??"/runs/stream",[r,a]=y.useState(t.token??null),i=y.useRef(t.headers??{}),[o,s]=y.useState(!1),[l,c]=y.useState(null),[d,_]=y.useState(""),[p,m]=y.useState(null),[E,f]=y.useState(0),[g,S]=y.useState(!1),b=y.useRef(null),h=y.useRef(0),v=y.useCallback(O=>{a(O)},[]),C=y.useCallback(()=>{var O;(O=b.current)==null||O.abort(),b.current=null,s(!1)},[]),R=y.useCallback(()=>{_(""),m(null),c(null)},[]),N=y.useCallback((O,I,D)=>{b.current&&(b.current.abort(),b.current=null),s(!0),c(null),t.autoAppendAssistant!==!1&&_("");const M=new AbortController;return b.current=M,(async()=>{var F,$,x,B,L,U;const Y=(()=>{var z;try{return typeof window<"u"&&((z=window.localStorage)==null?void 0:z.getItem("chat-debug"))==="1"}catch{return!1}})(),K=z=>{var W;try{const ne=JSON.parse(JSON.stringify(z));return(W=ne==null?void 0:ne.payload)!=null&&W.files_info&&Array.isArray(ne.payload.files_info)&&(ne.payload.files_info=ne.payload.files_info.map(q=>({...q,data:q!=null&&q.data?`<base64 ${String(q.data).length} chars>`:q==null?void 0:q.data}))),ne}catch{return z}};try{let z={};try{if(r)z={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const ce=window.__AUTH_TOKEN__,H=((F=window.localStorage)==null?void 0:F.getItem("authToken"))||null;let P=null;try{const Z=($=window.localStorage)==null?void 0:$.getItem("chat-settings");Z&&(P=((x=JSON.parse(Z))==null?void 0:x.apiKey)||null)}catch{}const V=ce||H||P||null;V&&(z={Authorization:`Bearer ${V}`})}}catch{}Y&&console.debug("[use-chat] POST",e+n,K(O));const W=await fetch(e+n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...z,...i.current},body:JSON.stringify(O),signal:M.signal});if(!W.ok||!W.body){const se=await W.text().catch(()=>"");throw Y&&console.debug("[use-chat] non-OK response",W.status,se==null?void 0:se.slice(0,500)),new Error(`stream ${W.status}${se?": "+se:""}`)}S(!0);let ne=null,q=null,X=null;try{const se=W.headers.get("X-Thread-Id")||W.headers.get("x-thread-id"),ce=W.headers.get("X-Thread-Created")||W.headers.get("x-thread-created"),H=se??null,P=String(ce??"").toLowerCase()==="true";(B=D==null?void 0:D.onOpen)==null||B.call(D,{threadId:H,created:P}),ne=W.body.getReader(),q=new TextDecoder;let V="",Z="",ie=h.current;for(;;){const{value:oe,done:Ne}=await ne.read();if(Ne)break;V+=q.decode(oe,{stream:!0});let Ue;for(;(Ue=V.indexOf(`
|
|
36
36
|
|
|
37
37
|
`))>=0;){const Oe=V.slice(0,Ue);V=V.slice(Ue+2);const de=Mv(Oe);if(!de)continue;let Me;try{Me=JSON.parse(de)}catch{Y&&console.debug("[use-chat] skip malformed SSE data:",de==null?void 0:de.slice(0,200));continue}const ae=wv(Me)?Me.data:Me;Y&&console.debug("[use-chat] event:",ae==null?void 0:ae.type,ae);const fe=ae.seq;if(fe!==void 0&&(ie>0&&fe>ie+1&&console.warn(`[use-chat] Gap detected: expected ${ie+1}, got ${fe}`),ie=fe,h.current=fe,f(fe)),fe!==void 0&&fe<=h.current){Y&&console.debug("[use-chat] Duplicate event ignored:",fe);continue}if(ae.type==="token"&&t.autoAppendAssistant!==!1)Z+=ae.content,X||(X=window.setTimeout(()=>{Z&&(_(Te=>Te+Z),Z=""),X=null},50)),I==null||I(ae);else if(ae.type==="message_delta"){const Te=ae.delta.filter(Se=>Se.type==="text").map(Se=>Se.text).join("");Te&&t.autoAppendAssistant!==!1&&(Z+=Te,X||(X=window.setTimeout(()=>{Z&&(_(Se=>Se+Z),Z=""),X=null},50))),I==null||I(ae)}else X&&(window.clearTimeout(X),X=null),Z&&(_(Te=>Te+Z),Z=""),ae.type==="checkpoint"?m(ae.checkpointId):ae.type==="error"&&c(ae.message)}}Z&&_(oe=>oe+Z)}catch(se){if((se==null?void 0:se.name)==="AbortError")return;const ce=(se==null?void 0:se.message)||String(se);Y&&console.debug("[use-chat] error:",ce),c(ce),(L=D==null?void 0:D.onError)==null||L.call(D,ce)}finally{try{ne==null||ne.cancel()}catch{}X&&window.clearTimeout(X),s(!1),S(!1),b.current=null}}catch(z){if((z==null?void 0:z.name)==="AbortError")return;const W=(z==null?void 0:z.message)||String(z);Y&&console.debug("[use-chat] connection error:",W),c(W),(U=D==null?void 0:D.onError)==null||U.call(D,W)}finally{s(!1),S(!1),b.current=null}})(),{close:()=>M.abort()}},[e,r,t.autoAppendAssistant]);return y.useEffect(()=>()=>{var O;return(O=b.current)==null?void 0:O.abort()},[]),{isStreaming:o,error:l,assistantText:d,lastCheckpointId:p,lastSeq:E,connected:g,stream:N,stop:C,clear:R,setToken:v}}function wv(t){return!!t&&typeof t=="object"&&t.protocolVersion==="v1"&&"data"in t}function Mv(t){const e=t.split(/\r?\n/),n=[];for(const r of e)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const a=r.slice(5);n.push(a.startsWith(" ")?a.slice(1):a)}return n.length===0?null:n.join(`
|
|
38
|
-
`)}const Lv={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null};function Pv(t,e){var n;switch(e.type){case"reset":return{messages:ho(((n=e.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null};case"seed":{const r=ho(e.payload.messages),a={...t,messages:r,assemblingId:null};return Object.prototype.hasOwnProperty.call(e.payload,"checkpointId")&&(a.lastCheckpointId=e.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(e.payload,"checkpointNs")&&(a.lastCheckpointNs=e.payload.checkpointNs??null),console.log("[MessageReducer] seed action:",{incomingCount:e.payload.messages.length,sanitizedCount:r.length,checkpointId:a.lastCheckpointId}),a}case"prepend":{const r=ho(e.payload.messages);if(!r.length)return console.log("[MessageReducer] No incoming messages after sanitize - skipping"),t;const a=new Set(t.messages.map(o=>o.id)),i=r.filter(o=>!a.has(o.id));return console.log("[MessageReducer] After dedup:",{uniqueCount:i.length,duplicates:r.length-i.length,finalTotal:i.length+t.messages.length}),i.length?{...t,messages:[...i,...t.messages]}:(console.log("[MessageReducer] All messages were duplicates - skipping"),t)}case"user_message":{const r=e.payload.message;return{...t,messages:[...t.messages,r]}}case"event":return Q_(t,e.payload.ev);case"batch":{const{events:r}=e.payload;return r.length?r.reduce((a,i)=>Q_(a,i),t):t}default:return t}}function K_(t=[]){const[e,n]=y.useReducer(Pv,{...Lv,messages:t}),r=y.useRef([]),a=y.useRef(null),i=y.useRef(null),o=y.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),i.current!==null&&clearTimeout(i.current),a.current=null,i.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),s=y.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?a.current===null&&(a.current=window.requestAnimationFrame(()=>o())):i.current===null&&(i.current=setTimeout(o,8))},[o]),l=y.useCallback(d=>{r.current.push(d),s()},[s]);y.useEffect(()=>()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),i.current!==null&&clearTimeout(i.current),r.current=[]},[]);const c=y.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,_)=>n({type:"seed",payload:{messages:d,..._??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:e,dispatch:n,...c}}function Q_(t,e){var n;if(e.type==="message_start"&&e.role==="assistant"){const r=e.id,a=Gv(e.model),i={id:r,role:"assistant",name:a||void 0,model:e.model,createdAt:new Date().toISOString(),content:[]};return{...t,assemblingId:r,messages:[...t.messages,i]}}if(e.type==="token"){const r=t.assemblingId??Co(t.messages);return r?{...t,messages:Uv(t.messages,r,e.content)}:t}if(e.type==="message_delta"){const r=t.assemblingId??Co(t.messages);return r?{...t,messages:j_(t.messages,r,e.delta)}:t}if(e.type==="message_end"){const r=t.assemblingId??Co(t.messages);if(!r)return{...t,assemblingId:null};const a=t.messages,i=a.findIndex(o=>o.id===r&&o.role==="assistant");if(i>=0&&!((n=a[i].content)==null?void 0:n.some(l=>{var c;return(l==null?void 0:l.type)==="text"&&((c=l.text)==null?void 0:c.trim())}))){const l=[...a.slice(0,i),...a.slice(i+1)];return{...t,assemblingId:null,messages:l}}return t}if(e.type==="tool_start"){const r=`tool-${e.id}`,a={type:"tool_call",id:e.id,name:e.name,args:e.args},i={id:r,role:"tool",name:e.name,createdAt:new Date().toISOString(),content:[a]};return{...t,messages:[...t.messages,i],toolIndex:{...t.toolIndex,[e.id]:r}}}if(e.type==="tool_result"){const r=t.toolIndex[e.id]??`tool-${e.id}`,a={type:"tool_result",toolCallId:e.id,output:e.output,error:e.error},i=t.messages.find(l=>l.id===r),o={id:r,role:"tool",content:[a],createdAt:new Date().toISOString()},s=i?j_(t.messages,r,[a]):[...t.messages,o];return{...t,messages:s}}if(e.type==="checkpoint"){const r=e.checkpointNs??t.lastCheckpointNs??null,a=Bv(t.messages,e.checkpointId,r);return{...t,lastCheckpointId:e.checkpointId,lastCheckpointNs:r,messages:a}}if(e.type==="branch"){const r=e.checkpointId??t.lastCheckpointId,a=e.checkpointNs??t.lastCheckpointNs;return{...t,lastBranch:e,lastCheckpointId:r??null,lastCheckpointNs:a??null}}if(e.type==="error"){const r={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${e.message}`}],createdAt:new Date().toISOString()};return{...t,messages:[...t.messages,r]}}return t}function ho(t){return t.filter(e=>{if(e.role!=="assistant")return!0;const n=(e.content||[]).some(a=>{var i;return a&&a.type==="text"&&((i=a.text)==null?void 0:i.trim())}),r=(e.content||[]).some(a=>a&&a.type==="image_url");return!!(n||r)})}function kv(t,e,n){return e<0||e>=t.length?t:[...t.slice(0,e),n,...t.slice(e+1)]}function Co(t){for(let e=t.length-1;e>=0;e--)if(t[e].role==="assistant")return t[e].id;return null}function Uv(t,e,n){return t.map(r=>{if(r.id!==e)return r;const a=r.content.slice(),i=a[a.length-1];return i&&i.type==="text"?i.text+=n:a.push({type:"text",text:n}),{...r,content:a}})}function j_(t,e,n){return t.map(r=>r.id===e?{...r,content:Fv(r.content,n)}:r)}function Fv(t,e){const n=t.slice();for(const r of e)if(r.type==="text"){const a=n[n.length-1];(a==null?void 0:a.type)==="text"?a.text+=r.text:n.push({type:"text",text:r.text})}else n.push(r);return n}function Bv(t,e,n){for(let r=t.length-1;r>=0;r--)if(t[r].role==="assistant"){const i={...t[r],checkpointId:e,checkpointNs:n??void 0};return kv(t,r,i)}return t}function Gv(t){if(!t)return null;const e=t.split("/");return e[e.length-1]||null}function Yv(t,e){const n=t==null?void 0:t.checkpoints,r=Array.isArray(n)?n.slice():n?Object.values(n):[],a=o=>o&&typeof o=="object"&&typeof o.checkpointId=="string"&&typeof o.createdAt=="string",i=r.filter(a).map(o=>({checkpointId:o.checkpointId,checkpointNs:o.checkpointNs??"",createdAt:o.createdAt,messagesLen:o.messagesLen??0,preview:o.preview??"",role:o.role??null,parentId:o.parentId??null,editedMessageId:o.editedMessageId??null,branchLabel:o.branchLabel??null,lastMessageId:o.lastMessageId??null,hasMessages:typeof o.hasMessages=="boolean"?o.hasMessages:void 0}));return{threadId:(t==null?void 0:t.threadId)??e??null,checkpoints:i}}async function Hv(t){return await new Promise((e,n)=>{const r=new FileReader;r.onload=()=>{try{const a=r.result,i=new Uint8Array(a);let o="";const s=i.byteLength;for(let l=0;l<s;l++)o+=String.fromCharCode(i[l]);e(btoa(o))}catch(a){n(a)}},r.onerror=a=>n(a),r.readAsArrayBuffer(t)})}async function qv(t,e=[],n,r,a,i){const o=[],s=[];for(const l of e)try{const c=await Hv(l);s.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:o,filesInfo:s}}const X_=y.createContext(null);function Pr({children:t,apiConfig:e,onError:n,onThreadChange:r,initialThreadId:a=null,autoLoadInitial:i=!0,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader"}){const l=En;y.useEffect(()=>{e&&l.updateConfig({baseUrl:e.baseUrl,authToken:e.apiKey})},[l,e]);const{isStreaming:c,error:d,stream:_,stop:p,setToken:m}=W_({baseUrl:l.baseUrl,token:null,headers:e==null?void 0:e.headers,streamPath:"/chat/runs/stream"}),[E,f]=y.useState(()=>typeof l.getAuthToken=="function"?l.getAuthToken():null);y.useEffect(()=>{m(typeof l.getAuthToken=="function"?l.getAuthToken():null);const k=l.onTokenChange(j=>{f(j),m(j)});return()=>{k()}},[l,m]);const g=y.useCallback(k=>{l.setAuthToken(k)},[l]),{state:S,seed:b,prepend:h,pushUser:v,onEvent:C,reset:R}=K_(),N=20,[O,I]=y.useState(!1),[D,M]=y.useState(!1),[Y,K]=y.useState(null),[F,$]=y.useState(void 0),[x,B]=y.useState(void 0),[L,U]=y.useState(!1),z=y.useRef(!1),W=y.useRef([]),ne=y.useCallback(k=>{k.cursor!==void 0&&K(k.cursor),k.hasMore!==void 0&&I(k.hasMore),k.checkpointId!==void 0&&$(k.checkpointId),k.checkpointNs!==void 0&&B(k.checkpointNs)},[]),q=y.useCallback((k,j)=>new Promise((be,ke)=>{const Ce=async()=>{if(z.current){console.warn(`[ChatProvider] Operation "${j}" queued - another operation in progress`),W.current.push(Ce);return}z.current=!0;try{console.log(`[ChatProvider] Executing operation: ${j}`),await k(),be()}catch(je){console.error(`[ChatProvider] Operation "${j}" failed:`,je),ke(je)}finally{z.current=!1;const je=W.current.shift();je&&je().catch(()=>{})}};z.current?(W.current.push(Ce),console.log(`[ChatProvider] Queued operation: ${j}`)):Ce().catch(je=>{ke(je)})}),[]),X=y.useCallback((k,j)=>{const be=Array.isArray(k==null?void 0:k.messages)?k.messages:[];j==="replace"?(console.log("[ChatProvider] Replacing messages, count:",be.length),b(be,{checkpointId:(k==null?void 0:k.checkpointId)??null,checkpointNs:(k==null?void 0:k.checkpointNs)??null})):j==="prepend"&&be.length?(console.log("[ChatProvider] Calling prepend with",be.length,"messages"),h(be)):console.log("[ChatProvider] Skipping prepend - empty list or wrong mode"),K((k==null?void 0:k.nextCursor)??null),I(!!(k!=null&&k.hasMore)),$(ke=>(k==null?void 0:k.checkpointId)??ke??void 0),B(ke=>(k==null?void 0:k.checkpointNs)??ke??void 0)},[b,h]),[se,ce]=y.useState([]),[H,P]=y.useState(null),V=y.useCallback(async()=>{const k=await l.listThreads();ce(k)},[l]),[Z,ie]=y.useState(!1),oe=y.useCallback(async k=>{const j=(k==null?void 0:k.maxAttempts)??5,be=(k==null?void 0:k.baseDelayMs)??500,ke=(k==null?void 0:k.timeoutMs)??2e3;if(!l.baseUrl)return!1;const Ce=l.baseUrl.replace(/\/+$/,""),je=["/health","/api/health","/","/api/v2/health","/api/v2/chat/health"],St=async mt=>{try{const Rt=new AbortController,_t=setTimeout(()=>Rt.abort(),ke),Et=await fetch(mt,{method:"GET",signal:Rt.signal});return clearTimeout(_t),Et.ok}catch{return!1}},gn=async mt=>{try{const Rt=new AbortController,_t=setTimeout(()=>Rt.abort(),ke),Et=await fetch(mt,{method:"HEAD",signal:Rt.signal});return clearTimeout(_t),Et.ok}catch{return!1}};for(let mt=0;mt<j;mt++){console.debug(`[ChatProvider] health-check attempt ${mt+1}/${j}`);for(const _t of je){let Et=_t;Ce.endsWith("/api")&&_t.startsWith("/api")&&(Et=_t.replace(/^\/api/,"")||"/");const Wt=Et==="/"?Ce+"/":Ce+Et;if(console.debug(`[ChatProvider] checking ${Wt}`),await St(Wt)||_t==="/"&&await gn(Ce+"/"))return ie(!0),!0}const Rt=be*Math.pow(2,mt);await new Promise(_t=>setTimeout(_t,Rt))}return ie(!1),!1},[l.baseUrl]);y.useEffect(()=>{let k=!0;if(!l.baseUrl){console.debug("[ChatProvider] skipping initial refreshThreads: api.baseUrl not configured");return}return(async()=>{try{const j=await oe();if(!k)return;j?V().catch(()=>{}):console.warn("[ChatProvider] backend health-check failed — skipping initial loads")}catch{}})(),()=>{k=!1}},[V,l.baseUrl,oe]),y.useEffect(()=>{r==null||r(H)},[H,r]);const Ne=y.useRef(null);y.useEffect(()=>{if(a&&i){if(!l.baseUrl){console.debug("[ChatProvider] skipping initial load: api.baseUrl not configured");return}if(!Z){console.debug("[ChatProvider] deferring initial load until backend health-check passes");return}Ne.current!==a&&(Ne.current=a,de(a).catch(()=>{}))}},[a,i,l.baseUrl,Z]);const Ue=y.useRef(null),Oe=y.useRef(null),de=y.useCallback(async(k,j,be)=>{await q(async()=>{if(!l.baseUrl){console.debug("[ChatProvider] skipping loadThread: api.baseUrl not configured");return}if(Ue.current){console.warn(`[ChatProvider] Thread load cancelled - another thread (${Ue.current}) is loading`);return}Oe.current!==null&&Oe.current!==k&&console.log(`[ChatProvider] Thread switch detected: ${Oe.current} -> ${k}`),Ue.current=k,Oe.current=k;try{ne({cursor:null,hasMore:!1,checkpointId:void 0,checkpointNs:void 0});const Ce=await l.getMessages({threadId:k,checkpointId:j,checkpointNs:be,limit:N});P(k);const je=Array.isArray(Ce==null?void 0:Ce.messages)?Ce.messages:[];console.log("[ChatProvider] Loading thread with",je.length,"messages"),b(je,{checkpointId:(Ce==null?void 0:Ce.checkpointId)??null,checkpointNs:(Ce==null?void 0:Ce.checkpointNs)??null}),K((Ce==null?void 0:Ce.nextCursor)??null),I(!!(Ce!=null&&Ce.hasMore)),$(St=>(Ce==null?void 0:Ce.checkpointId)??St??void 0),B(St=>(Ce==null?void 0:Ce.checkpointNs)??St??void 0)}finally{Ue.current=null}},`loadThread-${k}`)},[l,q,ne,b]),Me=y.useCallback(async k=>{const j=await l.listCheckpoints(k);return Yv(j,k)},[l]),ae=y.useCallback(async(k,j)=>{await q(async()=>{if(!H)throw new Error("No active thread");ne({cursor:null,hasMore:!1,checkpointId:void 0,checkpointNs:void 0});const be=await l.getMessages({threadId:H,checkpointId:k,checkpointNs:j??void 0,limit:N});X(be,"replace")},`navigateToCheckpoint-${k}`)},[l,H,X,q,ne]),fe=y.useCallback(async()=>{if(!H)throw new Error("No active thread");await de(H)},[H,de]),Te=y.useRef(!1);y.useEffect(()=>{const k=Te.current;Te.current=c,k&&!c&&H&&q(async()=>{try{await V()}catch(j){console.warn("[ChatProvider] Post-streaming thread refresh failed:",j)}},"postStreamingRefresh")},[c,H,l,X,V,q]);const Se=y.useCallback(async k=>{const j=await l.createThread(k);return await V(),await de(j.threadId),j.threadId},[l,V,de]),tt=y.useCallback(async k=>{await l.deleteThread(k),await V(),H===k&&(P(null),R([]),I(!1),K(null),$(void 0),B(void 0))},[l,V,H,R]),We=y.useCallback(async(k,j)=>{await l.updateThread(k,j),await V()},[l,V]),ct=y.useCallback(async(k,j)=>{var wt;const be=(j==null?void 0:j.attachments)||[],{contentParts:ke,filesInfo:Ce}=await qv(l,be,e==null?void 0:e.uploadPath),je=[];k&&k.trim()&&je.push({type:"text",text:k.trim()});const St={id:((wt=crypto.randomUUID)==null?void 0:wt.call(crypto))||`user-${Date.now()}`,role:"user",content:je,createdAt:new Date().toISOString(),checkpointId:(j==null?void 0:j.checkpointId)??S.lastCheckpointId??void 0,checkpointNs:(j==null?void 0:j.checkpointNs)??S.lastCheckpointNs??void 0};v(St);const gn={...St,content:je},mt={...(j==null?void 0:j.payloadExtras)??{}},Rt=!!mt.edit,_t=mt.originalMessageId,Et=typeof _t=="string"?_t:void 0,Wt=be&&be.length>0,Ge={...H?{threadId:H}:{},payload:{messages:[gn],files_info:Ce,...o&&Wt&&s?{active_agent:s}:{},...mt},checkpointId:(j==null?void 0:j.checkpointId)??S.lastCheckpointId??void 0,checkpointNs:(j==null?void 0:j.checkpointNs)??S.lastCheckpointNs??void 0,nodeFilter:j==null?void 0:j.nodeFilter,config:j==null?void 0:j.config,edit:Rt,originalMessageId:Et};_(Ge,le=>C(le),{onError:le=>console.warn("stream error",le),onOpen:({threadId:le,created:Ee})=>{!H&&le&&(P(le),Ee&&V().catch(()=>{}))}})},[H,v,_,C,S.lastCheckpointId,S.lastCheckpointNs,l,e==null?void 0:e.uploadPath,V,P,o,s]),et=y.useCallback(async k=>{if(!H)throw new Error("No active thread");if(D||!O)return;const j=Y;if(j){M(!0);try{const be=await l.getMessages({threadId:H,checkpointId:F,checkpointNs:x,limit:(k==null?void 0:k.limit)??N,beforeId:j});X(be,"prepend")}finally{M(!1)}}},[l,H,F,x,Y,O,D,X,N]),te={baseUrl:l.baseUrl,token:E,setToken:g,api:l,threads:se,currentThreadId:H,setCurrentThreadId:P,messages:S.messages,isStreaming:c,error:d,lastCheckpointId:S.lastCheckpointId,lastCheckpointNs:S.lastCheckpointNs,streamingAssistantId:S.assemblingId,hasMoreHistory:O,isLoadingHistory:D,isPostStreamFetch:L,loadOlderMessages:et,historyPageSize:N,listCheckpoints:Me,navigateToCheckpoint:ae,returnToLatest:fe,refreshThreads:V,createThread:Se,deleteThread:tt,renameThread:We,loadThread:de,send:ct,stop:p};return u.jsx(X_.Provider,{value:te,children:t})}function xa(){const t=y.useContext(X_);if(!t)throw new Error("useChat must be used within ChatProvider");return t}function Q(...t){return oR.twMerge(iR.clsx(t))}const Vv=yr.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),$e=T.forwardRef(({className:t,variant:e,size:n,asChild:r=!1,...a},i)=>{const o=r?Mt.Slot:"button";return u.jsx(o,{className:Q(Vv({variant:e,size:n,className:t})),ref:i,...a})});$e.displayName="Button";const Z_=T.forwardRef(({className:t,...e},n)=>u.jsx("textarea",{className:Q("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:n,...e}));Z_.displayName="Textarea";function zv({initialValue:t="",editingMessageId:e=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:a=!1,maxLength:i=2e4,onSend:o,onCancelEdit:s,onStop:l,className:c="",textareaClassName:d="",allowEmptySend:_=!1}){const[p,m]=y.useState(t),[E,f]=y.useTransition(),g=y.useRef(null);y.useEffect(()=>{m(t??""),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[t,e]);const S=y.useCallback(()=>{const O=g.current;O&&(O.style.height="auto",O.style.height=`${O.scrollHeight}px`)},[]);y.useEffect(()=>{S()},[S]);const b=y.useCallback(async O=>{O&&O.preventDefault();const I=(p??"").trim();!I&&!_||f(()=>{try{const D=o(I);D&&typeof D.then=="function"?D.then(()=>{m(""),g.current&&(g.current.style.height="auto")}).catch(()=>{}):(m(""),g.current&&(g.current.style.height="auto"))}catch{}})},[p,o,_]),h=y.useCallback(O=>{m(O.target.value),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[]),v=y.useCallback(O=>{O.key==="Enter"&&!O.shiftKey?(O.preventDefault(),b()):O.key==="Escape"&&e&&(O.preventDefault(),s==null||s())},[b,e,s]),N=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${e?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${d}`;return u.jsx("form",{onSubmit:O=>void b(O),className:`w-full ${c}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(Z_,{ref:g,value:p,onChange:h,onKeyDown:v,placeholder:e?"Edit your message...":n,className:N,disabled:a,maxLength:i,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx($e,{type:"button",onClick:()=>{l==null||l()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:a||!l,children:u.jsx(pe.Square,{size:16})}):u.jsx($e,{type:"submit",size:"icon",className:"shrink-0",title:e?"Save changes":"Send message",disabled:a||!p.trim()&&!_||E,children:u.jsx(pe.Send,{size:16})})})]})})}const $v=y.memo(zv),Da=0,Cn=1,lr=2,J_=4;function ep(t){return()=>t}function Wv(t){t()}function tp(t,e){return n=>t(e(n))}function np(t,e){return()=>t(e)}function Kv(t,e){return n=>t(e,n)}function Ro(t){return t!==void 0}function Qv(...t){return()=>{t.map(Wv)}}function cr(){}function wa(t,e){return e(t),t}function jv(t,e){return e(t)}function nt(...t){return t}function Qe(t,e){return t(Cn,e)}function Pe(t,e){t(Da,e)}function vo(t){t(lr)}function lt(t){return t(J_)}function he(t,e){return Qe(t,Kv(e,Da))}function Qt(t,e){const n=t(Cn,r=>{n(),e(r)});return n}function rp(t){let e,n;return r=>a=>{e=a,n&&clearTimeout(n),n=setTimeout(()=>{r(e)},t)}}function ap(t,e){return t===e}function rt(t=ap){let e;return n=>r=>{t(e,r)||(e=r,n(r))}}function Ae(t){return e=>n=>{t(n)&&e(n)}}function me(t){return e=>tp(e,t)}function on(t){return e=>()=>{e(t)}}function J(t,...e){const n=Xv(...e);return(r,a)=>{switch(r){case lr:vo(t);return;case Cn:return Qe(t,n(a))}}}function sn(t,e){return n=>r=>{n(e=t(e,r))}}function Yn(t){return e=>n=>{t>0?t--:e(n)}}function fn(t){let e=null,n;return r=>a=>{e=a,!n&&(n=setTimeout(()=>{n=void 0,r(e)},t))}}function Fe(...t){const e=new Array(t.length);let n=0,r=null;const a=Math.pow(2,t.length)-1;return t.forEach((i,o)=>{const s=Math.pow(2,o);Qe(i,l=>{const c=n;n=n|s,e[o]=l,c!==a&&n===a&&r&&(r(),r=null)})}),i=>o=>{const s=()=>{i([o].concat(e))};n===a?s():r=s}}function Xv(...t){return e=>t.reduceRight(jv,e)}function Zv(t){let e,n;const r=()=>e==null?void 0:e();return function(a,i){switch(a){case Cn:return i?n===i?void 0:(r(),n=i,e=Qe(t,i),e):(r(),cr);case lr:r(),n=null;return}}}function re(t){let e=t;const n=He();return(r,a)=>{switch(r){case Da:e=a;break;case Cn:{a(e);break}case J_:return e}return n(r,a)}}function Tt(t,e){return wa(re(e),n=>he(t,n))}function He(){const t=[];return(e,n)=>{switch(e){case Da:t.slice().forEach(r=>{r(n)});return;case lr:t.splice(0,t.length);return;case Cn:return t.push(n),()=>{const r=t.indexOf(n);r>-1&&t.splice(r,1)}}}}function Lt(t){return wa(He(),e=>he(t,e))}function ze(t,e=[],{singleton:n}={singleton:!0}){return{constructor:t,dependencies:e,id:Jv(),singleton:n}}const Jv=()=>Symbol();function eN(t){const e=new Map,n=({constructor:r,dependencies:a,id:i,singleton:o})=>{if(o&&e.has(i))return e.get(i);const s=r(a.map(l=>n(l)));return o&&e.set(i,s),s};return n(t)}function ut(...t){const e=He(),n=new Array(t.length);let r=0;const a=Math.pow(2,t.length)-1;return t.forEach((i,o)=>{const s=Math.pow(2,o);Qe(i,l=>{n[o]=l,r=r|s,r===a&&Pe(e,n)})}),function(i,o){switch(i){case lr:{vo(e);return}case Cn:return r===a&&o(n),Qe(e,o)}}}function Ie(t,e=ap){return J(t,rt(e))}function No(...t){return function(e,n){switch(e){case lr:return;case Cn:return Qv(...t.map(r=>Qe(r,n)))}}}var xt=(t=>(t[t.DEBUG=0]="DEBUG",t[t.INFO=1]="INFO",t[t.WARN=2]="WARN",t[t.ERROR=3]="ERROR",t))(xt||{});const tN={0:"debug",3:"error",1:"log",2:"warn"},nN=()=>typeof globalThis>"u"?window:globalThis,Rn=ze(()=>{const t=re(3);return{log:re((e,n,r=1)=>{var a;const i=(a=nN().VIRTUOSO_LOG_LEVEL)!=null?a:lt(t);r>=i&&console[tN[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",e,n)}),logLevel:t}},[],{singleton:!0});function Hn(t,e,n){return Oo(t,e,n).callbackRef}function Oo(t,e,n){const r=y.useRef(null);let a=o=>{};const i=y.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(o=>{const s=()=>{const l=o[0].target;l.offsetParent!==null&&t(l)};n?s():requestAnimationFrame(s)}):null,[t,n]);return a=o=>{o&&e?(i==null||i.observe(o),r.current=o):(r.current&&(i==null||i.unobserve(r.current)),r.current=null)},{callbackRef:a,ref:r}}function rN(t,e,n,r,a,i,o,s,l){const c=y.useCallback(d=>{const _=aN(d.children,e,s?"offsetWidth":"offsetHeight",a);let p=d.parentElement;for(;!p.dataset.virtuosoScroller;)p=p.parentElement;const m=p.lastElementChild.dataset.viewportType==="window";let E;m&&(E=p.ownerDocument.defaultView);const f=o?s?o.scrollLeft:o.scrollTop:m?s?E.scrollX||E.document.documentElement.scrollLeft:E.scrollY||E.document.documentElement.scrollTop:s?p.scrollLeft:p.scrollTop,g=o?s?o.scrollWidth:o.scrollHeight:m?s?E.document.documentElement.scrollWidth:E.document.documentElement.scrollHeight:s?p.scrollWidth:p.scrollHeight,S=o?s?o.offsetWidth:o.offsetHeight:m?s?E.innerWidth:E.innerHeight:s?p.offsetWidth:p.offsetHeight;r({scrollHeight:g,scrollTop:Math.max(f,0),viewportHeight:S}),i==null||i(s?ip("column-gap",getComputedStyle(d).columnGap,a):ip("row-gap",getComputedStyle(d).rowGap,a)),_!==null&&t(_)},[t,e,a,i,o,r,s]);return Oo(c,n,l)}function aN(t,e,n,r){const a=t.length;if(a===0)return null;const i=[];for(let o=0;o<a;o++){const s=t.item(o);if(s.dataset.index===void 0)continue;const l=parseInt(s.dataset.index),c=parseFloat(s.dataset.knownSize),d=e(s,n);if(d===0&&r("Zero-sized element, this should not happen",{child:s},xt.ERROR),d===c)continue;const _=i[i.length-1];i.length===0||_.size!==d||_.endIndex!==l-1?i.push({endIndex:l,size:d,startIndex:l}):i[i.length-1].endIndex++}return i}function ip(t,e,n){return e!=="normal"&&!(e!=null&&e.endsWith("px"))&&n(`${t} was not resolved to pixel value correctly`,e,xt.WARN),e==="normal"?0:parseInt(e??"0",10)}function op(t,e,n){const r=y.useRef(null),a=y.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let _,p;if(e){const m=e.getBoundingClientRect(),E=c.top-m.top;p=m.height-Math.max(0,E),_=E+e.scrollTop}else{const m=o.current.ownerDocument.defaultView;p=m.innerHeight-Math.max(0,c.top),_=c.top+m.scrollY}r.current={offsetTop:_,visibleHeight:p,visibleWidth:d},t(r.current)},[t,e]),{callbackRef:i,ref:o}=Oo(a,!0,n),s=y.useCallback(()=>{a(o.current)},[a,o]);return y.useEffect(()=>{var l;if(e){e.addEventListener("scroll",s);const c=new ResizeObserver(()=>{requestAnimationFrame(s)});return c.observe(e),()=>{e.removeEventListener("scroll",s),c.unobserve(e)}}else{const c=(l=o.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",s),c==null||c.addEventListener("resize",s),()=>{c==null||c.removeEventListener("scroll",s),c==null||c.removeEventListener("resize",s)}}},[s,e,o]),i}const Nt=ze(()=>{const t=He(),e=He(),n=re(0),r=He(),a=re(0),i=He(),o=He(),s=re(0),l=re(0),c=re(0),d=re(0),_=He(),p=He(),m=re(!1),E=re(!1),f=re(!1);return he(J(t,me(({scrollTop:g})=>g)),e),he(J(t,me(({scrollHeight:g})=>g)),o),he(e,a),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:s,horizontalDirection:E,scrollBy:p,scrollContainerState:t,scrollHeight:o,scrollingInProgress:m,scrollTo:_,scrollTop:e,skipAnimationFrameInResizeObserver:f,smoothScrollTargetReached:r,statefulScrollTop:a,viewportHeight:i}},[],{singleton:!0}),kr={lvl:0};function sp(t,e){const n=t.length;if(n===0)return[];let{index:r,value:a}=e(t[0]);const i=[];for(let o=1;o<n;o++){const{index:s,value:l}=e(t[o]);i.push({end:s-1,start:r,value:a}),r=s,a=l}return i.push({end:1/0,start:r,value:a}),i}function Ze(t){return t===kr}function Ur(t,e){if(!Ze(t))return e===t.k?t.v:e<t.k?Ur(t.l,e):Ur(t.r,e)}function jt(t,e,n="k"){if(Ze(t))return[-1/0,void 0];if(Number(t[n])===e)return[t.k,t.v];if(Number(t[n])<e){const r=jt(t.r,e,n);return r[0]===-1/0?[t.k,t.v]:r}return jt(t.l,e,n)}function Pt(t,e,n){return Ze(t)?dp(e,n,1):e===t.k?pt(t,{k:e,v:n}):e<t.k?up(pt(t,{l:Pt(t.l,e,n)})):up(pt(t,{r:Pt(t.r,e,n)}))}function dr(){return kr}function Ma(t,e,n){if(Ze(t))return[];const r=jt(t,e)[0];return iN(Io(t,r,n))}function yo(t,e){if(Ze(t))return kr;const{k:n,l:r,r:a}=t;if(e===n){if(Ze(r))return a;if(Ze(a))return r;{const[i,o]=cp(r);return La(pt(t,{k:i,l:lp(r),v:o}))}}else return e<n?La(pt(t,{l:yo(r,e)})):La(pt(t,{r:yo(a,e)}))}function qn(t){return Ze(t)?[]:[...qn(t.l),{k:t.k,v:t.v},...qn(t.r)]}function Io(t,e,n){if(Ze(t))return[];const{k:r,l:a,r:i,v:o}=t;let s=[];return r>e&&(s=s.concat(Io(a,e,n))),r>=e&&r<=n&&s.push({k:r,v:o}),r<=n&&(s=s.concat(Io(i,e,n))),s}function La(t){const{l:e,lvl:n,r}=t;if(r.lvl>=n-1&&e.lvl>=n-1)return t;if(n>r.lvl+1){if(Ao(e))return _p(pt(t,{lvl:n-1}));if(!Ze(e)&&!Ze(e.r))return pt(e.r,{l:pt(e,{r:e.r.l}),lvl:n,r:pt(t,{l:e.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(Ao(t))return xo(pt(t,{lvl:n-1}));if(!Ze(r)&&!Ze(r.l)){const a=r.l,i=Ao(a)?r.lvl-1:r.lvl;return pt(a,{l:pt(t,{lvl:n-1,r:a.l}),lvl:a.lvl+1,r:xo(pt(r,{l:a.r,lvl:i}))})}else throw new Error("Unexpected empty nodes")}}function pt(t,e){return dp(e.k!==void 0?e.k:t.k,e.v!==void 0?e.v:t.v,e.lvl!==void 0?e.lvl:t.lvl,e.l!==void 0?e.l:t.l,e.r!==void 0?e.r:t.r)}function lp(t){return Ze(t.r)?t.l:La(pt(t,{r:lp(t.r)}))}function Ao(t){return Ze(t)||t.lvl>t.r.lvl}function cp(t){return Ze(t.r)?[t.k,t.v]:cp(t.r)}function dp(t,e,n,r=kr,a=kr){return{k:t,l:r,lvl:n,r:a,v:e}}function up(t){return xo(_p(t))}function _p(t){const{l:e}=t;return!Ze(e)&&e.lvl===t.lvl?pt(e,{r:pt(t,{l:e.r})}):t}function xo(t){const{lvl:e,r:n}=t;return!Ze(n)&&!Ze(n.r)&&n.lvl===e&&n.r.lvl===e?pt(n,{l:pt(t,{r:n.l}),lvl:e+1}):t}function iN(t){return sp(t,({k:e,v:n})=>({index:e,value:n}))}function pp(t,e){return!!(t&&t.startIndex===e.startIndex&&t.endIndex===e.endIndex)}function Fr(t,e){return!!(t&&t[0]===e[0]&&t[1]===e[1])}const Do=ze(()=>({recalcInProgress:re(!1)}),[],{singleton:!0});function mp(t,e,n){return t[Pa(t,e,n)]}function Pa(t,e,n,r=0){let a=t.length-1;for(;r<=a;){const i=Math.floor((r+a)/2),o=t[i],s=n(o,e);if(s===0)return i;if(s===-1){if(a-r<2)return i-1;a=i-1}else{if(a===r)return i;r=i+1}}throw new Error(`Failed binary finding record in array - ${t.join(",")}, searched for ${e}`)}function oN(t,e,n,r){const a=Pa(t,e,r),i=Pa(t,n,r,a);return t.slice(a,i+1)}function vn(t,e){return Math.round(t.getBoundingClientRect()[e])}function ka(t){return!Ze(t.groupOffsetTree)}function wo({index:t},e){return e===t?0:e<t?-1:1}function sN(){return{groupIndices:[],groupOffsetTree:dr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:dr()}}function lN(t,e){let n=Ze(t)?0:1/0;for(const r of e){const{endIndex:a,size:i,startIndex:o}=r;if(n=Math.min(n,o),Ze(t)){t=Pt(t,0,i);continue}const s=Ma(t,o-1,a+1);if(s.some(gN(r)))continue;let l=!1,c=!1;for(const{end:d,start:_,value:p}of s)l?(a>=_||i===p)&&(t=yo(t,_)):(c=p!==i,l=!0),d>a&&a>=_&&p!==i&&(t=Pt(t,a+1,p));c&&(t=Pt(t,o,i))}return[t,n]}function cN(t){return typeof t.groupIndex<"u"}function dN({offset:t},e){return e===t?0:e<t?-1:1}function Br(t,e,n){if(e.length===0)return 0;const{index:r,offset:a,size:i}=mp(e,t,wo),o=t-r,s=i*o+(o-1)*n+a;return s>0?s+n:s}function gp(t,e){if(!ka(e))return t;let n=0;for(;e.groupIndices[n]<=t+n;)n++;return t+n}function Ep(t,e,n){if(cN(t))return e.groupIndices[t.groupIndex]+1;{const r=t.index==="LAST"?n:t.index;let a=gp(r,e);return a=Math.max(0,a,Math.min(n,a)),a}}function uN(t,e,n,r=0){return r>0&&(e=Math.max(e,mp(t,r,wo).offset)),sp(oN(t,e,n,dN),mN)}function _N(t,[e,n,r,a]){e.length>0&&r("received item sizes",e,xt.DEBUG);const i=t.sizeTree;let o=i,s=0;if(n.length>0&&Ze(i)&&e.length===2){const p=e[0].size,m=e[1].size;o=n.reduce((E,f)=>Pt(Pt(E,f,p),f+1,m),o)}else[o,s]=lN(o,e);if(o===i)return t;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:_}=Mo(t.offsetTree,s,o,a);return{groupIndices:n,groupOffsetTree:n.reduce((p,m)=>Pt(p,m,Br(m,_,a)),dr()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:_,sizeTree:o}}function pN(t){return qn(t).map(({k:e,v:n},r,a)=>{const i=a[r+1];return{endIndex:i?i.k-1:1/0,size:n,startIndex:e}})}function fp(t,e){let n=0,r=0;for(;n<t;)n+=e[r+1]-e[r]-1,r++;return r-(n===t?0:1)}function Mo(t,e,n,r){let a=t,i=0,o=0,s=0,l=0;if(e!==0){l=Pa(a,e-1,wo),s=a[l].offset;const c=jt(n,e-1);i=c[0],o=c[1],a.length&&a[l].size===jt(n,e)[1]&&(l-=1),a=a.slice(0,l+1)}else a=[];for(const{start:c,value:d}of Ma(n,e,1/0)){const _=c-i,p=_*o+s+_*r;a.push({index:c,offset:p,size:d}),i=c,s=p,o=d}return{lastIndex:i,lastOffset:s,lastSize:o,offsetTree:a}}function mN(t){return{index:t.index,value:t}}function gN(t){const{endIndex:e,size:n,startIndex:r}=t;return a=>a.start===r&&(a.end===e||a.end===1/0)&&a.value===n}const EN={offsetHeight:"height",offsetWidth:"width"},ln=ze(([{log:t},{recalcInProgress:e}])=>{const n=He(),r=He(),a=Tt(r,0),i=He(),o=He(),s=re(0),l=re([]),c=re(void 0),d=re(void 0),_=re((C,R)=>vn(C,EN[R])),p=re(void 0),m=re(0),E=sN(),f=Tt(J(n,Fe(l,t,m),sn(_N,E),rt()),E),g=Tt(J(l,rt(),sn((C,R)=>({current:R,prev:C.current}),{current:[],prev:[]}),me(({prev:C})=>C)),[]);he(J(l,Ae(C=>C.length>0),Fe(f,m),me(([C,R,N])=>{const O=C.reduce((I,D,M)=>Pt(I,D,Br(D,R.offsetTree,N)||M),dr());return{...R,groupIndices:C,groupOffsetTree:O}})),f),he(J(r,Fe(f),Ae(([C,{lastIndex:R}])=>C<R),me(([C,{lastIndex:R,lastSize:N}])=>[{endIndex:R,size:N,startIndex:C}])),n),he(c,d);const S=Tt(J(c,me(C=>C===void 0)),!0);he(J(d,Ae(C=>C!==void 0&&Ze(lt(f).sizeTree)),me(C=>[{endIndex:0,size:C,startIndex:0}])),n);const b=Lt(J(n,Fe(f),sn(({sizes:C},[R,N])=>({changed:N!==C,sizes:N}),{changed:!1,sizes:E}),me(C=>C.changed)));Qe(J(s,sn((C,R)=>({diff:C.prev-R,prev:R}),{diff:0,prev:0}),me(C=>C.diff)),C=>{const{groupIndices:R}=lt(f);if(C>0)Pe(e,!0),Pe(i,C+fp(C,R));else if(C<0){const N=lt(g);N.length>0&&(C-=fp(-C,N)),Pe(o,C)}}),Qe(J(s,Fe(t)),([C,R])=>{C<0&&R("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:s},xt.ERROR)});const h=Lt(i);he(J(i,Fe(f),me(([C,R])=>{const N=R.groupIndices.length>0,O=[],I=R.lastSize;if(N){const D=Ur(R.sizeTree,0);let M=0,Y=0;for(;M<C;){const F=R.groupIndices[Y],$=R.groupIndices.length===Y+1?1/0:R.groupIndices[Y+1]-F-1;O.push({endIndex:F,size:D,startIndex:F}),O.push({endIndex:F+1+$-1,size:I,startIndex:F+1}),Y++,M+=$+1}const K=qn(R.sizeTree);return M!==C&&K.shift(),K.reduce((F,{k:$,v:x})=>{let B=F.ranges;return F.prevSize!==0&&(B=[...F.ranges,{endIndex:$+C-1,size:F.prevSize,startIndex:F.prevIndex}]),{prevIndex:$+C,prevSize:x,ranges:B}},{prevIndex:C,prevSize:0,ranges:O}).ranges}return qn(R.sizeTree).reduce((D,{k:M,v:Y})=>({prevIndex:M+C,prevSize:Y,ranges:[...D.ranges,{endIndex:M+C-1,size:D.prevSize,startIndex:D.prevIndex}]}),{prevIndex:0,prevSize:I,ranges:[]}).ranges})),n);const v=Lt(J(o,Fe(f,m),me(([C,{offsetTree:R},N])=>{const O=-C;return Br(O,R,N)})));return he(J(o,Fe(f,m),me(([C,R,N])=>{if(R.groupIndices.length>0){if(Ze(R.sizeTree))return R;let O=dr();const I=lt(g);let D=0,M=0,Y=0;for(;D<-C;){Y=I[M];const K=I[M+1]-Y-1;M++,D+=K+1}if(O=qn(R.sizeTree).reduce((K,{k:F,v:$})=>Pt(K,Math.max(0,F+C),$),O),D!==-C){const K=Ur(R.sizeTree,Y);O=Pt(O,0,K);const F=jt(R.sizeTree,-C+1)[1];O=Pt(O,1,F)}return{...R,sizeTree:O,...Mo(R.offsetTree,0,O,N)}}else{const O=qn(R.sizeTree).reduce((I,{k:D,v:M})=>Pt(I,Math.max(0,D+C),M),dr());return{...R,sizeTree:O,...Mo(R.offsetTree,0,O,N)}}})),f),{beforeUnshiftWith:h,data:p,defaultItemSize:d,firstItemIndex:s,fixedItemSize:c,gap:m,groupIndices:l,itemSize:_,listRefresh:b,shiftWith:o,shiftWithOffset:v,sizeRanges:n,sizes:f,statefulTotalCount:a,totalCount:r,trackItemSizes:S,unshiftWith:i}},nt(Rn,Do),{singleton:!0});function fN(t){return t.reduce((e,n)=>(e.groupIndices.push(e.totalCount),e.totalCount+=n+1,e),{groupIndices:[],totalCount:0})}const Sp=ze(([{groupIndices:t,sizes:e,totalCount:n},{headerHeight:r,scrollTop:a}])=>{const i=He(),o=He(),s=Lt(J(i,me(fN)));return he(J(s,me(l=>l.totalCount)),n),he(J(s,me(l=>l.groupIndices)),t),he(J(ut(a,e,r),Ae(([l,c])=>ka(c)),me(([l,c,d])=>jt(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),rt(),me(l=>[l])),o),{groupCounts:i,topItemsIndexes:o}},nt(ln,Nt)),Nn=ze(([{log:t}])=>{const e=re(!1),n=Lt(J(e,Ae(r=>r),rt()));return Qe(e,r=>{r&<(t)("props updated",{},xt.DEBUG)}),{didMount:n,propsReady:e}},nt(Rn),{singleton:!0}),SN=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function bp(t){const e=typeof t=="number"?{index:t}:t;return e.align||(e.align="start"),(!e.behavior||!SN)&&(e.behavior="auto"),e.offset||(e.offset=0),e}const Gr=ze(([{gap:t,listRefresh:e,sizes:n,totalCount:r},{fixedFooterHeight:a,fixedHeaderHeight:i,footerHeight:o,headerHeight:s,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:_},{log:p}])=>{const m=He(),E=He(),f=re(0);let g=null,S=null,b=null;function h(){g&&(g(),g=null),b&&(b(),b=null),S&&(clearTimeout(S),S=null),Pe(l,!1)}return he(J(m,Fe(n,_,r,f,s,o,p),Fe(t,i,a),me(([[v,C,R,N,O,I,D,M],Y,K,F])=>{const $=bp(v),{align:x,behavior:B,offset:L}=$,U=N-1,z=Ep($,C,U);let W=Br(z,C.offsetTree,Y)+I;x==="end"?(W+=K+jt(C.sizeTree,z)[1]-R+F,z===U&&(W+=D)):x==="center"?W+=(K+jt(C.sizeTree,z)[1]-R+F)/2:W-=O,L&&(W+=L);const ne=q=>{h(),q?(M("retrying to scroll to",{location:v},xt.DEBUG),Pe(m,v)):(Pe(E,!0),M("list did not change, scroll successful",{},xt.DEBUG))};if(h(),B==="smooth"){let q=!1;b=Qe(e,X=>{q=q||X}),g=Qt(d,()=>{ne(q)})}else g=Qt(J(e,bN(150)),ne);return S=setTimeout(()=>{h()},1200),Pe(l,!0),M("scrolling from index to",{behavior:B,index:z,top:W},xt.DEBUG),{behavior:B,top:W}})),c),{scrollTargetReached:E,scrollToIndex:m,topListHeight:f}},nt(ln,Nt,Rn),{singleton:!0});function bN(t){return e=>{const n=setTimeout(()=>{e(!1)},t);return r=>{r&&(e(!0),clearTimeout(n))}}}function Lo(t,e){t==0?e():requestAnimationFrame(()=>{Lo(t-1,e)})}function Po(t,e){const n=e-1;return typeof t=="number"?t:t.index==="LAST"?n:t.index}const Yr=ze(([{defaultItemSize:t,listRefresh:e,sizes:n},{scrollTop:r},{scrollTargetReached:a,scrollToIndex:i},{didMount:o}])=>{const s=re(!0),l=re(0),c=re(!0);return he(J(o,Fe(l),Ae(([d,_])=>!!_),on(!1)),s),he(J(o,Fe(l),Ae(([d,_])=>!!_),on(!1)),c),Qe(J(ut(e,o),Fe(s,n,t,c),Ae(([[,d],_,{sizeTree:p},m,E])=>d&&(!Ze(p)||Ro(m))&&!_&&!E),Fe(l)),([,d])=>{Qt(a,()=>{Pe(c,!0)}),Lo(4,()=>{Qt(r,()=>{Pe(s,!0)}),Pe(i,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:s}},nt(ln,Nt,Gr,Nn),{singleton:!0});function Tp(t,e){return Math.abs(t-e)<1.01}const Hr="up",qr="down",TN="none",hN={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},CN=0,Vr=ze(([{footerHeight:t,headerHeight:e,scrollBy:n,scrollContainerState:r,scrollTop:a,viewportHeight:i}])=>{const o=re(!1),s=re(!0),l=He(),c=He(),d=re(4),_=re(CN),p=Tt(J(No(J(Ie(a),Yn(1),on(!0)),J(Ie(a),Yn(1),on(!1),rp(100))),rt()),!1),m=Tt(J(No(J(n,on(!0)),J(n,on(!1),rp(200))),rt()),!1);he(J(ut(Ie(a),Ie(_)),me(([b,h])=>b<=h),rt()),s),he(J(s,fn(50)),c);const E=Lt(J(ut(r,Ie(i),Ie(e),Ie(t),Ie(d)),sn((b,[{scrollHeight:h,scrollTop:v},C,R,N,O])=>{const I=v+C-h>-O,D={scrollHeight:h,scrollTop:v,viewportHeight:C};if(I){let Y,K;return v>b.state.scrollTop?(Y="SCROLLED_DOWN",K=b.state.scrollTop-v):(Y="SIZE_DECREASED",K=b.state.scrollTop-v||b.scrollTopDelta),{atBottom:!0,atBottomBecause:Y,scrollTopDelta:K,state:D}}let M;return D.scrollHeight>b.state.scrollHeight?M="SIZE_INCREASED":C<b.state.viewportHeight?M="VIEWPORT_HEIGHT_DECREASING":v<b.state.scrollTop?M="SCROLLING_UPWARDS":M="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:M,state:D}},hN),rt((b,h)=>b&&b.atBottom===h.atBottom))),f=Tt(J(r,sn((b,{scrollHeight:h,scrollTop:v,viewportHeight:C})=>{if(Tp(b.scrollHeight,h))return{changed:!1,jump:0,scrollHeight:h,scrollTop:v};{const R=h-(v+C)<1;return b.scrollTop!==v&&R?{changed:!0,jump:b.scrollTop-v,scrollHeight:h,scrollTop:v}:{changed:!0,jump:0,scrollHeight:h,scrollTop:v}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ae(b=>b.changed),me(b=>b.jump)),0);he(J(E,me(b=>b.atBottom)),o),he(J(o,fn(50)),l);const g=re(qr);he(J(r,me(({scrollTop:b})=>b),rt(),sn((b,h)=>lt(m)?{direction:b.direction,prevScrollTop:h}:{direction:h<b.prevScrollTop?Hr:qr,prevScrollTop:h},{direction:qr,prevScrollTop:0}),me(b=>b.direction)),g),he(J(r,fn(50),on(TN)),g);const S=re(0);return he(J(p,Ae(b=>!b),on(0)),S),he(J(a,fn(100),Fe(p),Ae(([b,h])=>!!h),sn(([b,h],[v])=>[h,v],[0,0]),me(([b,h])=>h-b)),S),{atBottomState:E,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:_,isAtBottom:o,isAtTop:s,isScrolling:p,lastJumpDueToItemResize:f,scrollDirection:g,scrollVelocity:S}},nt(Nt)),Ua="top",Fa="bottom",hp="none";function Cp(t,e,n){return typeof t=="number"?n===Hr&&e===Ua||n===qr&&e===Fa?t:0:n===Hr?e===Ua?t.main:t.reverse:e===Fa?t.main:t.reverse}function Rp(t,e){var n;return typeof t=="number"?t:(n=t[e])!=null?n:0}const ko=ze(([{deviation:t,fixedHeaderHeight:e,headerHeight:n,scrollTop:r,viewportHeight:a}])=>{const i=He(),o=re(0),s=re(0),l=re(0),c=Tt(J(ut(Ie(r),Ie(a),Ie(n),Ie(i,Fr),Ie(l),Ie(o),Ie(e),Ie(t),Ie(s)),me(([d,_,p,[m,E],f,g,S,b,h])=>{const v=d-b,C=g+S,R=Math.max(p-v,0);let N=hp;const O=Rp(h,Ua),I=Rp(h,Fa);return m-=b,m+=p+S,E+=p+S,E-=b,m>d+C-O&&(N=Hr),E<d-R+_+I&&(N=qr),N!==hp?[Math.max(v-p-Cp(f,Ua,N)-O,0),v-R-S+_+Cp(f,Fa,N)+I]:null}),Ae(d=>d!=null),rt(Fr)),[0,0]);return{increaseViewportBy:s,listBoundary:i,overscan:l,topListHeight:o,visibleRange:c}},nt(Nt),{singleton:!0});function RN(t,e,n){if(ka(e)){const r=gp(t,e);return[{index:jt(e.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:t,offset:0,size:0}]}const Uo={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Ba(t,e,n,r,a,i){const{lastIndex:o,lastOffset:s,lastSize:l}=a;let c=0,d=0;if(t.length>0){c=t[0].offset;const f=t[t.length-1];d=f.offset+f.size}const _=n-o,p=s+_*l+(_-1)*r,m=c,E=p-d;return{bottom:d,firstItemIndex:i,items:Np(t,a,i),offsetBottom:E,offsetTop:c,top:m,topItems:Np(e,a,i),topListHeight:e.reduce((f,g)=>g.size+f,0),totalCount:n}}function vp(t,e,n,r,a,i){let o=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-o>=t)break;o++}const s=t+o,l=Po(e,s),c=Array.from({length:s}).map((d,_)=>({data:i[_+l],index:_+l,offset:0,size:0}));return Ba(c,[],s,a,n,r)}function Np(t,e,n){if(t.length===0)return[];if(!ka(e))return t.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=t[0].index,a=t[t.length-1].index,i=[],o=Ma(e.groupOffsetTree,r,a);let s,l=0;for(const c of t){(!s||s.end<c.index)&&(s=o.shift(),l=e.groupIndices.indexOf(s.start));let d;c.index===s.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},i.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return i}const Vn=ze(([{data:t,firstItemIndex:e,gap:n,sizes:r,totalCount:a},i,{listBoundary:o,topListHeight:s,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:_},p,{didMount:m},{recalcInProgress:E}])=>{const f=re([]),g=re(0),S=He();he(i.topItemsIndexes,f);const b=Tt(J(ut(m,E,Ie(l,Fr),Ie(a),Ie(r),Ie(c),d,Ie(f),Ie(e),Ie(n),t),Ae(([R,N,,O,,,,,,,I])=>{const D=I&&I.length!==O;return R&&!N&&!D}),me(([,,[R,N],O,I,D,M,Y,K,F,$])=>{const x=I,{offsetTree:B,sizeTree:L}=x,U=lt(g);if(O===0)return{...Uo,totalCount:O};if(R===0&&N===0)return U===0?{...Uo,totalCount:O}:vp(U,D,I,K,F,$||[]);if(Ze(L))return U>0?null:Ba(RN(Po(D,O),x,$),[],O,F,x,K);const z=[];if(Y.length>0){const se=Y[0],ce=Y[Y.length-1];let H=0;for(const P of Ma(L,se,ce)){const V=P.value,Z=Math.max(P.start,se),ie=Math.min(P.end,ce);for(let oe=Z;oe<=ie;oe++)z.push({data:$==null?void 0:$[oe],index:oe,offset:H,size:V}),H+=V}}if(!M)return Ba([],z,O,F,x,K);const W=Y.length>0?Y[Y.length-1]+1:0,ne=uN(B,R,N,W);if(ne.length===0)return null;const q=O-1,X=wa([],se=>{for(const ce of ne){const H=ce.value;let P=H.offset,V=ce.start;const Z=H.size;if(H.offset<R){V+=Math.floor((R-H.offset+F)/(Z+F));const oe=V-ce.start;P+=oe*Z+oe*F}V<W&&(P+=(W-V)*Z,V=W);const ie=Math.min(ce.end,q);for(let oe=V;oe<=ie&&!(P>=N);oe++)se.push({data:$==null?void 0:$[oe],index:oe,offset:P,size:Z}),P+=Z+F}});return Ba(X,z,O,F,x,K)}),Ae(R=>R!==null),rt()),Uo);he(J(t,Ae(Ro),me(R=>R==null?void 0:R.length)),a),he(J(b,me(R=>R.topListHeight)),_),he(_,s),he(J(b,me(R=>[R.top,R.bottom])),o),he(J(b,me(R=>R.items)),S);const h=Lt(J(b,Ae(({items:R})=>R.length>0),Fe(a,t),Ae(([{items:R},N])=>R[R.length-1].originalIndex===N-1),me(([,R,N])=>[R-1,N]),rt(Fr),me(([R])=>R))),v=Lt(J(b,fn(200),Ae(({items:R,topItems:N})=>R.length>0&&R[0].originalIndex===N.length),me(({items:R})=>R[0].index),rt())),C=Lt(J(b,Ae(({items:R})=>R.length>0),me(({items:R})=>{let N=0,O=R.length-1;for(;R[N].type==="group"&&N<O;)N++;for(;R[O].type==="group"&&O>N;)O--;return{endIndex:R[O].index,startIndex:R[N].index}}),rt(pp)));return{endReached:h,initialItemCount:g,itemsRendered:S,listState:b,rangeChanged:C,startReached:v,topItemsIndexes:f,...p}},nt(ln,Sp,ko,Yr,Gr,Vr,Nn,Do),{singleton:!0}),Op=ze(([{fixedFooterHeight:t,fixedHeaderHeight:e,footerHeight:n,headerHeight:r},{listState:a}])=>{const i=He(),o=Tt(J(ut(n,t,r,e,a),me(([s,l,c,d,_])=>s+l+c+d+_.offsetBottom+_.bottom)),0);return he(Ie(o),i),{totalListHeight:o,totalListHeightChanged:i}},nt(Nt,Vn),{singleton:!0}),vN=ze(([{viewportHeight:t},{totalListHeight:e}])=>{const n=re(!1),r=Tt(J(ut(n,t,e),Ae(([a])=>a),me(([,a,i])=>Math.max(0,a-i)),fn(0),rt()),0);return{alignToBottom:n,paddingTopAddition:r}},nt(Nt,Op),{singleton:!0}),yp=ze(()=>({context:re(null)})),NN=({itemBottom:t,itemTop:e,locationParams:{align:n,behavior:r,...a},viewportBottom:i,viewportTop:o})=>e<o?{...a,align:n??"start",behavior:r}:t>i?{...a,align:n??"end",behavior:r}:null,Ip=ze(([{gap:t,sizes:e,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:a,headerHeight:i,scrollingInProgress:o,scrollTop:s,viewportHeight:l},{scrollToIndex:c}])=>{const d=He();return he(J(d,Fe(e,l,n,i,a,r,s),Fe(t),me(([[_,p,m,E,f,g,S,b],h])=>{const{align:v,behavior:C,calculateViewLocation:R=NN,done:N,...O}=_,I=Ep(_,p,E-1),D=Br(I,p.offsetTree,h)+f+g,M=D+jt(p.sizeTree,I)[1],Y=b+g,K=b+m-S,F=R({itemBottom:M,itemTop:D,locationParams:{align:v,behavior:C,...O},viewportBottom:K,viewportTop:Y});return F?N&&Qt(J(o,Ae($=>!$),Yn(lt(o)?1:2)),N):N&&N(),F}),Ae(_=>_!==null)),c),{scrollIntoView:d}},nt(ln,Nt,Gr,Vn,Rn),{singleton:!0});function Ap(t){return t?t==="smooth"?"smooth":"auto":!1}const ON=(t,e)=>typeof t=="function"?Ap(t(e)):e&&Ap(t),yN=ze(([{listRefresh:t,totalCount:e,fixedItemSize:n,data:r},{atBottomState:a,isAtBottom:i},{scrollToIndex:o},{scrolledToInitialItem:s},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:_},{context:p},{scrollIntoView:m}])=>{const E=re(!1),f=He();let g=null;function S(C){Pe(o,{align:"end",behavior:C,index:"LAST"})}Qe(J(ut(J(Ie(e),Yn(1)),l),Fe(Ie(E),i,s,_),me(([[C,R],N,O,I,D])=>{let M=R&&I,Y="auto";return M&&(Y=ON(N,O||D),M=M&&!!Y),{followOutputBehavior:Y,shouldFollow:M,totalCount:C}}),Ae(({shouldFollow:C})=>C)),({followOutputBehavior:C,totalCount:R})=>{g&&(g(),g=null),lt(n)?requestAnimationFrame(()=>{lt(d)("following output to ",{totalCount:R},xt.DEBUG),S(C)}):g=Qt(t,()=>{lt(d)("following output to ",{totalCount:R},xt.DEBUG),S(C),g=null})});function b(C){const R=Qt(a,N=>{C&&!N.atBottom&&N.notAtBottomBecause==="SIZE_INCREASED"&&!g&&(lt(d)("scrolling to bottom due to increased size",{},xt.DEBUG),S("auto"))});setTimeout(R,100)}Qe(J(ut(Ie(E),e,c),Ae(([C,,R])=>C&&R),sn(({value:C},[,R])=>({refreshed:C===R,value:R}),{refreshed:!1,value:0}),Ae(({refreshed:C})=>C),Fe(E,e)),([,C])=>{lt(s)&&b(C!==!1)}),Qe(f,()=>{b(lt(E)!==!1)}),Qe(ut(Ie(E),a),([C,R])=>{C&&!R.atBottom&&R.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&S("auto")});const h=re(null),v=He();return he(No(J(Ie(r),me(C=>{var R;return(R=C==null?void 0:C.length)!=null?R:0})),J(Ie(e))),v),Qe(J(ut(J(v,Yn(1)),l),Fe(Ie(h),s,_,p),me(([[C,R],N,O,I,D])=>R&&O&&(N==null?void 0:N({context:D,totalCount:C,scrollingInProgress:I}))),Ae(C=>!!C),fn(0)),C=>{g&&(g(),g=null),lt(n)?requestAnimationFrame(()=>{lt(d)("scrolling into view",{}),Pe(m,C)}):g=Qt(t,()=>{lt(d)("scrolling into view",{}),Pe(m,C),g=null})}),{autoscrollToBottom:f,followOutput:E,scrollIntoViewOnChange:h}},nt(ln,Vr,Gr,Yr,Nn,Rn,Nt,yp,Ip)),IN=ze(([{data:t,firstItemIndex:e,gap:n,sizes:r},{initialTopMostItemIndex:a},{initialItemCount:i,listState:o},{didMount:s}])=>(he(J(s,Fe(i),Ae(([,l])=>l!==0),Fe(a,r,e,n,t),me(([[,l],c,d,_,p,m=[]])=>vp(l,c,d,_,p,m))),o),{}),nt(ln,Yr,Vn,Nn),{singleton:!0}),AN=ze(([{didMount:t},{scrollTo:e},{listState:n}])=>{const r=re(0);return Qe(J(t,Fe(r),Ae(([,a])=>a!==0),me(([,a])=>({top:a}))),a=>{Qt(J(n,Yn(1),Ae(i=>i.items.length>1)),()=>{requestAnimationFrame(()=>{Pe(e,a)})})}),{initialScrollTop:r}},nt(Nn,Nt,Vn),{singleton:!0}),xp=ze(([{scrollVelocity:t}])=>{const e=re(!1),n=He(),r=re(!1);return he(J(t,Fe(r,e,n),Ae(([a,i])=>!!i),me(([a,i,o,s])=>{const{enter:l,exit:c}=i;if(o){if(c(a,s))return!1}else if(l(a,s))return!0;return o}),rt()),e),Qe(J(ut(e,t,n),Fe(r)),([[a,i,o],s])=>{a&&s&&s.change&&s.change(i,o)}),{isSeeking:e,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:t}},nt(Vr),{singleton:!0}),Fo=ze(([{scrollContainerState:t,scrollTo:e}])=>{const n=He(),r=He(),a=He(),i=re(!1),o=re(void 0);return he(J(ut(n,r),me(([{scrollHeight:s,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:s,scrollTop:Math.max(0,l-d),viewportHeight:c}))),t),he(J(e,Fe(r),me(([s,{offsetTop:l}])=>({...s,top:s.top+l}))),a),{customScrollParent:o,useWindowScroll:i,windowScrollContainerState:n,windowScrollTo:a,windowViewportRect:r}},nt(Nt)),xN=ze(([{sizeRanges:t,sizes:e},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:a},{didMount:i},{useWindowScroll:o,windowScrollContainerState:s,windowViewportRect:l}])=>{const c=He(),d=re(void 0),_=re(null),p=re(null);return he(s,_),he(l,p),Qe(J(c,Fe(e,r,o,_,p,n)),([m,E,f,g,S,b,h])=>{const v=pN(E.sizeTree);g&&S!==null&&b!==null&&(f=S.scrollTop-b.offsetTop),f-=h,m({ranges:v,scrollTop:f})}),he(J(d,Ae(Ro),me(DN)),a),he(J(i,Fe(d),Ae(([,m])=>m!==void 0),rt(),me(([,m])=>m.ranges)),t),{getState:c,restoreStateFrom:d}},nt(ln,Nt,Yr,Nn,Fo));function DN(t){return{align:"start",index:0,offset:t.scrollTop}}const wN=ze(([{topItemsIndexes:t}])=>{const e=re(0);return he(J(e,Ae(n=>n>=0),me(n=>Array.from({length:n}).map((r,a)=>a))),t),{topItemCount:e}},nt(Vn));function Dp(t){let e=!1,n;return()=>(e||(e=!0,n=t()),n)}const MN=Dp(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),LN=ze(([{deviation:t,scrollBy:e,scrollingInProgress:n,scrollTop:r},{isAtBottom:a,isScrolling:i,lastJumpDueToItemResize:o,scrollDirection:s},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:_,sizes:p},{log:m},{recalcInProgress:E}])=>{const f=Lt(J(l,Fe(o),sn(([,S,b,h],[{bottom:v,items:C,offsetBottom:R,totalCount:N},O])=>{const I=v+R;let D=0;return b===N&&S.length>0&&C.length>0&&(C[0].originalIndex===0&&S[0].originalIndex===0||(D=I-h,D!==0&&(D+=O))),[D,C,N,I]},[0,[],0,0]),Ae(([S])=>S!==0),Fe(r,s,n,a,m,E),Ae(([,S,b,h,,,v])=>!v&&!h&&S!==0&&b===Hr),me(([[S],,,,,b])=>(b("Upward scrolling compensation",{amount:S},xt.DEBUG),S))));function g(S){S>0?(Pe(e,{behavior:"auto",top:-S}),Pe(t,0)):(Pe(t,0),Pe(e,{behavior:"auto",top:-S}))}return Qe(J(f,Fe(t,i)),([S,b,h])=>{h&&MN()?Pe(t,b-S):g(-S)}),Qe(J(ut(Tt(i,!1),t,E),Ae(([S,b,h])=>!S&&!h&&b!==0),me(([S,b])=>b),fn(1)),g),he(J(_,me(S=>({top:-S}))),e),Qe(J(c,Fe(p,d),me(([S,{groupIndices:b,lastSize:h,sizeTree:v},C])=>{function R(N){return N*(h+C)}if(b.length===0)return R(S);{let N=0;const O=Ur(v,0);let I=0,D=0;for(;I<S;){I++,N+=O;let M=b.length===D+1?1/0:b[D+1]-b[D]-1;I+M>S&&(N-=O,M=S-I+1),I+=M,N+=R(M),D++}return N}})),S=>{Pe(t,S),requestAnimationFrame(()=>{Pe(e,{top:S}),requestAnimationFrame(()=>{Pe(t,0),Pe(E,!1)})})}),{deviation:t}},nt(Nt,Vr,Vn,ln,Rn,Do)),PN=ze(([t,e,n,r,a,i,o,s,l,c,d])=>({...t,...e,...n,...r,...a,...i,...o,...s,...l,...c,...d}),nt(ko,IN,Nn,xp,Op,AN,vN,Fo,Ip,Rn,yp)),wp=ze(([{data:t,defaultItemSize:e,firstItemIndex:n,fixedItemSize:r,gap:a,groupIndices:i,itemSize:o,sizeRanges:s,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:_},{initialItemFinalLocationReached:p,initialTopMostItemIndex:m,scrolledToInitialItem:E},f,g,S,{listState:b,topItemsIndexes:h,...v},{scrollToIndex:C},R,{topItemCount:N},{groupCounts:O},I])=>(he(v.rangeChanged,I.scrollSeekRangeChanged),he(J(I.windowViewportRect,me(D=>D.visibleHeight)),f.viewportHeight),{data:t,defaultItemHeight:e,firstItemIndex:n,fixedItemHeight:r,gap:a,groupCounts:O,initialItemFinalLocationReached:p,initialTopMostItemIndex:m,scrolledToInitialItem:E,sizeRanges:s,topItemCount:N,topItemsIndexes:h,totalCount:d,...S,groupIndices:i,itemSize:o,listState:b,scrollToIndex:C,statefulTotalCount:c,trackItemSizes:_,...v,...I,...f,sizes:l,...g}),nt(ln,Yr,Nt,xN,yN,Vn,Gr,LN,wN,Sp,PN));function kN(t,e){const n={},r={};let a=0;const i=t.length;for(;a<i;)r[t[a]]=1,a+=1;for(const o in e)Object.hasOwn(r,o)||(n[o]=e[o]);return n}const Ga=typeof document<"u"?y.useLayoutEffect:y.useEffect;function Mp(t,e,n){const r=Object.keys(e.required||{}),a=Object.keys(e.optional||{}),i=Object.keys(e.methods||{}),o=Object.keys(e.events||{}),s=y.createContext({});function l(g,S){g.propsReady&&Pe(g.propsReady,!1);for(const b of r){const h=g[e.required[b]];Pe(h,S[b])}for(const b of a)if(b in S){const h=g[e.optional[b]];Pe(h,S[b])}g.propsReady&&Pe(g.propsReady,!0)}function c(g){return i.reduce((S,b)=>(S[b]=h=>{const v=g[e.methods[b]];Pe(v,h)},S),{})}function d(g){return o.reduce((S,b)=>(S[b]=Zv(g[e.events[b]]),S),{})}const _=y.forwardRef((g,S)=>{const{children:b,...h}=g,[v]=y.useState(()=>wa(eN(t),N=>{l(N,h)})),[C]=y.useState(np(d,v));Ga(()=>{for(const N of o)N in h&&Qe(C[N],h[N]);return()=>{Object.values(C).map(vo)}},[h,C,v]),Ga(()=>{l(v,h)}),y.useImperativeHandle(S,ep(c(v)));const R=n;return u.jsx(s.Provider,{value:v,children:n?u.jsx(R,{...kN([...r,...a,...o],h),children:b}):b})}),p=g=>{const S=y.useContext(s);return y.useCallback(b=>{Pe(S[g],b)},[S,g])},m=g=>{const S=y.useContext(s)[g],b=y.useCallback(h=>Qe(S,h),[S]);return y.useSyncExternalStore(b,()=>lt(S),()=>lt(S))},E=g=>{const S=y.useContext(s)[g],[b,h]=y.useState(np(lt,S));return Ga(()=>Qe(S,v=>{v!==b&&h(ep(v))}),[S,b]),b},f=y.version.startsWith("18")?m:E;return{Component:_,useEmitter:(g,S)=>{const b=y.useContext(s)[g];Ga(()=>Qe(b,S),[S,b])},useEmitterValue:f,usePublisher:p}}const Lp=y.createContext(void 0),Pp=y.createContext(void 0),kp=typeof document<"u"?y.useLayoutEffect:y.useEffect;function Bo(t){return"self"in t}function UN(t){return"body"in t}function Up(t,e,n,r=cr,a,i){const o=y.useRef(null),s=y.useRef(null),l=y.useRef(null),c=y.useCallback(p=>{let m,E,f;const g=p.target;if(UN(g)||Bo(g)){const b=Bo(g)?g:g.defaultView;f=i?b.scrollX:b.scrollY,m=i?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,E=i?b.innerWidth:b.innerHeight}else f=i?g.scrollLeft:g.scrollTop,m=i?g.scrollWidth:g.scrollHeight,E=i?g.offsetWidth:g.offsetHeight;const S=()=>{t({scrollHeight:m,scrollTop:Math.max(f,0),viewportHeight:E})};p.suppressFlushSync?S():ro.flushSync(S),s.current!==null&&(f===s.current||f<=0||f===m-E)&&(s.current=null,e(!0),l.current&&(clearTimeout(l.current),l.current=null))},[t,e,i]);y.useEffect(()=>{const p=a||o.current;return r(a||o.current),c({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",c,{passive:!0}),()=>{r(null),p.removeEventListener("scroll",c)}},[o,c,n,r,a]);function d(p){const m=o.current;if(!m||(i?"offsetWidth"in m&&m.offsetWidth===0:"offsetHeight"in m&&m.offsetHeight===0))return;const E=p.behavior==="smooth";let f,g,S;Bo(m)?(g=Math.max(vn(m.document.documentElement,i?"width":"height"),i?m.document.documentElement.scrollWidth:m.document.documentElement.scrollHeight),f=i?m.innerWidth:m.innerHeight,S=i?window.scrollX:window.scrollY):(g=m[i?"scrollWidth":"scrollHeight"],f=vn(m,i?"width":"height"),S=m[i?"scrollLeft":"scrollTop"]);const b=g-f;if(p.top=Math.ceil(Math.max(Math.min(b,p.top),0)),Tp(f,g)||p.top===S){t({scrollHeight:g,scrollTop:S,viewportHeight:f}),E&&e(!0);return}E?(s.current=p.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,s.current=null,e(!0)},1e3)):s.current=null,i&&(p={behavior:p.behavior,left:p.top}),m.scrollTo(p)}function _(p){i&&(p={behavior:p.behavior,left:p.top}),o.current.scrollBy(p)}return{scrollByCallback:_,scrollerRef:o,scrollToCallback:d}}const Go="-webkit-sticky",Fp="sticky",Yo=Dp(()=>{if(typeof document>"u")return Fp;const t=document.createElement("div");return t.style.position=Go,t.style.position===Go?Go:Fp});function Ho(t){return t}const FN=ze(()=>{const t=re(s=>`Item ${s}`),e=re(s=>`Group ${s}`),n=re({}),r=re(Ho),a=re("div"),i=re(cr),o=(s,l=null)=>Tt(J(n,me(c=>c[s]),rt()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:o("EmptyPlaceholder"),FooterComponent:o("Footer"),GroupComponent:o("Group","div"),groupContent:e,HeaderComponent:o("Header"),HeaderFooterTag:a,ItemComponent:o("Item","div"),itemContent:t,ListComponent:o("List","div"),ScrollerComponent:o("Scroller","div"),scrollerRef:i,ScrollSeekPlaceholder:o("ScrollSeekPlaceholder"),TopItemListComponent:o("TopItemList")}}),BN=ze(([t,e])=>({...t,...e}),nt(wp,FN)),GN=({height:t})=>u.jsx("div",{style:{height:t}}),YN={overflowAnchor:"none",position:Yo(),zIndex:1},Bp={overflowAnchor:"none"},HN={...Bp,display:"inline-block",height:"100%"},Gp=y.memo(function({showTopList:t=!1}){const e=we("listState"),n=Ht("sizeRanges"),r=we("useWindowScroll"),a=we("customScrollParent"),i=Ht("windowScrollContainerState"),o=Ht("scrollContainerState"),s=a||r?i:o,l=we("itemContent"),c=we("context"),d=we("groupContent"),_=we("trackItemSizes"),p=we("itemSize"),m=we("log"),E=Ht("gap"),f=we("horizontalDirection"),{callbackRef:g}=rN(n,p,_,t?cr:s,m,E,a,f,we("skipAnimationFrameInResizeObserver")),[S,b]=y.useState(0);qo("deviation",F=>{S!==F&&b(F)});const h=we("EmptyPlaceholder"),v=we("ScrollSeekPlaceholder")||GN,C=we("ListComponent"),R=we("ItemComponent"),N=we("GroupComponent"),O=we("computeItemKey"),I=we("isSeeking"),D=we("groupIndices").length>0,M=we("alignToBottom"),Y=we("initialItemFinalLocationReached"),K=t?{}:{boxSizing:"border-box",...f?{display:"inline-block",height:"100%",marginLeft:S!==0?S:M?"auto":0,paddingLeft:e.offsetTop,paddingRight:e.offsetBottom,whiteSpace:"nowrap"}:{marginTop:S!==0?S:M?"auto":0,paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},...Y?{}:{visibility:"hidden"}};return!t&&e.totalCount===0&&h?u.jsx(h,{...ht(h,c)}):u.jsx(C,{...ht(C,c),"data-testid":t?"virtuoso-top-item-list":"virtuoso-item-list",ref:g,style:K,children:(t?e.topItems:e.items).map(F=>{const $=F.originalIndex,x=O($+e.firstItemIndex,F.data,c);return I?y.createElement(v,{...ht(v,c),height:F.size,index:F.index,key:x,type:F.type||"item",...F.type==="group"?{}:{groupIndex:F.groupIndex}}):F.type==="group"?y.createElement(N,{...ht(N,c),"data-index":$,"data-item-index":F.index,"data-known-size":F.size,key:x,style:YN},d(F.index,c)):y.createElement(R,{...ht(R,c),...$N(R,F.data),"data-index":$,"data-item-group-index":F.groupIndex,"data-item-index":F.index,"data-known-size":F.size,key:x,style:f?HN:Bp},D?l(F.index,F.groupIndex,F.data,c):l(F.index,F.data,c))})})}),qN={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},VN={outline:"none",overflowX:"auto",position:"relative"},Ya=t=>({height:"100%",position:"absolute",top:0,width:"100%",...t?{display:"flex",flexDirection:"column"}:{}}),zN={position:Yo(),top:0,width:"100%",zIndex:1};function ht(t,e){if(typeof t!="string")return{context:e}}function $N(t,e){return{item:typeof t=="string"?void 0:e}}const WN=y.memo(function(){const t=we("HeaderComponent"),e=Ht("headerHeight"),n=we("HeaderFooterTag"),r=Hn(y.useMemo(()=>i=>{e(vn(i,"height"))},[e]),!0,we("skipAnimationFrameInResizeObserver")),a=we("context");return t?u.jsx(n,{ref:r,children:u.jsx(t,{...ht(t,a)})}):null}),KN=y.memo(function(){const t=we("FooterComponent"),e=Ht("footerHeight"),n=we("HeaderFooterTag"),r=Hn(y.useMemo(()=>i=>{e(vn(i,"height"))},[e]),!0,we("skipAnimationFrameInResizeObserver")),a=we("context");return t?u.jsx(n,{ref:r,children:u.jsx(t,{...ht(t,a)})}):null});function Yp({useEmitter:t,useEmitterValue:e,usePublisher:n}){return y.memo(function({children:r,style:a,context:i,...o}){const s=n("scrollContainerState"),l=e("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=e("scrollerRef"),_=e("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:m,scrollToCallback:E}=Up(s,c,l,d,void 0,_);return t("scrollTo",E),t("scrollBy",p),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:m,style:{..._?VN:qN,...a},tabIndex:0,...o,...ht(l,i),children:r})})}function Hp({useEmitter:t,useEmitterValue:e,usePublisher:n}){return y.memo(function({children:r,style:a,context:i,...o}){const s=n("windowScrollContainerState"),l=e("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=e("totalListHeight"),_=e("deviation"),p=e("customScrollParent"),m=y.useRef(null),E=e("scrollerRef"),{scrollByCallback:f,scrollerRef:g,scrollToCallback:S}=Up(s,c,l,E,p);return kp(()=>{var b;return g.current=p||((b=m.current)==null?void 0:b.ownerDocument.defaultView),()=>{g.current=null}},[g,p]),t("windowScrollTo",S),t("scrollBy",f),u.jsx(l,{ref:m,"data-virtuoso-scroller":!0,style:{position:"relative",...a,...d!==0?{height:d+_}:{}},...o,...ht(l,i),children:r})})}const QN=({children:t})=>{const e=y.useContext(Lp),n=Ht("viewportHeight"),r=Ht("fixedItemHeight"),a=we("alignToBottom"),i=we("horizontalDirection"),o=y.useMemo(()=>tp(n,l=>vn(l,i?"width":"height")),[n,i]),s=Hn(o,!0,we("skipAnimationFrameInResizeObserver"));return y.useEffect(()=>{e&&(n(e.viewportHeight),r(e.itemHeight))},[e,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:s,style:Ya(a),children:t})},jN=({children:t})=>{const e=y.useContext(Lp),n=Ht("windowViewportRect"),r=Ht("fixedItemHeight"),a=we("customScrollParent"),i=op(n,a,we("skipAnimationFrameInResizeObserver")),o=we("alignToBottom");return y.useEffect(()=>{e&&(r(e.itemHeight),n({offsetTop:0,visibleHeight:e.viewportHeight,visibleWidth:100}))},[e,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:i,style:Ya(o),children:t})},XN=({children:t})=>{const e=we("TopItemListComponent")||"div",n=we("headerHeight"),r={...zN,marginTop:`${n}px`},a=we("context");return u.jsx(e,{style:r,...ht(e,a),children:t})},ZN=y.memo(function(t){const e=we("useWindowScroll"),n=we("topItemsIndexes").length>0,r=we("customScrollParent"),a=we("context");return u.jsxs(r||e?tO:eO,{...t,context:a,children:[n&&u.jsx(XN,{children:u.jsx(Gp,{showTopList:!0})}),u.jsxs(r||e?jN:QN,{children:[u.jsx(WN,{}),u.jsx(Gp,{}),u.jsx(KN,{})]})]})}),{Component:JN,useEmitter:qo,useEmitterValue:we,usePublisher:Ht}=Mp(BN,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},ZN),eO=Yp({useEmitter:qo,useEmitterValue:we,usePublisher:Ht}),tO=Hp({useEmitter:qo,useEmitterValue:we,usePublisher:Ht}),nO=JN;nt(wp,ze(()=>{const t=re(c=>u.jsxs("td",{children:["Item $",c]})),e=re(null),n=re(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=re(null),a=re(null),i=re({}),o=re(Ho),s=re(cr),l=(c,d=null)=>Tt(J(i,me(_=>_[c]),rt()),d);return{components:i,computeItemKey:o,context:e,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:a,fixedHeaderContent:r,itemContent:t,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder"),TableBodyComponent:l("TableBody","tbody"),TableComponent:l("Table","table"),TableFooterComponent:l("TableFoot","tfoot"),TableHeadComponent:l("TableHead","thead"),TableRowComponent:l("TableRow","tr"),GroupComponent:l("Group","tr")}})),Yo();const qp={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},rO={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Vp,floor:Ha,max:zr,min:Vo,round:zp}=Math;function $p(t,e,n){return Array.from({length:e-t+1}).map((r,a)=>({data:n===null?null:n[a+t],index:a+t}))}function aO(t){return{...rO,items:t}}function qa(t,e){return t&&t.width===e.width&&t.height===e.height}function iO(t,e){return t&&t.column===e.column&&t.row===e.row}const oO=ze(([{increaseViewportBy:t,listBoundary:e,overscan:n,visibleRange:r},{footerHeight:a,headerHeight:i,scrollBy:o,scrollContainerState:s,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:_},p,m,{didMount:E,propsReady:f},{customScrollParent:g,useWindowScroll:S,windowScrollContainerState:b,windowScrollTo:h,windowViewportRect:v},C])=>{const R=re(0),N=re(0),O=re(qp),I=re({height:0,width:0}),D=re({height:0,width:0}),M=He(),Y=He(),K=re(0),F=re(null),$=re({column:0,row:0}),x=He(),B=He(),L=re(!1),U=re(0),z=re(!0),W=re(!1),ne=re(!1);Qe(J(E,Fe(U),Ae(([P,V])=>!!V)),()=>{Pe(z,!1)}),Qe(J(ut(E,z,D,I,U,W),Ae(([P,V,Z,ie,,oe])=>P&&!V&&Z.height!==0&&ie.height!==0&&!oe)),([,,,,P])=>{Pe(W,!0),Lo(1,()=>{Pe(M,P)}),Qt(J(c),()=>{Pe(e,[0,0]),Pe(z,!0)})}),he(J(B,Ae(P=>P!=null&&P.scrollTop>0),on(0)),N),Qe(J(E,Fe(B),Ae(([,P])=>P!=null)),([,P])=>{P&&(Pe(I,P.viewport),Pe(D,P.item),Pe($,P.gap),P.scrollTop>0&&(Pe(L,!0),Qt(J(c,Yn(1)),V=>{Pe(L,!1)}),Pe(l,{top:P.scrollTop})))}),he(J(I,me(({height:P})=>P)),_),he(J(ut(Ie(I,qa),Ie(D,qa),Ie($,(P,V)=>P&&P.column===V.column&&P.row===V.row),Ie(c)),me(([P,V,Z,ie])=>({gap:Z,item:V,scrollTop:ie,viewport:P}))),x),he(J(ut(Ie(R),r,Ie($,iO),Ie(D,qa),Ie(I,qa),Ie(F),Ie(N),Ie(L),Ie(z),Ie(U)),Ae(([,,,,,,,P])=>!P),me(([P,[V,Z],ie,oe,Ne,Ue,Oe,,de,Me])=>{const{column:ae,row:fe}=ie,{height:Te,width:Se}=oe,{width:tt}=Ne;if(Oe===0&&(P===0||tt===0))return qp;if(Se===0){const Ce=Po(Me,P),je=Ce+Math.max(Oe-1,0);return aO($p(Ce,je,Ue))}const We=Wp(tt,Se,ae);let ct,et;de?V===0&&Z===0&&Oe>0?(ct=0,et=Oe-1):(ct=We*Ha((V+fe)/(Te+fe)),et=We*Vp((Z+fe)/(Te+fe))-1,et=Vo(P-1,zr(et,We-1)),ct=Vo(et,zr(0,ct))):(ct=0,et=-1);const te=$p(ct,et,Ue),{bottom:k,top:j}=Kp(Ne,ie,oe,te),be=Vp(P/We),ke=be*Te+(be-1)*fe-k;return{bottom:k,itemHeight:Te,items:te,itemWidth:Se,offsetBottom:ke,offsetTop:j,top:j}})),O),he(J(F,Ae(P=>P!==null),me(P=>P.length)),R),he(J(ut(I,D,O,$),Ae(([P,V,{items:Z}])=>Z.length>0&&V.height!==0&&P.height!==0),me(([P,V,{items:Z},ie])=>{const{bottom:oe,top:Ne}=Kp(P,ie,V,Z);return[Ne,oe]}),rt(Fr)),e);const q=re(!1);he(J(c,Fe(q),me(([P,V])=>V||P!==0)),q);const X=Lt(J(ut(O,R),Ae(([{items:P}])=>P.length>0),Fe(q),Ae(([[P,V],Z])=>{const ie=P.items[P.items.length-1].index===V-1;return(Z||P.bottom>0&&P.itemHeight>0&&P.offsetBottom===0&&P.items.length===V)&&ie}),me(([[,P]])=>P-1),rt())),se=Lt(J(Ie(O),Ae(({items:P})=>P.length>0&&P[0].index===0),on(0),rt())),ce=Lt(J(Ie(O),Fe(L),Ae(([{items:P},V])=>P.length>0&&!V),me(([{items:P}])=>({endIndex:P[P.length-1].index,startIndex:P[0].index})),rt(pp),fn(0)));he(ce,m.scrollSeekRangeChanged),he(J(M,Fe(I,D,R,$),me(([P,V,Z,ie,oe])=>{const Ne=bp(P),{align:Ue,behavior:Oe,offset:de}=Ne;let Me=Ne.index;Me==="LAST"&&(Me=ie-1),Me=zr(0,Me,Vo(ie-1,Me));let ae=zo(V,oe,Z,Me);return Ue==="end"?ae=zp(ae-V.height+Z.height):Ue==="center"&&(ae=zp(ae-V.height/2+Z.height/2)),de&&(ae+=de),{behavior:Oe,top:ae}})),l);const H=Tt(J(O,me(P=>P.offsetBottom+P.bottom)),0);return he(J(v,me(P=>({height:P.visibleHeight,width:P.visibleWidth}))),I),{customScrollParent:g,data:F,deviation:K,footerHeight:a,gap:$,headerHeight:i,increaseViewportBy:t,initialItemCount:N,itemDimensions:D,overscan:n,restoreStateFrom:B,scrollBy:o,scrollContainerState:s,scrollHeight:Y,scrollTo:l,scrollToIndex:M,scrollTop:c,smoothScrollTargetReached:d,totalCount:R,useWindowScroll:S,viewportDimensions:I,windowScrollContainerState:b,windowScrollTo:h,windowViewportRect:v,...m,gridState:O,horizontalDirection:ne,initialTopMostItemIndex:U,totalListHeight:H,...p,endReached:X,propsReady:f,rangeChanged:ce,startReached:se,stateChanged:x,stateRestoreInProgress:L,...C}},nt(ko,Nt,Vr,xp,Nn,Fo,Rn));function Wp(t,e,n){return zr(1,Ha((t+n)/(Ha(e)+n)))}function Kp(t,e,n,r){const{height:a}=n;if(a===void 0||r.length===0)return{bottom:0,top:0};const i=zo(t,e,n,r[0].index);return{bottom:zo(t,e,n,r[r.length-1].index)+a,top:i}}function zo(t,e,n,r){const a=Wp(t.width,n.width,e.column),i=Ha(r/a),o=i*n.height+zr(0,i-1)*e.row;return o>0?o+e.row:o}const sO=ze(()=>{const t=re(_=>`Item ${_}`),e=re({}),n=re(null),r=re("virtuoso-grid-item"),a=re("virtuoso-grid-list"),i=re(Ho),o=re("div"),s=re(cr),l=(_,p=null)=>Tt(J(e,me(m=>m[_]),rt()),p),c=re(!1),d=re(!1);return he(Ie(d),c),{components:e,computeItemKey:i,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:o,itemClassName:r,ItemComponent:l("Item","div"),itemContent:t,listClassName:a,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),lO=ze(([t,e])=>({...t,...e}),nt(oO,sO)),cO=y.memo(function(){const t=at("gridState"),e=at("listClassName"),n=at("itemClassName"),r=at("itemContent"),a=at("computeItemKey"),i=at("isSeeking"),o=qt("scrollHeight"),s=at("ItemComponent"),l=at("ListComponent"),c=at("ScrollSeekPlaceholder"),d=at("context"),_=qt("itemDimensions"),p=qt("gap"),m=at("log"),E=at("stateRestoreInProgress"),f=qt("reportReadyState"),g=Hn(y.useMemo(()=>S=>{const b=S.parentElement.parentElement.scrollHeight;o(b);const h=S.firstChild;if(h){const{height:v,width:C}=h.getBoundingClientRect();_({height:v,width:C})}p({column:jp("column-gap",getComputedStyle(S).columnGap,m),row:jp("row-gap",getComputedStyle(S).rowGap,m)})},[o,_,p,m]),!0,!1);return kp(()=>{t.itemHeight>0&&t.itemWidth>0&&f(!0)},[t]),E?null:u.jsx(l,{className:e,ref:g,...ht(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},children:t.items.map(S=>{const b=a(S.index,S.data,d);return i?u.jsx(c,{...ht(c,d),height:t.itemHeight,index:S.index,width:t.itemWidth},b):y.createElement(s,{...ht(s,d),className:n,"data-index":S.index,key:b},r(S.index,S.data,d))})})}),dO=y.memo(function(){const t=at("HeaderComponent"),e=qt("headerHeight"),n=at("headerFooterTag"),r=Hn(y.useMemo(()=>i=>{e(vn(i,"height"))},[e]),!0,!1),a=at("context");return t?u.jsx(n,{ref:r,children:u.jsx(t,{...ht(t,a)})}):null}),uO=y.memo(function(){const t=at("FooterComponent"),e=qt("footerHeight"),n=at("headerFooterTag"),r=Hn(y.useMemo(()=>i=>{e(vn(i,"height"))},[e]),!0,!1),a=at("context");return t?u.jsx(n,{ref:r,children:u.jsx(t,{...ht(t,a)})}):null}),_O=({children:t})=>{const e=y.useContext(Pp),n=qt("itemDimensions"),r=qt("viewportDimensions"),a=Hn(y.useMemo(()=>i=>{r(i.getBoundingClientRect())},[r]),!0,!1);return y.useEffect(()=>{e&&(r({height:e.viewportHeight,width:e.viewportWidth}),n({height:e.itemHeight,width:e.itemWidth}))},[e,r,n]),u.jsx("div",{ref:a,style:Ya(!1),children:t})},pO=({children:t})=>{const e=y.useContext(Pp),n=qt("windowViewportRect"),r=qt("itemDimensions"),a=at("customScrollParent"),i=op(n,a,!1);return y.useEffect(()=>{e&&(r({height:e.itemHeight,width:e.itemWidth}),n({offsetTop:0,visibleHeight:e.viewportHeight,visibleWidth:e.viewportWidth}))},[e,n,r]),u.jsx("div",{ref:i,style:Ya(!1),children:t})},mO=y.memo(function({...t}){const e=at("useWindowScroll"),n=at("customScrollParent"),r=n||e?EO:gO,a=n||e?pO:_O,i=at("context");return u.jsx(r,{...t,...ht(r,i),children:u.jsxs(a,{children:[u.jsx(dO,{}),u.jsx(cO,{}),u.jsx(uO,{})]})})}),{useEmitter:Qp,useEmitterValue:at,usePublisher:qt}=Mp(lO,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},mO),gO=Yp({useEmitter:Qp,useEmitterValue:at,usePublisher:qt}),EO=Hp({useEmitter:Qp,useEmitterValue:at,usePublisher:qt});function jp(t,e,n){return e!=="normal"&&!(e!=null&&e.endsWith("px"))&&n(`${t} was not resolved to pixel value correctly`,e,xt.WARN),e==="normal"?0:parseInt(e??"0",10)}const fO=yr.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Xp({className:t,variant:e,...n}){return u.jsx("div",{className:Q(fO({variant:e}),t),...n})}function ue(t,e,{checkForDefaultPrevented:n=!0}={}){return function(a){if(t==null||t(a),n===!1||!a.defaultPrevented)return e==null?void 0:e(a)}}function SO(t,e){const n=T.createContext(e),r=i=>{const{children:o,...s}=i,l=T.useMemo(()=>s,Object.values(s));return u.jsx(n.Provider,{value:l,children:o})};r.displayName=t+"Provider";function a(i){const o=T.useContext(n);if(o)return o;if(e!==void 0)return e;throw new Error(`\`${i}\` must be used within \`${t}\``)}return[r,a]}function Xt(t,e=[]){let n=[];function r(i,o){const s=T.createContext(o),l=n.length;n=[...n,o];const c=_=>{var S;const{scope:p,children:m,...E}=_,f=((S=p==null?void 0:p[t])==null?void 0:S[l])||s,g=T.useMemo(()=>E,Object.values(E));return u.jsx(f.Provider,{value:g,children:m})};c.displayName=i+"Provider";function d(_,p){var f;const m=((f=p==null?void 0:p[t])==null?void 0:f[l])||s,E=T.useContext(m);if(E)return E;if(o!==void 0)return o;throw new Error(`\`${_}\` must be used within \`${i}\``)}return[c,d]}const a=()=>{const i=n.map(o=>T.createContext(o));return function(s){const l=(s==null?void 0:s[t])||i;return T.useMemo(()=>({[`__scope${t}`]:{...s,[t]:l}}),[s,l])}};return a.scopeName=t,[r,bO(a,...e)]}function bO(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const o=r.reduce((s,{useScope:l,scopeName:c})=>{const _=l(i)[`__scope${c}`];return{...s,..._}},{});return T.useMemo(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return n.scopeName=e.scopeName,n}var gt=globalThis!=null&&globalThis.document?T.useLayoutEffect:()=>{},TO=T[" useInsertionEffect ".trim().toString()]||gt;function On({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){const[a,i,o]=hO({defaultProp:e,onChange:n}),s=t!==void 0,l=s?t:a;{const d=T.useRef(t!==void 0);T.useEffect(()=>{const _=d.current;_!==s&&console.warn(`${r} is changing from ${_?"controlled":"uncontrolled"} to ${s?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=s},[s,r])}const c=T.useCallback(d=>{var _;if(s){const p=CO(d)?d(t):d;p!==t&&((_=o.current)==null||_.call(o,p))}else i(d)},[s,t,i,o]);return[l,c]}function hO({defaultProp:t,onChange:e}){const[n,r]=T.useState(t),a=T.useRef(n),i=T.useRef(e);return TO(()=>{i.current=e},[e]),T.useEffect(()=>{var o;a.current!==n&&((o=i.current)==null||o.call(i,n),a.current=n)},[n,a]),[n,r,i]}function CO(t){return typeof t=="function"}function Zp(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function $o(...t){return e=>{let n=!1;const r=t.map(a=>{const i=Zp(a,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a<r.length;a++){const i=r[a];typeof i=="function"?i():Zp(t[a],null)}}}}function Be(...t){return T.useCallback($o(...t),t)}var RO=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],xe=RO.reduce((t,e)=>{const n=Mt.createSlot(`Primitive.${e}`),r=T.forwardRef((a,i)=>{const{asChild:o,...s}=a,l=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...s,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function Jp(t,e){t&&fa.flushSync(()=>t.dispatchEvent(e))}function vO(t,e){return T.useReducer((n,r)=>e[n][r]??n,t)}var Dt=t=>{const{present:e,children:n}=t,r=NO(e),a=typeof n=="function"?n({present:r.isPresent}):T.Children.only(n),i=Be(r.ref,OO(a));return typeof n=="function"||r.isPresent?T.cloneElement(a,{ref:i}):null};Dt.displayName="Presence";function NO(t){const[e,n]=T.useState(),r=T.useRef(null),a=T.useRef(t),i=T.useRef("none"),o=t?"mounted":"unmounted",[s,l]=vO(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return T.useEffect(()=>{const c=Va(r.current);i.current=s==="mounted"?c:"none"},[s]),gt(()=>{const c=r.current,d=a.current;if(d!==t){const p=i.current,m=Va(c);t?l("MOUNT"):m==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&p!==m?"ANIMATION_OUT":"UNMOUNT"),a.current=t}},[t,l]),gt(()=>{if(e){let c;const d=e.ownerDocument.defaultView??window,_=m=>{const f=Va(r.current).includes(CSS.escape(m.animationName));if(m.target===e&&f&&(l("ANIMATION_END"),!a.current)){const g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=d.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},p=m=>{m.target===e&&(i.current=Va(r.current))};return e.addEventListener("animationstart",p),e.addEventListener("animationcancel",_),e.addEventListener("animationend",_),()=>{d.clearTimeout(c),e.removeEventListener("animationstart",p),e.removeEventListener("animationcancel",_),e.removeEventListener("animationend",_)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:T.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Va(t){return(t==null?void 0:t.animationName)||"none"}function OO(t){var r,a;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(a=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:a.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var yO=T[" useId ".trim().toString()]||(()=>{}),IO=0;function Zt(t){const[e,n]=T.useState(yO());return gt(()=>{n(r=>r??String(IO++))},[t]),t||(e?`radix-${e}`:"")}var za="Collapsible",[AO,J0]=Xt(za),[xO,Wo]=AO(za),em=T.forwardRef((t,e)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:o,...s}=t,[l,c]=On({prop:r,defaultProp:a??!1,onChange:o,caller:za});return u.jsx(xO,{scope:n,disabled:i,contentId:Zt(),open:l,onOpenToggle:T.useCallback(()=>c(d=>!d),[c]),children:u.jsx(xe.div,{"data-state":Qo(l),"data-disabled":i?"":void 0,...s,ref:e})})});em.displayName=za;var tm="CollapsibleTrigger",nm=T.forwardRef((t,e)=>{const{__scopeCollapsible:n,...r}=t,a=Wo(tm,n);return u.jsx(xe.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":Qo(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:e,onClick:ue(t.onClick,a.onOpenToggle)})});nm.displayName=tm;var Ko="CollapsibleContent",DO=T.forwardRef((t,e)=>{const{forceMount:n,...r}=t,a=Wo(Ko,t.__scopeCollapsible);return u.jsx(Dt,{present:n||a.open,children:({present:i})=>u.jsx(wO,{...r,ref:e,present:i})})});DO.displayName=Ko;var wO=T.forwardRef((t,e)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=t,o=Wo(Ko,n),[s,l]=T.useState(r),c=T.useRef(null),d=Be(e,c),_=T.useRef(0),p=_.current,m=T.useRef(0),E=m.current,f=o.open||s,g=T.useRef(f),S=T.useRef(void 0);return T.useEffect(()=>{const b=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(b)},[]),gt(()=>{const b=c.current;if(b){S.current=S.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const h=b.getBoundingClientRect();_.current=h.height,m.current=h.width,g.current||(b.style.transitionDuration=S.current.transitionDuration,b.style.animationName=S.current.animationName),l(r)}},[o.open,r]),u.jsx(xe.div,{"data-state":Qo(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!f,...i,ref:d,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":E?`${E}px`:void 0,...t.style},children:f&&a})});function Qo(t){return t?"open":"closed"}var MO=em;const rm=MO,am=nm,im=new URL("data:video/mp2t;base64,Ly8vIDxyZWZlcmVuY2UgbGliPSJ3ZWJ3b3JrZXIiIC8+CmltcG9ydCBtYXJrZWQgZnJvbSAnbWFya2VkJzsKCmRlY2xhcmUgY29uc3Qgc2VsZjogRGVkaWNhdGVkV29ya2VyR2xvYmFsU2NvcGU7CmNvbnN0IHNjb3BlOiBEZWRpY2F0ZWRXb3JrZXJHbG9iYWxTY29wZSA9IHNlbGY7CgpzY29wZS5wb3N0TWVzc2FnZT8uKHsgd29ya2VyX3JlYWR5OiB0cnVlIH0pOwoKc2NvcGUuYWRkRXZlbnRMaXN0ZW5lcignbWVzc2FnZScsIChldmVudDogTWVzc2FnZUV2ZW50KSA9PiB7CiAgY29uc3QgcGF5bG9hZDogYW55ID0gZXZlbnQ/LmRhdGEgPz8ge307CiAgY29uc3QgaWQgPSB0eXBlb2YgcGF5bG9hZC5pZCA9PT0gJ3N0cmluZycgPyBwYXlsb2FkLmlkIDogdW5kZWZpbmVkOwogIGNvbnN0IGtleSA9IHR5cGVvZiBwYXlsb2FkLmtleSA9PT0gJ3N0cmluZycgPyBwYXlsb2FkLmtleSA6IHVuZGVmaW5lZDsKICBjb25zdCBzb3VyY2UgPSB0eXBlb2YgcGF5bG9hZC5zb3VyY2UgPT09ICdzdHJpbmcnID8gcGF5bG9hZC5zb3VyY2UgOiB1bmRlZmluZWQ7CiAgaWYgKCFpZCB8fCB0eXBlb2Ygc291cmNlICE9PSAnc3RyaW5nJykgcmV0dXJuOwoKICB0cnkgewogICAgY29uc3QgaHRtbCA9IG1hcmtlZC5wYXJzZShzb3VyY2UpOwogICAgc2NvcGUucG9zdE1lc3NhZ2UoeyBpZCwga2V5LCBodG1sIH0pOwogIH0gY2F0Y2ggKGVycikgewogICAgc2NvcGUucG9zdE1lc3NhZ2UoeyBpZCwga2V5LCBodG1sOiBgPHByZT5FcnJvciByZW5kZXJpbmcgbWFya2Rvd246ICR7U3RyaW5nKGVycil9PC9wcmU+YCB9KTsKICB9Cn0pOwo=",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ao&&ao.tagName.toUpperCase()==="SCRIPT"&&ao.src||new URL("index.umd.js",document.baseURI).href),$r=im.toString(),LO=(()=>{try{if(typeof Worker>"u"||typeof URL>"u"||typeof Blob>"u")return!1;const t=new Blob(["export default null;"],{type:"application/javascript"}),e=URL.createObjectURL(t);return new Worker(e,{type:"module"}).terminate(),URL.revokeObjectURL(e),!0}catch{return!1}})(),PO=$r.includes("data:"),kO=(()=>{if(typeof navigator>"u")return!1;const t=navigator.userAgent.toLowerCase();return t.includes("safari")&&!t.includes("chrome")&&!t.includes("android")})(),jo=LO&&!(PO&&kO),Xo=t=>typeof t=="object"&&t!==null,Zo=t=>typeof t=="function"?t:Xo(t)&&typeof t.parse=="function"?t.parse:null;let $a=null;async function om(t){try{$a||($a=Promise.resolve().then(()=>KM));const e=await $a,n=Xo(e)?e:{},r=Zo(n.parse)??Zo(n.marked)??Zo(n.default);return r?r(t):""}catch(e){throw $a=null,e}}const UO=t=>Xo(t)&&typeof t.highlightElement=="function"?{highlightElement:t.highlightElement}:null;console.log("[MarkdownContent] worker url",$r);const Wr=[];let Kr=!1;const sm={addEventListener:()=>{},removeEventListener:()=>{},postMessage:()=>{},terminate:()=>{}};let yn=sm;const lm=t=>{console.error("[MarkdownContent] worker error",t)};function Jo(t){if(yn&&yn!==sm)try{yn.removeEventListener("error",lm)}catch{}yn=t,Kr=!0;try{yn.addEventListener("error",lm)}catch(e){console.warn("[MarkdownContent] failed to register worker error handler",e)}try{for(;Wr.length;){const e=Wr.shift();if(e)try{e()}catch{}}}catch(e){console.warn("[MarkdownContent] markWorkerOnline notify failed",e)}}function FO(t){if(!jo)return null;const e=t.indexOf("data:");if(e===-1)return null;const r=t.slice(e).match(/^data:[^;]+;base64,(.*)$/);if(!r)return null;try{const a=r[1],i=atob(a),o=Uint8Array.from(i,c=>c.charCodeAt(0)),s=new Blob([o],{type:"application/javascript"}),l=URL.createObjectURL(s);try{const c=new Worker(l,{type:"module"});return URL.revokeObjectURL(l),c}catch(c){return URL.revokeObjectURL(l),console.error("[MarkdownContent] failed to initialize worker from data URI blob",c),null}}catch(a){return console.warn("[MarkdownContent] failed to decode embedded data URI",a),null}}async function BO(t){if(jo)try{let e="";const n=await fetch(t);if(e=await n.text(),n.ok||console.warn("[MarkdownContent] fetch worker non-ok",n.status,n.statusText),!e){console.warn("[MarkdownContent] worker fetch returned empty content; aborting worker init.");return}if(e.trim().startsWith("<")){console.warn("[MarkdownContent] worker fetch returned HTML; dev server may be redirecting. Aborting worker init.");return}const r=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(r);try{const i=new Worker(a,{type:"module"});Jo(i)}catch(i){console.error("[MarkdownContent] failed to initialize worker from blob",i)}finally{URL.revokeObjectURL(a)}}catch(e){console.error("[MarkdownContent] fetch worker failed",e)}}function GO(){if($r.includes("data:")){const t=FO($r);if(t){Jo(t);return}console.warn("[MarkdownContent] data URI bootstrap failed; worker will remain offline until fallback succeeds");return}try{const t=new Worker(im,{type:"module"});Jo(t)}catch(t){console.warn("[MarkdownContent] worker constructor failed, will try fetch+blob fallback",t),BO($r)}}jo?GO():console.warn("[MarkdownContent] module workers not supported; falling back to main-thread markdown parsing");const Qr=new Map;function YO(t,e=!1){if(e){const a=t.slice(0,128);return`streaming:${Math.floor(t.length/50)*50}:${a}`}const n=t.slice(0,64),r=t.length>64?t.slice(-64):"";return`${t.length}:${n}:${r}`}function HO(t,e){const[n,r]=y.useState(t),a=y.useRef(t),i=y.useRef(null);return y.useEffect(()=>{if(!e){r(t);return}return a.current=t,i.current===null&&(i.current=requestAnimationFrame(()=>{i.current=null,r(a.current)})),()=>{i.current&&cancelAnimationFrame(i.current)}},[t,e]),n}function Wa({content:t,className:e="",fallback:n=u.jsx("div",{"aria-busy":!0,children:"Rendering…"}),isStreaming:r=!1,hideFallbackDuringStreaming:a=!0,streamingThrottleMs:i=16,useWorker:o}){const s=HO(t,r),l=YO(s,r),[c,d]=y.useState(()=>{var E;return((E=Qr.get(l))==null?void 0:E.html)??null}),_=y.useRef(null),p=y.useRef([]);y.useEffect(()=>{p.current=[];const E=Qr.get(l);if(E&&E.source===s){E.html!==c&&d(E.html);return}if(E&&E.html!==c&&d(E.html),!(o!==void 0?o:Kr&&!r)){console.log(`[MarkdownContent] Using main-thread parsing (streaming: ${r}, worker: ${o})`);let I=!1;return(async()=>{try{const D=await om(s);Qr.set(l,{html:D,source:s}),I||d(D)}catch(D){console.error("[MarkdownContent] fallback parse failed",D)}})(),()=>{I=!0}}let g=!0,S=!1;const b=`${l}::${Date.now().toString(36)}::${Math.random().toString(36).slice(2)}`;_.current=b;const h=I=>{const D=I.data;if(!D||D.id!==b||D.key&&D.key!==l||!g)return;S=!0;const M=D.html??"";Qr.set(l,{html:M,source:s}),d(M)};yn.addEventListener("message",h);const v=()=>{try{yn.postMessage({id:b,key:l,source:s})}catch(I){console.error("[MarkdownContent] worker.postMessage threw",I)}},C=()=>{if(!r||i<=0){v();return}if(typeof window>"u"){v();return}const I=window.setTimeout(()=>{if(typeof window.requestAnimationFrame=="function"){const D=window.requestAnimationFrame(()=>{v()});p.current.push({type:"raf",id:D})}else v()},i);p.current.push({type:"timeout",id:I})};Kr?C():Wr.push(C);const N=((I,D,M)=>D?M?I>2e4?15e3:I>8e3?8e3:I>2e3?3e3:1e3:I>2e4?1e4:I>8e3?5e3:I>2e3?2e3:600:Math.min(15e3,2e3+Math.floor(I*.5)))(s.length,Kr,r),O=window.setTimeout(async()=>{if(!S){console.warn("[MarkdownContent] worker timeout (ms="+N+"), falling back to main-thread parse for",l);try{const I=await om(s);Qr.set(l,{html:I,source:s}),g&&_.current===b&&d(I)}catch(I){console.error("[MarkdownContent] fallback parse failed",I)}}},N);return()=>{if(g=!1,clearTimeout(O),yn.removeEventListener("message",h),_.current===b&&(_.current=null),!Kr){const I=Wr.indexOf(C);I>=0&&Wr.splice(I,1)}p.current.forEach(I=>{I.type==="timeout"?clearTimeout(I.id):I.type==="raf"&&cancelAnimationFrame(I.id)}),p.current=[]}},[s,c,r,l,i]);const m=y.useRef(null);return y.useEffect(()=>{if(!c)return;const E=m.current;if(!E)return;const f=Array.from(E.querySelectorAll("pre code"));if(!f.length)return;let g=null,S=!1;const b=(v,C)=>{for(const R of v){if(!R.isIntersecting)continue;const N=R.target;if(!g)Promise.resolve().then(()=>S0).then(O=>{if(S)return;const I=UO(O.default??O);if(I){g=I;try{f.forEach(D=>{E.contains(D)&&(g==null||g.highlightElement(D))})}catch{}}}).catch(()=>{});else try{g.highlightElement(N)}catch{}C.unobserve(N)}},h=new IntersectionObserver(b,{root:E,threshold:.1});return f.forEach(v=>h.observe(v)),()=>{S=!0,h.disconnect()}},[c]),c?u.jsx("div",{ref:m,className:Q("markdown prose max-w-none break-words dark:prose-invert",e),dangerouslySetInnerHTML:{__html:c}}):r&&a?null:u.jsx("div",{className:Q("markdown prose max-w-none break-words dark:prose-invert",e),children:n})}async function cm(t,e){return await Gt(t,{responseType:"blob",onDownloadProgress:r=>{try{e&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function dm(t,e){return await(await cm(`/chat/files/${t}/view`,e)).text()}async function qO(t,e){const n=await cm(`/chat/files/${t}/download`,e),r=URL.createObjectURL(n);let a=`file_${t}`;try{const o=await Gt(`/chat/files/${t}`);a=(o==null?void 0:o.filename)??a}catch{}const i=document.createElement("a");i.href=r,i.download=a,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}const VO=1,zO=1e6;let es=0;function $O(){return es=(es+1)%Number.MAX_SAFE_INTEGER,es.toString()}const ts=new Map,um=t=>{if(ts.has(t))return;const e=setTimeout(()=>{ts.delete(t),jr({type:"REMOVE_TOAST",toastId:t})},zO);ts.set(t,e)},WO=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,VO)};case"UPDATE_TOAST":return{...t,toasts:t.toasts.map(n=>n.id===e.toast.id?{...n,...e.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=e;return n?um(n):t.toasts.forEach(r=>{um(r.id)}),{...t,toasts:t.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return e.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(n=>n.id!==e.toastId)}}},Ka=[];let Qa={toasts:[]};function jr(t){Qa=WO(Qa,t),Ka.forEach(e=>{e(Qa)})}function KO({...t}){const e=$O(),n=a=>jr({type:"UPDATE_TOAST",toast:{...a,id:e}}),r=()=>jr({type:"DISMISS_TOAST",toastId:e});return jr({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:a=>{a||r()}}}),{id:e,dismiss:r,update:n}}function ns(){const[t,e]=T.useState(Qa);return T.useEffect(()=>(Ka.push(e),()=>{const n=Ka.indexOf(e);n>-1&&Ka.splice(n,1)}),[t]),{...t,toast:KO,dismiss:n=>jr({type:"DISMISS_TOAST",toastId:n})}}function ft(t){const e=T.useRef(t);return T.useEffect(()=>{e.current=t}),T.useMemo(()=>(...n)=>{var r;return(r=e.current)==null?void 0:r.call(e,...n)},[])}function QO(t,e=globalThis==null?void 0:globalThis.document){const n=ft(t);T.useEffect(()=>{const r=a=>{a.key==="Escape"&&n(a)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[n,e])}var jO="DismissableLayer",rs="dismissableLayer.update",XO="dismissableLayer.pointerDownOutside",ZO="dismissableLayer.focusOutside",_m,pm=T.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Xr=T.forwardRef((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:o,onDismiss:s,...l}=t,c=T.useContext(pm),[d,_]=T.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,m]=T.useState({}),E=Be(e,N=>_(N)),f=Array.from(c.layers),[g]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),S=f.indexOf(g),b=d?f.indexOf(d):-1,h=c.layersWithOutsidePointerEventsDisabled.size>0,v=b>=S,C=ty(N=>{const O=N.target,I=[...c.branches].some(D=>D.contains(O));!v||I||(a==null||a(N),o==null||o(N),N.defaultPrevented||s==null||s())},p),R=ny(N=>{const O=N.target;[...c.branches].some(D=>D.contains(O))||(i==null||i(N),o==null||o(N),N.defaultPrevented||s==null||s())},p);return QO(N=>{b===c.layers.size-1&&(r==null||r(N),!N.defaultPrevented&&s&&(N.preventDefault(),s()))},p),T.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(_m=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),mm(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=_m)}},[d,p,n,c]),T.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),mm())},[d,c]),T.useEffect(()=>{const N=()=>m({});return document.addEventListener(rs,N),()=>document.removeEventListener(rs,N)},[]),u.jsx(xe.div,{...l,ref:E,style:{pointerEvents:h?v?"auto":"none":void 0,...t.style},onFocusCapture:ue(t.onFocusCapture,R.onFocusCapture),onBlurCapture:ue(t.onBlurCapture,R.onBlurCapture),onPointerDownCapture:ue(t.onPointerDownCapture,C.onPointerDownCapture)})});Xr.displayName=jO;var JO="DismissableLayerBranch",ey=T.forwardRef((t,e)=>{const n=T.useContext(pm),r=T.useRef(null),a=Be(e,r);return T.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),u.jsx(xe.div,{...t,ref:a})});ey.displayName=JO;function ty(t,e=globalThis==null?void 0:globalThis.document){const n=ft(t),r=T.useRef(!1),a=T.useRef(()=>{});return T.useEffect(()=>{const i=s=>{if(s.target&&!r.current){let l=function(){gm(XO,n,c,{discrete:!0})};const c={originalEvent:s};s.pointerType==="touch"?(e.removeEventListener("click",a.current),a.current=l,e.addEventListener("click",a.current,{once:!0})):l()}else e.removeEventListener("click",a.current);r.current=!1},o=window.setTimeout(()=>{e.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(o),e.removeEventListener("pointerdown",i),e.removeEventListener("click",a.current)}},[e,n]),{onPointerDownCapture:()=>r.current=!0}}function ny(t,e=globalThis==null?void 0:globalThis.document){const n=ft(t),r=T.useRef(!1);return T.useEffect(()=>{const a=i=>{i.target&&!r.current&&gm(ZO,n,{originalEvent:i},{discrete:!1})};return e.addEventListener("focusin",a),()=>e.removeEventListener("focusin",a)},[e,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function mm(){const t=new CustomEvent(rs);document.dispatchEvent(t)}function gm(t,e,n,{discrete:r}){const a=n.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&a.addEventListener(t,e,{once:!0}),r?Jp(a,i):a.dispatchEvent(i)}var as="focusScope.autoFocusOnMount",is="focusScope.autoFocusOnUnmount",Em={bubbles:!1,cancelable:!0},ry="FocusScope",ja=T.forwardRef((t,e)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...o}=t,[s,l]=T.useState(null),c=ft(a),d=ft(i),_=T.useRef(null),p=Be(e,f=>l(f)),m=T.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;T.useEffect(()=>{if(r){let f=function(h){if(m.paused||!s)return;const v=h.target;s.contains(v)?_.current=v:In(_.current,{select:!0})},g=function(h){if(m.paused||!s)return;const v=h.relatedTarget;v!==null&&(s.contains(v)||In(_.current,{select:!0}))},S=function(h){if(document.activeElement===document.body)for(const C of h)C.removedNodes.length>0&&In(s)};document.addEventListener("focusin",f),document.addEventListener("focusout",g);const b=new MutationObserver(S);return s&&b.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",f),document.removeEventListener("focusout",g),b.disconnect()}}},[r,s,m.paused]),T.useEffect(()=>{if(s){bm.add(m);const f=document.activeElement;if(!s.contains(f)){const S=new CustomEvent(as,Em);s.addEventListener(as,c),s.dispatchEvent(S),S.defaultPrevented||(ay(cy(fm(s)),{select:!0}),document.activeElement===f&&In(s))}return()=>{s.removeEventListener(as,c),setTimeout(()=>{const S=new CustomEvent(is,Em);s.addEventListener(is,d),s.dispatchEvent(S),S.defaultPrevented||In(f??document.body,{select:!0}),s.removeEventListener(is,d),bm.remove(m)},0)}}},[s,c,d,m]);const E=T.useCallback(f=>{if(!n&&!r||m.paused)return;const g=f.key==="Tab"&&!f.altKey&&!f.ctrlKey&&!f.metaKey,S=document.activeElement;if(g&&S){const b=f.currentTarget,[h,v]=iy(b);h&&v?!f.shiftKey&&S===v?(f.preventDefault(),n&&In(h,{select:!0})):f.shiftKey&&S===h&&(f.preventDefault(),n&&In(v,{select:!0})):S===b&&f.preventDefault()}},[n,r,m.paused]);return u.jsx(xe.div,{tabIndex:-1,...o,ref:p,onKeyDown:E})});ja.displayName=ry;function ay(t,{select:e=!1}={}){const n=document.activeElement;for(const r of t)if(In(r,{select:e}),document.activeElement!==n)return}function iy(t){const e=fm(t),n=Sm(e,t),r=Sm(e.reverse(),t);return[n,r]}function fm(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function Sm(t,e){for(const n of t)if(!oy(n,{upTo:e}))return n}function oy(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function sy(t){return t instanceof HTMLInputElement&&"select"in t}function In(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&sy(t)&&e&&t.select()}}var bm=ly();function ly(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=Tm(t,e),t.unshift(e)},remove(e){var n;t=Tm(t,e),(n=t[0])==null||n.resume()}}}function Tm(t,e){const n=[...t],r=n.indexOf(e);return r!==-1&&n.splice(r,1),n}function cy(t){return t.filter(e=>e.tagName!=="A")}var dy="Portal",Xa=T.forwardRef((t,e)=>{var s;const{container:n,...r}=t,[a,i]=T.useState(!1);gt(()=>i(!0),[]);const o=n||a&&((s=globalThis==null?void 0:globalThis.document)==null?void 0:s.body);return o?ro.createPortal(u.jsx(xe.div,{...r,ref:e}),o):null});Xa.displayName=dy;var os=0;function ss(){T.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??hm()),document.body.insertAdjacentElement("beforeend",t[1]??hm()),os++,()=>{os===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),os--}},[])}function hm(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var cn=function(){return cn=Object.assign||function(e){for(var n,r=1,a=arguments.length;r<a;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},cn.apply(this,arguments)};function Cm(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(t);a<r.length;a++)e.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(t,r[a])&&(n[r[a]]=t[r[a]]);return n}function uy(t,e,n){if(n||arguments.length===2)for(var r=0,a=e.length,i;r<a;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;var Za="right-scroll-bar-position",Ja="width-before-scroll-bar",_y="with-scroll-bars-hidden",py="--removed-body-scroll-bar-size";function ls(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function my(t,e){var n=y.useState(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(r){var a=n.value;a!==r&&(n.value=r,n.callback(r,a))}}}})[0];return n.callback=e,n.facade}var gy=typeof window<"u"?T.useLayoutEffect:T.useEffect,Rm=new WeakMap;function Ey(t,e){var n=my(null,function(r){return t.forEach(function(a){return ls(a,r)})});return gy(function(){var r=Rm.get(n);if(r){var a=new Set(r),i=new Set(t),o=n.current;a.forEach(function(s){i.has(s)||ls(s,null)}),i.forEach(function(s){a.has(s)||ls(s,o)})}Rm.set(n,t)},[t]),n}function fy(t){return t}function Sy(t,e){e===void 0&&(e=fy);var n=[],r=!1,a={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(i){var o=e(i,r);return n.push(o),function(){n=n.filter(function(s){return s!==o})}},assignSyncMedium:function(i){for(r=!0;n.length;){var o=n;n=[],o.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){r=!0;var o=[];if(n.length){var s=n;n=[],s.forEach(i),o=n}var l=function(){var d=o;o=[],d.forEach(i)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){o.push(d),c()},filter:function(d){return o=o.filter(d),n}}}};return a}function by(t){t===void 0&&(t={});var e=Sy(null);return e.options=cn({async:!0,ssr:!1},t),e}var vm=function(t){var e=t.sideCar,n=Cm(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return T.createElement(r,cn({},n))};vm.isSideCarExport=!0;function Ty(t,e){return t.useMedium(e),vm}var Nm=by(),cs=function(){},ei=T.forwardRef(function(t,e){var n=T.useRef(null),r=T.useState({onScrollCapture:cs,onWheelCapture:cs,onTouchMoveCapture:cs}),a=r[0],i=r[1],o=t.forwardProps,s=t.children,l=t.className,c=t.removeScrollBar,d=t.enabled,_=t.shards,p=t.sideCar,m=t.noRelative,E=t.noIsolation,f=t.inert,g=t.allowPinchZoom,S=t.as,b=S===void 0?"div":S,h=t.gapMode,v=Cm(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,R=Ey([n,e]),N=cn(cn({},v),a);return T.createElement(T.Fragment,null,d&&T.createElement(C,{sideCar:Nm,removeScrollBar:c,shards:_,noRelative:m,noIsolation:E,inert:f,setCallbacks:i,allowPinchZoom:!!g,lockRef:n,gapMode:h}),o?T.cloneElement(T.Children.only(s),cn(cn({},N),{ref:R})):T.createElement(b,cn({},N,{className:l,ref:R}),s))});ei.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ei.classNames={fullWidth:Ja,zeroRight:Za};var hy=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Cy(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=hy();return e&&t.setAttribute("nonce",e),t}function Ry(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function vy(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var Ny=function(){var t=0,e=null;return{add:function(n){t==0&&(e=Cy())&&(Ry(e,n),vy(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},Oy=function(){var t=Ny();return function(e,n){T.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&n])}},Om=function(){var t=Oy(),e=function(n){var r=n.styles,a=n.dynamic;return t(r,a),null};return e},yy={left:0,top:0,right:0,gap:0},ds=function(t){return parseInt(t||"",10)||0},Iy=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],a=e[t==="padding"?"paddingRight":"marginRight"];return[ds(n),ds(r),ds(a)]},Ay=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return yy;var e=Iy(t),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-n+e[2]-e[0])}},xy=Om(),ur="data-scroll-locked",Dy=function(t,e,n,r){var a=t.left,i=t.top,o=t.right,s=t.gap;return n===void 0&&(n="margin"),`
|
|
38
|
+
`)}const Lv={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null};function Pv(t,e){var n;switch(e.type){case"reset":return{messages:ho(((n=e.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null};case"seed":{const r=ho(e.payload.messages),a={...t,messages:r,assemblingId:null};return Object.prototype.hasOwnProperty.call(e.payload,"checkpointId")&&(a.lastCheckpointId=e.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(e.payload,"checkpointNs")&&(a.lastCheckpointNs=e.payload.checkpointNs??null),console.log("[MessageReducer] seed action:",{incomingCount:e.payload.messages.length,sanitizedCount:r.length,checkpointId:a.lastCheckpointId}),a}case"prepend":{const r=ho(e.payload.messages);if(!r.length)return console.log("[MessageReducer] No incoming messages after sanitize - skipping"),t;const a=new Set(t.messages.map(o=>o.id)),i=r.filter(o=>!a.has(o.id));return console.log("[MessageReducer] After dedup:",{uniqueCount:i.length,duplicates:r.length-i.length,finalTotal:i.length+t.messages.length}),i.length?{...t,messages:[...i,...t.messages]}:(console.log("[MessageReducer] All messages were duplicates - skipping"),t)}case"user_message":{const r=e.payload.message;if(t.assemblingId){const a=t.messages.findIndex(i=>i.id===t.assemblingId);if(a!==-1)return{...t,messages:[...t.messages.slice(0,a),r,...t.messages.slice(a)]}}return{...t,messages:[...t.messages,r]}}case"event":return Q_(t,e.payload.ev);case"batch":{const{events:r}=e.payload;return r.length?r.reduce((a,i)=>Q_(a,i),t):t}default:return t}}function K_(t=[]){const[e,n]=y.useReducer(Pv,{...Lv,messages:t}),r=y.useRef([]),a=y.useRef(null),i=y.useRef(null),o=y.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),i.current!==null&&clearTimeout(i.current),a.current=null,i.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),s=y.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?a.current===null&&(a.current=window.requestAnimationFrame(()=>o())):i.current===null&&(i.current=setTimeout(o,8))},[o]),l=y.useCallback(d=>{r.current.push(d),s()},[s]);y.useEffect(()=>()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),i.current!==null&&clearTimeout(i.current),r.current=[]},[]);const c=y.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,_)=>n({type:"seed",payload:{messages:d,..._??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:e,dispatch:n,...c}}function Q_(t,e){var n;if(e.type==="message_start"&&e.role==="assistant"){const r=e.id,a=Gv(e.model),i={id:r,role:"assistant",name:a||void 0,model:e.model,createdAt:new Date().toISOString(),content:[]};return{...t,assemblingId:r,messages:[...t.messages,i]}}if(e.type==="token"){const r=t.assemblingId??Co(t.messages);return r?{...t,messages:Uv(t.messages,r,e.content)}:t}if(e.type==="message_delta"){const r=t.assemblingId??Co(t.messages);return r?{...t,messages:j_(t.messages,r,e.delta)}:t}if(e.type==="message_end"){const r=t.assemblingId??Co(t.messages);if(!r)return{...t,assemblingId:null};const a=t.messages,i=a.findIndex(o=>o.id===r&&o.role==="assistant");if(i>=0&&!((n=a[i].content)==null?void 0:n.some(l=>{var c;return(l==null?void 0:l.type)==="text"&&((c=l.text)==null?void 0:c.trim())}))){const l=[...a.slice(0,i),...a.slice(i+1)];return{...t,assemblingId:null,messages:l}}return t}if(e.type==="tool_start"){const r=`tool-${e.id}`,a={type:"tool_call",id:e.id,name:e.name,args:e.args},i={id:r,role:"tool",name:e.name,createdAt:new Date().toISOString(),content:[a]};return{...t,messages:[...t.messages,i],toolIndex:{...t.toolIndex,[e.id]:r}}}if(e.type==="tool_result"){const r=t.toolIndex[e.id]??`tool-${e.id}`,a={type:"tool_result",toolCallId:e.id,output:e.output,error:e.error},i=t.messages.find(l=>l.id===r),o={id:r,role:"tool",content:[a],createdAt:new Date().toISOString()},s=i?j_(t.messages,r,[a]):[...t.messages,o];return{...t,messages:s}}if(e.type==="checkpoint"){const r=e.checkpointNs??t.lastCheckpointNs??null,a=Bv(t.messages,e.checkpointId,r);return{...t,lastCheckpointId:e.checkpointId,lastCheckpointNs:r,messages:a}}if(e.type==="branch"){const r=e.checkpointId??t.lastCheckpointId,a=e.checkpointNs??t.lastCheckpointNs;return{...t,lastBranch:e,lastCheckpointId:r??null,lastCheckpointNs:a??null}}if(e.type==="error"){const r={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${e.message}`}],createdAt:new Date().toISOString()};return{...t,messages:[...t.messages,r]}}return t}function ho(t){return t.filter(e=>{if(e.role!=="assistant")return!0;const n=(e.content||[]).some(a=>{var i;return a&&a.type==="text"&&((i=a.text)==null?void 0:i.trim())}),r=(e.content||[]).some(a=>a&&a.type==="image_url");return!!(n||r)})}function kv(t,e,n){return e<0||e>=t.length?t:[...t.slice(0,e),n,...t.slice(e+1)]}function Co(t){for(let e=t.length-1;e>=0;e--)if(t[e].role==="assistant")return t[e].id;return null}function Uv(t,e,n){return t.map(r=>{if(r.id!==e)return r;const a=r.content.slice(),i=a[a.length-1];return i&&i.type==="text"?i.text+=n:a.push({type:"text",text:n}),{...r,content:a}})}function j_(t,e,n){return t.map(r=>r.id===e?{...r,content:Fv(r.content,n)}:r)}function Fv(t,e){const n=t.slice();for(const r of e)if(r.type==="text"){const a=n[n.length-1];(a==null?void 0:a.type)==="text"?a.text+=r.text:n.push({type:"text",text:r.text})}else n.push(r);return n}function Bv(t,e,n){for(let r=t.length-1;r>=0;r--)if(t[r].role==="assistant"){const i={...t[r],checkpointId:e,checkpointNs:n??void 0};return kv(t,r,i)}return t}function Gv(t){if(!t)return null;const e=t.split("/");return e[e.length-1]||null}function Yv(t,e){const n=t==null?void 0:t.checkpoints,r=Array.isArray(n)?n.slice():n?Object.values(n):[],a=o=>o&&typeof o=="object"&&typeof o.checkpointId=="string"&&typeof o.createdAt=="string",i=r.filter(a).map(o=>({checkpointId:o.checkpointId,checkpointNs:o.checkpointNs??"",createdAt:o.createdAt,messagesLen:o.messagesLen??0,preview:o.preview??"",role:o.role??null,parentId:o.parentId??null,editedMessageId:o.editedMessageId??null,branchLabel:o.branchLabel??null,lastMessageId:o.lastMessageId??null,hasMessages:typeof o.hasMessages=="boolean"?o.hasMessages:void 0}));return{threadId:(t==null?void 0:t.threadId)??e??null,checkpoints:i}}async function Hv(t){return await new Promise((e,n)=>{const r=new FileReader;r.onload=()=>{try{const a=r.result,i=new Uint8Array(a);let o="";const s=i.byteLength;for(let l=0;l<s;l++)o+=String.fromCharCode(i[l]);e(btoa(o))}catch(a){n(a)}},r.onerror=a=>n(a),r.readAsArrayBuffer(t)})}async function qv(t,e=[],n,r,a,i){const o=[],s=[];for(const l of e)try{const c=await Hv(l);s.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:o,filesInfo:s}}const X_=y.createContext(null);function Pr({children:t,apiConfig:e,onError:n,onThreadChange:r,initialThreadId:a=null,autoLoadInitial:i=!0,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader"}){const l=En;y.useEffect(()=>{e&&l.updateConfig({baseUrl:e.baseUrl,authToken:e.apiKey})},[l,e]);const{isStreaming:c,error:d,stream:_,stop:p,setToken:m}=W_({baseUrl:l.baseUrl,token:null,headers:e==null?void 0:e.headers,streamPath:"/chat/runs/stream"}),[E,f]=y.useState(()=>typeof l.getAuthToken=="function"?l.getAuthToken():null);y.useEffect(()=>{m(typeof l.getAuthToken=="function"?l.getAuthToken():null);const k=l.onTokenChange(j=>{f(j),m(j)});return()=>{k()}},[l,m]);const g=y.useCallback(k=>{l.setAuthToken(k)},[l]),{state:S,seed:b,prepend:h,pushUser:v,onEvent:C,reset:R}=K_(),N=20,[O,I]=y.useState(!1),[D,M]=y.useState(!1),[Y,K]=y.useState(null),[F,$]=y.useState(void 0),[x,B]=y.useState(void 0),[L,U]=y.useState(!1),z=y.useRef(!1),W=y.useRef([]),ne=y.useCallback(k=>{k.cursor!==void 0&&K(k.cursor),k.hasMore!==void 0&&I(k.hasMore),k.checkpointId!==void 0&&$(k.checkpointId),k.checkpointNs!==void 0&&B(k.checkpointNs)},[]),q=y.useCallback((k,j)=>new Promise((be,ke)=>{const Ce=async()=>{if(z.current){console.warn(`[ChatProvider] Operation "${j}" queued - another operation in progress`),W.current.push(Ce);return}z.current=!0;try{console.log(`[ChatProvider] Executing operation: ${j}`),await k(),be()}catch(je){console.error(`[ChatProvider] Operation "${j}" failed:`,je),ke(je)}finally{z.current=!1;const je=W.current.shift();je&&je().catch(()=>{})}};z.current?(W.current.push(Ce),console.log(`[ChatProvider] Queued operation: ${j}`)):Ce().catch(je=>{ke(je)})}),[]),X=y.useCallback((k,j)=>{const be=Array.isArray(k==null?void 0:k.messages)?k.messages:[];j==="replace"?(console.log("[ChatProvider] Replacing messages, count:",be.length),b(be,{checkpointId:(k==null?void 0:k.checkpointId)??null,checkpointNs:(k==null?void 0:k.checkpointNs)??null})):j==="prepend"&&be.length?(console.log("[ChatProvider] Calling prepend with",be.length,"messages"),h(be)):console.log("[ChatProvider] Skipping prepend - empty list or wrong mode"),K((k==null?void 0:k.nextCursor)??null),I(!!(k!=null&&k.hasMore)),$(ke=>(k==null?void 0:k.checkpointId)??ke??void 0),B(ke=>(k==null?void 0:k.checkpointNs)??ke??void 0)},[b,h]),[se,ce]=y.useState([]),[H,P]=y.useState(null),V=y.useCallback(async()=>{const k=await l.listThreads();ce(k)},[l]),[Z,ie]=y.useState(!1),oe=y.useCallback(async k=>{const j=(k==null?void 0:k.maxAttempts)??5,be=(k==null?void 0:k.baseDelayMs)??500,ke=(k==null?void 0:k.timeoutMs)??2e3;if(!l.baseUrl)return!1;const Ce=l.baseUrl.replace(/\/+$/,""),je=["/health","/api/health","/","/api/v2/health","/api/v2/chat/health"],St=async mt=>{try{const Rt=new AbortController,_t=setTimeout(()=>Rt.abort(),ke),Et=await fetch(mt,{method:"GET",signal:Rt.signal});return clearTimeout(_t),Et.ok}catch{return!1}},gn=async mt=>{try{const Rt=new AbortController,_t=setTimeout(()=>Rt.abort(),ke),Et=await fetch(mt,{method:"HEAD",signal:Rt.signal});return clearTimeout(_t),Et.ok}catch{return!1}};for(let mt=0;mt<j;mt++){console.debug(`[ChatProvider] health-check attempt ${mt+1}/${j}`);for(const _t of je){let Et=_t;Ce.endsWith("/api")&&_t.startsWith("/api")&&(Et=_t.replace(/^\/api/,"")||"/");const Wt=Et==="/"?Ce+"/":Ce+Et;if(console.debug(`[ChatProvider] checking ${Wt}`),await St(Wt)||_t==="/"&&await gn(Ce+"/"))return ie(!0),!0}const Rt=be*Math.pow(2,mt);await new Promise(_t=>setTimeout(_t,Rt))}return ie(!1),!1},[l.baseUrl]);y.useEffect(()=>{let k=!0;if(!l.baseUrl){console.debug("[ChatProvider] skipping initial refreshThreads: api.baseUrl not configured");return}return(async()=>{try{const j=await oe();if(!k)return;j?V().catch(()=>{}):console.warn("[ChatProvider] backend health-check failed — skipping initial loads")}catch{}})(),()=>{k=!1}},[V,l.baseUrl,oe]),y.useEffect(()=>{r==null||r(H)},[H,r]);const Ne=y.useRef(null);y.useEffect(()=>{if(a&&i){if(!l.baseUrl){console.debug("[ChatProvider] skipping initial load: api.baseUrl not configured");return}if(!Z){console.debug("[ChatProvider] deferring initial load until backend health-check passes");return}Ne.current!==a&&(Ne.current=a,de(a).catch(()=>{}))}},[a,i,l.baseUrl,Z]);const Ue=y.useRef(null),Oe=y.useRef(null),de=y.useCallback(async(k,j,be)=>{await q(async()=>{if(!l.baseUrl){console.debug("[ChatProvider] skipping loadThread: api.baseUrl not configured");return}if(Ue.current){console.warn(`[ChatProvider] Thread load cancelled - another thread (${Ue.current}) is loading`);return}Oe.current!==null&&Oe.current!==k&&(console.log(`[ChatProvider] Thread switch detected: ${Oe.current} -> ${k}`),b([],{checkpointId:null,checkpointNs:null})),Ue.current=k,Oe.current=k;try{ne({cursor:null,hasMore:!1,checkpointId:void 0,checkpointNs:void 0}),P(k);const Ce=await l.getMessages({threadId:k,checkpointId:j,checkpointNs:be,limit:N}),je=Array.isArray(Ce==null?void 0:Ce.messages)?Ce.messages:[];console.log("[ChatProvider] Loading thread with",je.length,"messages"),b(je,{checkpointId:(Ce==null?void 0:Ce.checkpointId)??null,checkpointNs:(Ce==null?void 0:Ce.checkpointNs)??null}),K((Ce==null?void 0:Ce.nextCursor)??null),I(!!(Ce!=null&&Ce.hasMore)),$(St=>(Ce==null?void 0:Ce.checkpointId)??St??void 0),B(St=>(Ce==null?void 0:Ce.checkpointNs)??St??void 0)}finally{Ue.current=null}},`loadThread-${k}`)},[l,q,ne,b]),Me=y.useCallback(async k=>{const j=await l.listCheckpoints(k);return Yv(j,k)},[l]),ae=y.useCallback(async(k,j)=>{await q(async()=>{if(!H)throw new Error("No active thread");ne({cursor:null,hasMore:!1,checkpointId:void 0,checkpointNs:void 0});const be=await l.getMessages({threadId:H,checkpointId:k,checkpointNs:j??void 0,limit:N});X(be,"replace")},`navigateToCheckpoint-${k}`)},[l,H,X,q,ne]),fe=y.useCallback(async()=>{if(!H)throw new Error("No active thread");await de(H)},[H,de]),Te=y.useRef(!1);y.useEffect(()=>{const k=Te.current;Te.current=c,k&&!c&&H&&q(async()=>{try{await V()}catch(j){console.warn("[ChatProvider] Post-streaming thread refresh failed:",j)}},"postStreamingRefresh")},[c,H,l,X,V,q]);const Se=y.useCallback(async k=>{const j=await l.createThread(k);return await V(),await de(j.threadId),j.threadId},[l,V,de]),tt=y.useCallback(async k=>{await l.deleteThread(k),await V(),H===k&&(P(null),R([]),I(!1),K(null),$(void 0),B(void 0))},[l,V,H,R]),We=y.useCallback(async(k,j)=>{await l.updateThread(k,j),await V()},[l,V]),ct=y.useCallback(async(k,j)=>{await q(async()=>{var wt;const be=(j==null?void 0:j.attachments)||[],{contentParts:ke,filesInfo:Ce}=await qv(l,be,e==null?void 0:e.uploadPath),je=[];k&&k.trim()&&je.push({type:"text",text:k.trim()});const St={id:((wt=crypto.randomUUID)==null?void 0:wt.call(crypto))||`user-${Date.now()}`,role:"user",content:je,createdAt:new Date().toISOString(),checkpointId:(j==null?void 0:j.checkpointId)??S.lastCheckpointId??void 0,checkpointNs:(j==null?void 0:j.checkpointNs)??S.lastCheckpointNs??void 0};v(St);const gn={...St,content:je},mt={...(j==null?void 0:j.payloadExtras)??{}},Rt=!!mt.edit,_t=mt.originalMessageId,Et=typeof _t=="string"?_t:void 0,Wt=be&&be.length>0,Ge={...H?{threadId:H}:{},payload:{messages:[gn],files_info:Ce,...o&&Wt&&s?{active_agent:s}:{},...mt},checkpointId:(j==null?void 0:j.checkpointId)??S.lastCheckpointId??void 0,checkpointNs:(j==null?void 0:j.checkpointNs)??S.lastCheckpointNs??void 0,nodeFilter:j==null?void 0:j.nodeFilter,config:j==null?void 0:j.config,edit:Rt,originalMessageId:Et};_(Ge,le=>C(le),{onError:le=>console.warn("stream error",le),onOpen:({threadId:le,created:Ee})=>{!H&&le&&(P(le),Ee&&V().catch(()=>{}))}})},"send")},[H,v,_,C,S.lastCheckpointId,S.lastCheckpointNs,l,e==null?void 0:e.uploadPath,V,P,o,s,q]),et=y.useCallback(async k=>{if(!H)throw new Error("No active thread");if(D||!O)return;const j=Y;if(j){M(!0);try{const be=await l.getMessages({threadId:H,checkpointId:F,checkpointNs:x,limit:(k==null?void 0:k.limit)??N,beforeId:j});X(be,"prepend")}finally{M(!1)}}},[l,H,F,x,Y,O,D,X,N]),te={baseUrl:l.baseUrl,token:E,setToken:g,api:l,threads:se,currentThreadId:H,setCurrentThreadId:P,messages:S.messages,isStreaming:c,error:d,lastCheckpointId:S.lastCheckpointId,lastCheckpointNs:S.lastCheckpointNs,streamingAssistantId:S.assemblingId,hasMoreHistory:O,isLoadingHistory:D,isPostStreamFetch:L,loadOlderMessages:et,historyPageSize:N,listCheckpoints:Me,navigateToCheckpoint:ae,returnToLatest:fe,refreshThreads:V,createThread:Se,deleteThread:tt,renameThread:We,loadThread:de,send:ct,stop:p};return u.jsx(X_.Provider,{value:te,children:t})}function xa(){const t=y.useContext(X_);if(!t)throw new Error("useChat must be used within ChatProvider");return t}function Q(...t){return oR.twMerge(iR.clsx(t))}const Vv=yr.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),$e=T.forwardRef(({className:t,variant:e,size:n,asChild:r=!1,...a},i)=>{const o=r?Mt.Slot:"button";return u.jsx(o,{className:Q(Vv({variant:e,size:n,className:t})),ref:i,...a})});$e.displayName="Button";const Z_=T.forwardRef(({className:t,...e},n)=>u.jsx("textarea",{className:Q("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:n,...e}));Z_.displayName="Textarea";function zv({initialValue:t="",editingMessageId:e=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:a=!1,maxLength:i=2e4,onSend:o,onCancelEdit:s,onStop:l,className:c="",textareaClassName:d="",allowEmptySend:_=!1}){const[p,m]=y.useState(t),[E,f]=y.useTransition(),g=y.useRef(null);y.useEffect(()=>{m(t??""),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[t,e]);const S=y.useCallback(()=>{const O=g.current;O&&(O.style.height="auto",O.style.height=`${O.scrollHeight}px`)},[]);y.useEffect(()=>{S()},[S]);const b=y.useCallback(async O=>{O&&O.preventDefault();const I=(p??"").trim();!I&&!_||f(()=>{try{const D=o(I);D&&typeof D.then=="function"?D.then(()=>{m(""),g.current&&(g.current.style.height="auto")}).catch(()=>{}):(m(""),g.current&&(g.current.style.height="auto"))}catch{}})},[p,o,_]),h=y.useCallback(O=>{m(O.target.value),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[]),v=y.useCallback(O=>{O.key==="Enter"&&!O.shiftKey?(O.preventDefault(),b()):O.key==="Escape"&&e&&(O.preventDefault(),s==null||s())},[b,e,s]),N=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${e?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${d}`;return u.jsx("form",{onSubmit:O=>void b(O),className:`w-full ${c}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(Z_,{ref:g,value:p,onChange:h,onKeyDown:v,placeholder:e?"Edit your message...":n,className:N,disabled:a,maxLength:i,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx($e,{type:"button",onClick:()=>{l==null||l()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:a||!l,children:u.jsx(pe.Square,{size:16})}):u.jsx($e,{type:"submit",size:"icon",className:"shrink-0",title:e?"Save changes":"Send message",disabled:a||!p.trim()&&!_||E,children:u.jsx(pe.Send,{size:16})})})]})})}const $v=y.memo(zv),Da=0,Cn=1,lr=2,J_=4;function ep(t){return()=>t}function Wv(t){t()}function tp(t,e){return n=>t(e(n))}function np(t,e){return()=>t(e)}function Kv(t,e){return n=>t(e,n)}function Ro(t){return t!==void 0}function Qv(...t){return()=>{t.map(Wv)}}function cr(){}function wa(t,e){return e(t),t}function jv(t,e){return e(t)}function nt(...t){return t}function Qe(t,e){return t(Cn,e)}function Pe(t,e){t(Da,e)}function vo(t){t(lr)}function lt(t){return t(J_)}function he(t,e){return Qe(t,Kv(e,Da))}function Qt(t,e){const n=t(Cn,r=>{n(),e(r)});return n}function rp(t){let e,n;return r=>a=>{e=a,n&&clearTimeout(n),n=setTimeout(()=>{r(e)},t)}}function ap(t,e){return t===e}function rt(t=ap){let e;return n=>r=>{t(e,r)||(e=r,n(r))}}function Ae(t){return e=>n=>{t(n)&&e(n)}}function me(t){return e=>tp(e,t)}function on(t){return e=>()=>{e(t)}}function J(t,...e){const n=Xv(...e);return(r,a)=>{switch(r){case lr:vo(t);return;case Cn:return Qe(t,n(a))}}}function sn(t,e){return n=>r=>{n(e=t(e,r))}}function Yn(t){return e=>n=>{t>0?t--:e(n)}}function fn(t){let e=null,n;return r=>a=>{e=a,!n&&(n=setTimeout(()=>{n=void 0,r(e)},t))}}function Fe(...t){const e=new Array(t.length);let n=0,r=null;const a=Math.pow(2,t.length)-1;return t.forEach((i,o)=>{const s=Math.pow(2,o);Qe(i,l=>{const c=n;n=n|s,e[o]=l,c!==a&&n===a&&r&&(r(),r=null)})}),i=>o=>{const s=()=>{i([o].concat(e))};n===a?s():r=s}}function Xv(...t){return e=>t.reduceRight(jv,e)}function Zv(t){let e,n;const r=()=>e==null?void 0:e();return function(a,i){switch(a){case Cn:return i?n===i?void 0:(r(),n=i,e=Qe(t,i),e):(r(),cr);case lr:r(),n=null;return}}}function re(t){let e=t;const n=He();return(r,a)=>{switch(r){case Da:e=a;break;case Cn:{a(e);break}case J_:return e}return n(r,a)}}function Tt(t,e){return wa(re(e),n=>he(t,n))}function He(){const t=[];return(e,n)=>{switch(e){case Da:t.slice().forEach(r=>{r(n)});return;case lr:t.splice(0,t.length);return;case Cn:return t.push(n),()=>{const r=t.indexOf(n);r>-1&&t.splice(r,1)}}}}function Lt(t){return wa(He(),e=>he(t,e))}function ze(t,e=[],{singleton:n}={singleton:!0}){return{constructor:t,dependencies:e,id:Jv(),singleton:n}}const Jv=()=>Symbol();function eN(t){const e=new Map,n=({constructor:r,dependencies:a,id:i,singleton:o})=>{if(o&&e.has(i))return e.get(i);const s=r(a.map(l=>n(l)));return o&&e.set(i,s),s};return n(t)}function ut(...t){const e=He(),n=new Array(t.length);let r=0;const a=Math.pow(2,t.length)-1;return t.forEach((i,o)=>{const s=Math.pow(2,o);Qe(i,l=>{n[o]=l,r=r|s,r===a&&Pe(e,n)})}),function(i,o){switch(i){case lr:{vo(e);return}case Cn:return r===a&&o(n),Qe(e,o)}}}function Ie(t,e=ap){return J(t,rt(e))}function No(...t){return function(e,n){switch(e){case lr:return;case Cn:return Qv(...t.map(r=>Qe(r,n)))}}}var xt=(t=>(t[t.DEBUG=0]="DEBUG",t[t.INFO=1]="INFO",t[t.WARN=2]="WARN",t[t.ERROR=3]="ERROR",t))(xt||{});const tN={0:"debug",3:"error",1:"log",2:"warn"},nN=()=>typeof globalThis>"u"?window:globalThis,Rn=ze(()=>{const t=re(3);return{log:re((e,n,r=1)=>{var a;const i=(a=nN().VIRTUOSO_LOG_LEVEL)!=null?a:lt(t);r>=i&&console[tN[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",e,n)}),logLevel:t}},[],{singleton:!0});function Hn(t,e,n){return Oo(t,e,n).callbackRef}function Oo(t,e,n){const r=y.useRef(null);let a=o=>{};const i=y.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(o=>{const s=()=>{const l=o[0].target;l.offsetParent!==null&&t(l)};n?s():requestAnimationFrame(s)}):null,[t,n]);return a=o=>{o&&e?(i==null||i.observe(o),r.current=o):(r.current&&(i==null||i.unobserve(r.current)),r.current=null)},{callbackRef:a,ref:r}}function rN(t,e,n,r,a,i,o,s,l){const c=y.useCallback(d=>{const _=aN(d.children,e,s?"offsetWidth":"offsetHeight",a);let p=d.parentElement;for(;!p.dataset.virtuosoScroller;)p=p.parentElement;const m=p.lastElementChild.dataset.viewportType==="window";let E;m&&(E=p.ownerDocument.defaultView);const f=o?s?o.scrollLeft:o.scrollTop:m?s?E.scrollX||E.document.documentElement.scrollLeft:E.scrollY||E.document.documentElement.scrollTop:s?p.scrollLeft:p.scrollTop,g=o?s?o.scrollWidth:o.scrollHeight:m?s?E.document.documentElement.scrollWidth:E.document.documentElement.scrollHeight:s?p.scrollWidth:p.scrollHeight,S=o?s?o.offsetWidth:o.offsetHeight:m?s?E.innerWidth:E.innerHeight:s?p.offsetWidth:p.offsetHeight;r({scrollHeight:g,scrollTop:Math.max(f,0),viewportHeight:S}),i==null||i(s?ip("column-gap",getComputedStyle(d).columnGap,a):ip("row-gap",getComputedStyle(d).rowGap,a)),_!==null&&t(_)},[t,e,a,i,o,r,s]);return Oo(c,n,l)}function aN(t,e,n,r){const a=t.length;if(a===0)return null;const i=[];for(let o=0;o<a;o++){const s=t.item(o);if(s.dataset.index===void 0)continue;const l=parseInt(s.dataset.index),c=parseFloat(s.dataset.knownSize),d=e(s,n);if(d===0&&r("Zero-sized element, this should not happen",{child:s},xt.ERROR),d===c)continue;const _=i[i.length-1];i.length===0||_.size!==d||_.endIndex!==l-1?i.push({endIndex:l,size:d,startIndex:l}):i[i.length-1].endIndex++}return i}function ip(t,e,n){return e!=="normal"&&!(e!=null&&e.endsWith("px"))&&n(`${t} was not resolved to pixel value correctly`,e,xt.WARN),e==="normal"?0:parseInt(e??"0",10)}function op(t,e,n){const r=y.useRef(null),a=y.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let _,p;if(e){const m=e.getBoundingClientRect(),E=c.top-m.top;p=m.height-Math.max(0,E),_=E+e.scrollTop}else{const m=o.current.ownerDocument.defaultView;p=m.innerHeight-Math.max(0,c.top),_=c.top+m.scrollY}r.current={offsetTop:_,visibleHeight:p,visibleWidth:d},t(r.current)},[t,e]),{callbackRef:i,ref:o}=Oo(a,!0,n),s=y.useCallback(()=>{a(o.current)},[a,o]);return y.useEffect(()=>{var l;if(e){e.addEventListener("scroll",s);const c=new ResizeObserver(()=>{requestAnimationFrame(s)});return c.observe(e),()=>{e.removeEventListener("scroll",s),c.unobserve(e)}}else{const c=(l=o.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",s),c==null||c.addEventListener("resize",s),()=>{c==null||c.removeEventListener("scroll",s),c==null||c.removeEventListener("resize",s)}}},[s,e,o]),i}const Nt=ze(()=>{const t=He(),e=He(),n=re(0),r=He(),a=re(0),i=He(),o=He(),s=re(0),l=re(0),c=re(0),d=re(0),_=He(),p=He(),m=re(!1),E=re(!1),f=re(!1);return he(J(t,me(({scrollTop:g})=>g)),e),he(J(t,me(({scrollHeight:g})=>g)),o),he(e,a),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:s,horizontalDirection:E,scrollBy:p,scrollContainerState:t,scrollHeight:o,scrollingInProgress:m,scrollTo:_,scrollTop:e,skipAnimationFrameInResizeObserver:f,smoothScrollTargetReached:r,statefulScrollTop:a,viewportHeight:i}},[],{singleton:!0}),kr={lvl:0};function sp(t,e){const n=t.length;if(n===0)return[];let{index:r,value:a}=e(t[0]);const i=[];for(let o=1;o<n;o++){const{index:s,value:l}=e(t[o]);i.push({end:s-1,start:r,value:a}),r=s,a=l}return i.push({end:1/0,start:r,value:a}),i}function Ze(t){return t===kr}function Ur(t,e){if(!Ze(t))return e===t.k?t.v:e<t.k?Ur(t.l,e):Ur(t.r,e)}function jt(t,e,n="k"){if(Ze(t))return[-1/0,void 0];if(Number(t[n])===e)return[t.k,t.v];if(Number(t[n])<e){const r=jt(t.r,e,n);return r[0]===-1/0?[t.k,t.v]:r}return jt(t.l,e,n)}function Pt(t,e,n){return Ze(t)?dp(e,n,1):e===t.k?pt(t,{k:e,v:n}):e<t.k?up(pt(t,{l:Pt(t.l,e,n)})):up(pt(t,{r:Pt(t.r,e,n)}))}function dr(){return kr}function Ma(t,e,n){if(Ze(t))return[];const r=jt(t,e)[0];return iN(Io(t,r,n))}function yo(t,e){if(Ze(t))return kr;const{k:n,l:r,r:a}=t;if(e===n){if(Ze(r))return a;if(Ze(a))return r;{const[i,o]=cp(r);return La(pt(t,{k:i,l:lp(r),v:o}))}}else return e<n?La(pt(t,{l:yo(r,e)})):La(pt(t,{r:yo(a,e)}))}function qn(t){return Ze(t)?[]:[...qn(t.l),{k:t.k,v:t.v},...qn(t.r)]}function Io(t,e,n){if(Ze(t))return[];const{k:r,l:a,r:i,v:o}=t;let s=[];return r>e&&(s=s.concat(Io(a,e,n))),r>=e&&r<=n&&s.push({k:r,v:o}),r<=n&&(s=s.concat(Io(i,e,n))),s}function La(t){const{l:e,lvl:n,r}=t;if(r.lvl>=n-1&&e.lvl>=n-1)return t;if(n>r.lvl+1){if(Ao(e))return _p(pt(t,{lvl:n-1}));if(!Ze(e)&&!Ze(e.r))return pt(e.r,{l:pt(e,{r:e.r.l}),lvl:n,r:pt(t,{l:e.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(Ao(t))return xo(pt(t,{lvl:n-1}));if(!Ze(r)&&!Ze(r.l)){const a=r.l,i=Ao(a)?r.lvl-1:r.lvl;return pt(a,{l:pt(t,{lvl:n-1,r:a.l}),lvl:a.lvl+1,r:xo(pt(r,{l:a.r,lvl:i}))})}else throw new Error("Unexpected empty nodes")}}function pt(t,e){return dp(e.k!==void 0?e.k:t.k,e.v!==void 0?e.v:t.v,e.lvl!==void 0?e.lvl:t.lvl,e.l!==void 0?e.l:t.l,e.r!==void 0?e.r:t.r)}function lp(t){return Ze(t.r)?t.l:La(pt(t,{r:lp(t.r)}))}function Ao(t){return Ze(t)||t.lvl>t.r.lvl}function cp(t){return Ze(t.r)?[t.k,t.v]:cp(t.r)}function dp(t,e,n,r=kr,a=kr){return{k:t,l:r,lvl:n,r:a,v:e}}function up(t){return xo(_p(t))}function _p(t){const{l:e}=t;return!Ze(e)&&e.lvl===t.lvl?pt(e,{r:pt(t,{l:e.r})}):t}function xo(t){const{lvl:e,r:n}=t;return!Ze(n)&&!Ze(n.r)&&n.lvl===e&&n.r.lvl===e?pt(n,{l:pt(t,{r:n.l}),lvl:e+1}):t}function iN(t){return sp(t,({k:e,v:n})=>({index:e,value:n}))}function pp(t,e){return!!(t&&t.startIndex===e.startIndex&&t.endIndex===e.endIndex)}function Fr(t,e){return!!(t&&t[0]===e[0]&&t[1]===e[1])}const Do=ze(()=>({recalcInProgress:re(!1)}),[],{singleton:!0});function mp(t,e,n){return t[Pa(t,e,n)]}function Pa(t,e,n,r=0){let a=t.length-1;for(;r<=a;){const i=Math.floor((r+a)/2),o=t[i],s=n(o,e);if(s===0)return i;if(s===-1){if(a-r<2)return i-1;a=i-1}else{if(a===r)return i;r=i+1}}throw new Error(`Failed binary finding record in array - ${t.join(",")}, searched for ${e}`)}function oN(t,e,n,r){const a=Pa(t,e,r),i=Pa(t,n,r,a);return t.slice(a,i+1)}function vn(t,e){return Math.round(t.getBoundingClientRect()[e])}function ka(t){return!Ze(t.groupOffsetTree)}function wo({index:t},e){return e===t?0:e<t?-1:1}function sN(){return{groupIndices:[],groupOffsetTree:dr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:dr()}}function lN(t,e){let n=Ze(t)?0:1/0;for(const r of e){const{endIndex:a,size:i,startIndex:o}=r;if(n=Math.min(n,o),Ze(t)){t=Pt(t,0,i);continue}const s=Ma(t,o-1,a+1);if(s.some(gN(r)))continue;let l=!1,c=!1;for(const{end:d,start:_,value:p}of s)l?(a>=_||i===p)&&(t=yo(t,_)):(c=p!==i,l=!0),d>a&&a>=_&&p!==i&&(t=Pt(t,a+1,p));c&&(t=Pt(t,o,i))}return[t,n]}function cN(t){return typeof t.groupIndex<"u"}function dN({offset:t},e){return e===t?0:e<t?-1:1}function Br(t,e,n){if(e.length===0)return 0;const{index:r,offset:a,size:i}=mp(e,t,wo),o=t-r,s=i*o+(o-1)*n+a;return s>0?s+n:s}function gp(t,e){if(!ka(e))return t;let n=0;for(;e.groupIndices[n]<=t+n;)n++;return t+n}function Ep(t,e,n){if(cN(t))return e.groupIndices[t.groupIndex]+1;{const r=t.index==="LAST"?n:t.index;let a=gp(r,e);return a=Math.max(0,a,Math.min(n,a)),a}}function uN(t,e,n,r=0){return r>0&&(e=Math.max(e,mp(t,r,wo).offset)),sp(oN(t,e,n,dN),mN)}function _N(t,[e,n,r,a]){e.length>0&&r("received item sizes",e,xt.DEBUG);const i=t.sizeTree;let o=i,s=0;if(n.length>0&&Ze(i)&&e.length===2){const p=e[0].size,m=e[1].size;o=n.reduce((E,f)=>Pt(Pt(E,f,p),f+1,m),o)}else[o,s]=lN(o,e);if(o===i)return t;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:_}=Mo(t.offsetTree,s,o,a);return{groupIndices:n,groupOffsetTree:n.reduce((p,m)=>Pt(p,m,Br(m,_,a)),dr()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:_,sizeTree:o}}function pN(t){return qn(t).map(({k:e,v:n},r,a)=>{const i=a[r+1];return{endIndex:i?i.k-1:1/0,size:n,startIndex:e}})}function fp(t,e){let n=0,r=0;for(;n<t;)n+=e[r+1]-e[r]-1,r++;return r-(n===t?0:1)}function Mo(t,e,n,r){let a=t,i=0,o=0,s=0,l=0;if(e!==0){l=Pa(a,e-1,wo),s=a[l].offset;const c=jt(n,e-1);i=c[0],o=c[1],a.length&&a[l].size===jt(n,e)[1]&&(l-=1),a=a.slice(0,l+1)}else a=[];for(const{start:c,value:d}of Ma(n,e,1/0)){const _=c-i,p=_*o+s+_*r;a.push({index:c,offset:p,size:d}),i=c,s=p,o=d}return{lastIndex:i,lastOffset:s,lastSize:o,offsetTree:a}}function mN(t){return{index:t.index,value:t}}function gN(t){const{endIndex:e,size:n,startIndex:r}=t;return a=>a.start===r&&(a.end===e||a.end===1/0)&&a.value===n}const EN={offsetHeight:"height",offsetWidth:"width"},ln=ze(([{log:t},{recalcInProgress:e}])=>{const n=He(),r=He(),a=Tt(r,0),i=He(),o=He(),s=re(0),l=re([]),c=re(void 0),d=re(void 0),_=re((C,R)=>vn(C,EN[R])),p=re(void 0),m=re(0),E=sN(),f=Tt(J(n,Fe(l,t,m),sn(_N,E),rt()),E),g=Tt(J(l,rt(),sn((C,R)=>({current:R,prev:C.current}),{current:[],prev:[]}),me(({prev:C})=>C)),[]);he(J(l,Ae(C=>C.length>0),Fe(f,m),me(([C,R,N])=>{const O=C.reduce((I,D,M)=>Pt(I,D,Br(D,R.offsetTree,N)||M),dr());return{...R,groupIndices:C,groupOffsetTree:O}})),f),he(J(r,Fe(f),Ae(([C,{lastIndex:R}])=>C<R),me(([C,{lastIndex:R,lastSize:N}])=>[{endIndex:R,size:N,startIndex:C}])),n),he(c,d);const S=Tt(J(c,me(C=>C===void 0)),!0);he(J(d,Ae(C=>C!==void 0&&Ze(lt(f).sizeTree)),me(C=>[{endIndex:0,size:C,startIndex:0}])),n);const b=Lt(J(n,Fe(f),sn(({sizes:C},[R,N])=>({changed:N!==C,sizes:N}),{changed:!1,sizes:E}),me(C=>C.changed)));Qe(J(s,sn((C,R)=>({diff:C.prev-R,prev:R}),{diff:0,prev:0}),me(C=>C.diff)),C=>{const{groupIndices:R}=lt(f);if(C>0)Pe(e,!0),Pe(i,C+fp(C,R));else if(C<0){const N=lt(g);N.length>0&&(C-=fp(-C,N)),Pe(o,C)}}),Qe(J(s,Fe(t)),([C,R])=>{C<0&&R("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:s},xt.ERROR)});const h=Lt(i);he(J(i,Fe(f),me(([C,R])=>{const N=R.groupIndices.length>0,O=[],I=R.lastSize;if(N){const D=Ur(R.sizeTree,0);let M=0,Y=0;for(;M<C;){const F=R.groupIndices[Y],$=R.groupIndices.length===Y+1?1/0:R.groupIndices[Y+1]-F-1;O.push({endIndex:F,size:D,startIndex:F}),O.push({endIndex:F+1+$-1,size:I,startIndex:F+1}),Y++,M+=$+1}const K=qn(R.sizeTree);return M!==C&&K.shift(),K.reduce((F,{k:$,v:x})=>{let B=F.ranges;return F.prevSize!==0&&(B=[...F.ranges,{endIndex:$+C-1,size:F.prevSize,startIndex:F.prevIndex}]),{prevIndex:$+C,prevSize:x,ranges:B}},{prevIndex:C,prevSize:0,ranges:O}).ranges}return qn(R.sizeTree).reduce((D,{k:M,v:Y})=>({prevIndex:M+C,prevSize:Y,ranges:[...D.ranges,{endIndex:M+C-1,size:D.prevSize,startIndex:D.prevIndex}]}),{prevIndex:0,prevSize:I,ranges:[]}).ranges})),n);const v=Lt(J(o,Fe(f,m),me(([C,{offsetTree:R},N])=>{const O=-C;return Br(O,R,N)})));return he(J(o,Fe(f,m),me(([C,R,N])=>{if(R.groupIndices.length>0){if(Ze(R.sizeTree))return R;let O=dr();const I=lt(g);let D=0,M=0,Y=0;for(;D<-C;){Y=I[M];const K=I[M+1]-Y-1;M++,D+=K+1}if(O=qn(R.sizeTree).reduce((K,{k:F,v:$})=>Pt(K,Math.max(0,F+C),$),O),D!==-C){const K=Ur(R.sizeTree,Y);O=Pt(O,0,K);const F=jt(R.sizeTree,-C+1)[1];O=Pt(O,1,F)}return{...R,sizeTree:O,...Mo(R.offsetTree,0,O,N)}}else{const O=qn(R.sizeTree).reduce((I,{k:D,v:M})=>Pt(I,Math.max(0,D+C),M),dr());return{...R,sizeTree:O,...Mo(R.offsetTree,0,O,N)}}})),f),{beforeUnshiftWith:h,data:p,defaultItemSize:d,firstItemIndex:s,fixedItemSize:c,gap:m,groupIndices:l,itemSize:_,listRefresh:b,shiftWith:o,shiftWithOffset:v,sizeRanges:n,sizes:f,statefulTotalCount:a,totalCount:r,trackItemSizes:S,unshiftWith:i}},nt(Rn,Do),{singleton:!0});function fN(t){return t.reduce((e,n)=>(e.groupIndices.push(e.totalCount),e.totalCount+=n+1,e),{groupIndices:[],totalCount:0})}const Sp=ze(([{groupIndices:t,sizes:e,totalCount:n},{headerHeight:r,scrollTop:a}])=>{const i=He(),o=He(),s=Lt(J(i,me(fN)));return he(J(s,me(l=>l.totalCount)),n),he(J(s,me(l=>l.groupIndices)),t),he(J(ut(a,e,r),Ae(([l,c])=>ka(c)),me(([l,c,d])=>jt(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),rt(),me(l=>[l])),o),{groupCounts:i,topItemsIndexes:o}},nt(ln,Nt)),Nn=ze(([{log:t}])=>{const e=re(!1),n=Lt(J(e,Ae(r=>r),rt()));return Qe(e,r=>{r&<(t)("props updated",{},xt.DEBUG)}),{didMount:n,propsReady:e}},nt(Rn),{singleton:!0}),SN=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function bp(t){const e=typeof t=="number"?{index:t}:t;return e.align||(e.align="start"),(!e.behavior||!SN)&&(e.behavior="auto"),e.offset||(e.offset=0),e}const Gr=ze(([{gap:t,listRefresh:e,sizes:n,totalCount:r},{fixedFooterHeight:a,fixedHeaderHeight:i,footerHeight:o,headerHeight:s,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:_},{log:p}])=>{const m=He(),E=He(),f=re(0);let g=null,S=null,b=null;function h(){g&&(g(),g=null),b&&(b(),b=null),S&&(clearTimeout(S),S=null),Pe(l,!1)}return he(J(m,Fe(n,_,r,f,s,o,p),Fe(t,i,a),me(([[v,C,R,N,O,I,D,M],Y,K,F])=>{const $=bp(v),{align:x,behavior:B,offset:L}=$,U=N-1,z=Ep($,C,U);let W=Br(z,C.offsetTree,Y)+I;x==="end"?(W+=K+jt(C.sizeTree,z)[1]-R+F,z===U&&(W+=D)):x==="center"?W+=(K+jt(C.sizeTree,z)[1]-R+F)/2:W-=O,L&&(W+=L);const ne=q=>{h(),q?(M("retrying to scroll to",{location:v},xt.DEBUG),Pe(m,v)):(Pe(E,!0),M("list did not change, scroll successful",{},xt.DEBUG))};if(h(),B==="smooth"){let q=!1;b=Qe(e,X=>{q=q||X}),g=Qt(d,()=>{ne(q)})}else g=Qt(J(e,bN(150)),ne);return S=setTimeout(()=>{h()},1200),Pe(l,!0),M("scrolling from index to",{behavior:B,index:z,top:W},xt.DEBUG),{behavior:B,top:W}})),c),{scrollTargetReached:E,scrollToIndex:m,topListHeight:f}},nt(ln,Nt,Rn),{singleton:!0});function bN(t){return e=>{const n=setTimeout(()=>{e(!1)},t);return r=>{r&&(e(!0),clearTimeout(n))}}}function Lo(t,e){t==0?e():requestAnimationFrame(()=>{Lo(t-1,e)})}function Po(t,e){const n=e-1;return typeof t=="number"?t:t.index==="LAST"?n:t.index}const Yr=ze(([{defaultItemSize:t,listRefresh:e,sizes:n},{scrollTop:r},{scrollTargetReached:a,scrollToIndex:i},{didMount:o}])=>{const s=re(!0),l=re(0),c=re(!0);return he(J(o,Fe(l),Ae(([d,_])=>!!_),on(!1)),s),he(J(o,Fe(l),Ae(([d,_])=>!!_),on(!1)),c),Qe(J(ut(e,o),Fe(s,n,t,c),Ae(([[,d],_,{sizeTree:p},m,E])=>d&&(!Ze(p)||Ro(m))&&!_&&!E),Fe(l)),([,d])=>{Qt(a,()=>{Pe(c,!0)}),Lo(4,()=>{Qt(r,()=>{Pe(s,!0)}),Pe(i,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:s}},nt(ln,Nt,Gr,Nn),{singleton:!0});function Tp(t,e){return Math.abs(t-e)<1.01}const Hr="up",qr="down",TN="none",hN={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},CN=0,Vr=ze(([{footerHeight:t,headerHeight:e,scrollBy:n,scrollContainerState:r,scrollTop:a,viewportHeight:i}])=>{const o=re(!1),s=re(!0),l=He(),c=He(),d=re(4),_=re(CN),p=Tt(J(No(J(Ie(a),Yn(1),on(!0)),J(Ie(a),Yn(1),on(!1),rp(100))),rt()),!1),m=Tt(J(No(J(n,on(!0)),J(n,on(!1),rp(200))),rt()),!1);he(J(ut(Ie(a),Ie(_)),me(([b,h])=>b<=h),rt()),s),he(J(s,fn(50)),c);const E=Lt(J(ut(r,Ie(i),Ie(e),Ie(t),Ie(d)),sn((b,[{scrollHeight:h,scrollTop:v},C,R,N,O])=>{const I=v+C-h>-O,D={scrollHeight:h,scrollTop:v,viewportHeight:C};if(I){let Y,K;return v>b.state.scrollTop?(Y="SCROLLED_DOWN",K=b.state.scrollTop-v):(Y="SIZE_DECREASED",K=b.state.scrollTop-v||b.scrollTopDelta),{atBottom:!0,atBottomBecause:Y,scrollTopDelta:K,state:D}}let M;return D.scrollHeight>b.state.scrollHeight?M="SIZE_INCREASED":C<b.state.viewportHeight?M="VIEWPORT_HEIGHT_DECREASING":v<b.state.scrollTop?M="SCROLLING_UPWARDS":M="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:M,state:D}},hN),rt((b,h)=>b&&b.atBottom===h.atBottom))),f=Tt(J(r,sn((b,{scrollHeight:h,scrollTop:v,viewportHeight:C})=>{if(Tp(b.scrollHeight,h))return{changed:!1,jump:0,scrollHeight:h,scrollTop:v};{const R=h-(v+C)<1;return b.scrollTop!==v&&R?{changed:!0,jump:b.scrollTop-v,scrollHeight:h,scrollTop:v}:{changed:!0,jump:0,scrollHeight:h,scrollTop:v}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ae(b=>b.changed),me(b=>b.jump)),0);he(J(E,me(b=>b.atBottom)),o),he(J(o,fn(50)),l);const g=re(qr);he(J(r,me(({scrollTop:b})=>b),rt(),sn((b,h)=>lt(m)?{direction:b.direction,prevScrollTop:h}:{direction:h<b.prevScrollTop?Hr:qr,prevScrollTop:h},{direction:qr,prevScrollTop:0}),me(b=>b.direction)),g),he(J(r,fn(50),on(TN)),g);const S=re(0);return he(J(p,Ae(b=>!b),on(0)),S),he(J(a,fn(100),Fe(p),Ae(([b,h])=>!!h),sn(([b,h],[v])=>[h,v],[0,0]),me(([b,h])=>h-b)),S),{atBottomState:E,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:_,isAtBottom:o,isAtTop:s,isScrolling:p,lastJumpDueToItemResize:f,scrollDirection:g,scrollVelocity:S}},nt(Nt)),Ua="top",Fa="bottom",hp="none";function Cp(t,e,n){return typeof t=="number"?n===Hr&&e===Ua||n===qr&&e===Fa?t:0:n===Hr?e===Ua?t.main:t.reverse:e===Fa?t.main:t.reverse}function Rp(t,e){var n;return typeof t=="number"?t:(n=t[e])!=null?n:0}const ko=ze(([{deviation:t,fixedHeaderHeight:e,headerHeight:n,scrollTop:r,viewportHeight:a}])=>{const i=He(),o=re(0),s=re(0),l=re(0),c=Tt(J(ut(Ie(r),Ie(a),Ie(n),Ie(i,Fr),Ie(l),Ie(o),Ie(e),Ie(t),Ie(s)),me(([d,_,p,[m,E],f,g,S,b,h])=>{const v=d-b,C=g+S,R=Math.max(p-v,0);let N=hp;const O=Rp(h,Ua),I=Rp(h,Fa);return m-=b,m+=p+S,E+=p+S,E-=b,m>d+C-O&&(N=Hr),E<d-R+_+I&&(N=qr),N!==hp?[Math.max(v-p-Cp(f,Ua,N)-O,0),v-R-S+_+Cp(f,Fa,N)+I]:null}),Ae(d=>d!=null),rt(Fr)),[0,0]);return{increaseViewportBy:s,listBoundary:i,overscan:l,topListHeight:o,visibleRange:c}},nt(Nt),{singleton:!0});function RN(t,e,n){if(ka(e)){const r=gp(t,e);return[{index:jt(e.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:t,offset:0,size:0}]}const Uo={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Ba(t,e,n,r,a,i){const{lastIndex:o,lastOffset:s,lastSize:l}=a;let c=0,d=0;if(t.length>0){c=t[0].offset;const f=t[t.length-1];d=f.offset+f.size}const _=n-o,p=s+_*l+(_-1)*r,m=c,E=p-d;return{bottom:d,firstItemIndex:i,items:Np(t,a,i),offsetBottom:E,offsetTop:c,top:m,topItems:Np(e,a,i),topListHeight:e.reduce((f,g)=>g.size+f,0),totalCount:n}}function vp(t,e,n,r,a,i){let o=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-o>=t)break;o++}const s=t+o,l=Po(e,s),c=Array.from({length:s}).map((d,_)=>({data:i[_+l],index:_+l,offset:0,size:0}));return Ba(c,[],s,a,n,r)}function Np(t,e,n){if(t.length===0)return[];if(!ka(e))return t.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=t[0].index,a=t[t.length-1].index,i=[],o=Ma(e.groupOffsetTree,r,a);let s,l=0;for(const c of t){(!s||s.end<c.index)&&(s=o.shift(),l=e.groupIndices.indexOf(s.start));let d;c.index===s.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},i.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return i}const Vn=ze(([{data:t,firstItemIndex:e,gap:n,sizes:r,totalCount:a},i,{listBoundary:o,topListHeight:s,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:_},p,{didMount:m},{recalcInProgress:E}])=>{const f=re([]),g=re(0),S=He();he(i.topItemsIndexes,f);const b=Tt(J(ut(m,E,Ie(l,Fr),Ie(a),Ie(r),Ie(c),d,Ie(f),Ie(e),Ie(n),t),Ae(([R,N,,O,,,,,,,I])=>{const D=I&&I.length!==O;return R&&!N&&!D}),me(([,,[R,N],O,I,D,M,Y,K,F,$])=>{const x=I,{offsetTree:B,sizeTree:L}=x,U=lt(g);if(O===0)return{...Uo,totalCount:O};if(R===0&&N===0)return U===0?{...Uo,totalCount:O}:vp(U,D,I,K,F,$||[]);if(Ze(L))return U>0?null:Ba(RN(Po(D,O),x,$),[],O,F,x,K);const z=[];if(Y.length>0){const se=Y[0],ce=Y[Y.length-1];let H=0;for(const P of Ma(L,se,ce)){const V=P.value,Z=Math.max(P.start,se),ie=Math.min(P.end,ce);for(let oe=Z;oe<=ie;oe++)z.push({data:$==null?void 0:$[oe],index:oe,offset:H,size:V}),H+=V}}if(!M)return Ba([],z,O,F,x,K);const W=Y.length>0?Y[Y.length-1]+1:0,ne=uN(B,R,N,W);if(ne.length===0)return null;const q=O-1,X=wa([],se=>{for(const ce of ne){const H=ce.value;let P=H.offset,V=ce.start;const Z=H.size;if(H.offset<R){V+=Math.floor((R-H.offset+F)/(Z+F));const oe=V-ce.start;P+=oe*Z+oe*F}V<W&&(P+=(W-V)*Z,V=W);const ie=Math.min(ce.end,q);for(let oe=V;oe<=ie&&!(P>=N);oe++)se.push({data:$==null?void 0:$[oe],index:oe,offset:P,size:Z}),P+=Z+F}});return Ba(X,z,O,F,x,K)}),Ae(R=>R!==null),rt()),Uo);he(J(t,Ae(Ro),me(R=>R==null?void 0:R.length)),a),he(J(b,me(R=>R.topListHeight)),_),he(_,s),he(J(b,me(R=>[R.top,R.bottom])),o),he(J(b,me(R=>R.items)),S);const h=Lt(J(b,Ae(({items:R})=>R.length>0),Fe(a,t),Ae(([{items:R},N])=>R[R.length-1].originalIndex===N-1),me(([,R,N])=>[R-1,N]),rt(Fr),me(([R])=>R))),v=Lt(J(b,fn(200),Ae(({items:R,topItems:N})=>R.length>0&&R[0].originalIndex===N.length),me(({items:R})=>R[0].index),rt())),C=Lt(J(b,Ae(({items:R})=>R.length>0),me(({items:R})=>{let N=0,O=R.length-1;for(;R[N].type==="group"&&N<O;)N++;for(;R[O].type==="group"&&O>N;)O--;return{endIndex:R[O].index,startIndex:R[N].index}}),rt(pp)));return{endReached:h,initialItemCount:g,itemsRendered:S,listState:b,rangeChanged:C,startReached:v,topItemsIndexes:f,...p}},nt(ln,Sp,ko,Yr,Gr,Vr,Nn,Do),{singleton:!0}),Op=ze(([{fixedFooterHeight:t,fixedHeaderHeight:e,footerHeight:n,headerHeight:r},{listState:a}])=>{const i=He(),o=Tt(J(ut(n,t,r,e,a),me(([s,l,c,d,_])=>s+l+c+d+_.offsetBottom+_.bottom)),0);return he(Ie(o),i),{totalListHeight:o,totalListHeightChanged:i}},nt(Nt,Vn),{singleton:!0}),vN=ze(([{viewportHeight:t},{totalListHeight:e}])=>{const n=re(!1),r=Tt(J(ut(n,t,e),Ae(([a])=>a),me(([,a,i])=>Math.max(0,a-i)),fn(0),rt()),0);return{alignToBottom:n,paddingTopAddition:r}},nt(Nt,Op),{singleton:!0}),yp=ze(()=>({context:re(null)})),NN=({itemBottom:t,itemTop:e,locationParams:{align:n,behavior:r,...a},viewportBottom:i,viewportTop:o})=>e<o?{...a,align:n??"start",behavior:r}:t>i?{...a,align:n??"end",behavior:r}:null,Ip=ze(([{gap:t,sizes:e,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:a,headerHeight:i,scrollingInProgress:o,scrollTop:s,viewportHeight:l},{scrollToIndex:c}])=>{const d=He();return he(J(d,Fe(e,l,n,i,a,r,s),Fe(t),me(([[_,p,m,E,f,g,S,b],h])=>{const{align:v,behavior:C,calculateViewLocation:R=NN,done:N,...O}=_,I=Ep(_,p,E-1),D=Br(I,p.offsetTree,h)+f+g,M=D+jt(p.sizeTree,I)[1],Y=b+g,K=b+m-S,F=R({itemBottom:M,itemTop:D,locationParams:{align:v,behavior:C,...O},viewportBottom:K,viewportTop:Y});return F?N&&Qt(J(o,Ae($=>!$),Yn(lt(o)?1:2)),N):N&&N(),F}),Ae(_=>_!==null)),c),{scrollIntoView:d}},nt(ln,Nt,Gr,Vn,Rn),{singleton:!0});function Ap(t){return t?t==="smooth"?"smooth":"auto":!1}const ON=(t,e)=>typeof t=="function"?Ap(t(e)):e&&Ap(t),yN=ze(([{listRefresh:t,totalCount:e,fixedItemSize:n,data:r},{atBottomState:a,isAtBottom:i},{scrollToIndex:o},{scrolledToInitialItem:s},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:_},{context:p},{scrollIntoView:m}])=>{const E=re(!1),f=He();let g=null;function S(C){Pe(o,{align:"end",behavior:C,index:"LAST"})}Qe(J(ut(J(Ie(e),Yn(1)),l),Fe(Ie(E),i,s,_),me(([[C,R],N,O,I,D])=>{let M=R&&I,Y="auto";return M&&(Y=ON(N,O||D),M=M&&!!Y),{followOutputBehavior:Y,shouldFollow:M,totalCount:C}}),Ae(({shouldFollow:C})=>C)),({followOutputBehavior:C,totalCount:R})=>{g&&(g(),g=null),lt(n)?requestAnimationFrame(()=>{lt(d)("following output to ",{totalCount:R},xt.DEBUG),S(C)}):g=Qt(t,()=>{lt(d)("following output to ",{totalCount:R},xt.DEBUG),S(C),g=null})});function b(C){const R=Qt(a,N=>{C&&!N.atBottom&&N.notAtBottomBecause==="SIZE_INCREASED"&&!g&&(lt(d)("scrolling to bottom due to increased size",{},xt.DEBUG),S("auto"))});setTimeout(R,100)}Qe(J(ut(Ie(E),e,c),Ae(([C,,R])=>C&&R),sn(({value:C},[,R])=>({refreshed:C===R,value:R}),{refreshed:!1,value:0}),Ae(({refreshed:C})=>C),Fe(E,e)),([,C])=>{lt(s)&&b(C!==!1)}),Qe(f,()=>{b(lt(E)!==!1)}),Qe(ut(Ie(E),a),([C,R])=>{C&&!R.atBottom&&R.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&S("auto")});const h=re(null),v=He();return he(No(J(Ie(r),me(C=>{var R;return(R=C==null?void 0:C.length)!=null?R:0})),J(Ie(e))),v),Qe(J(ut(J(v,Yn(1)),l),Fe(Ie(h),s,_,p),me(([[C,R],N,O,I,D])=>R&&O&&(N==null?void 0:N({context:D,totalCount:C,scrollingInProgress:I}))),Ae(C=>!!C),fn(0)),C=>{g&&(g(),g=null),lt(n)?requestAnimationFrame(()=>{lt(d)("scrolling into view",{}),Pe(m,C)}):g=Qt(t,()=>{lt(d)("scrolling into view",{}),Pe(m,C),g=null})}),{autoscrollToBottom:f,followOutput:E,scrollIntoViewOnChange:h}},nt(ln,Vr,Gr,Yr,Nn,Rn,Nt,yp,Ip)),IN=ze(([{data:t,firstItemIndex:e,gap:n,sizes:r},{initialTopMostItemIndex:a},{initialItemCount:i,listState:o},{didMount:s}])=>(he(J(s,Fe(i),Ae(([,l])=>l!==0),Fe(a,r,e,n,t),me(([[,l],c,d,_,p,m=[]])=>vp(l,c,d,_,p,m))),o),{}),nt(ln,Yr,Vn,Nn),{singleton:!0}),AN=ze(([{didMount:t},{scrollTo:e},{listState:n}])=>{const r=re(0);return Qe(J(t,Fe(r),Ae(([,a])=>a!==0),me(([,a])=>({top:a}))),a=>{Qt(J(n,Yn(1),Ae(i=>i.items.length>1)),()=>{requestAnimationFrame(()=>{Pe(e,a)})})}),{initialScrollTop:r}},nt(Nn,Nt,Vn),{singleton:!0}),xp=ze(([{scrollVelocity:t}])=>{const e=re(!1),n=He(),r=re(!1);return he(J(t,Fe(r,e,n),Ae(([a,i])=>!!i),me(([a,i,o,s])=>{const{enter:l,exit:c}=i;if(o){if(c(a,s))return!1}else if(l(a,s))return!0;return o}),rt()),e),Qe(J(ut(e,t,n),Fe(r)),([[a,i,o],s])=>{a&&s&&s.change&&s.change(i,o)}),{isSeeking:e,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:t}},nt(Vr),{singleton:!0}),Fo=ze(([{scrollContainerState:t,scrollTo:e}])=>{const n=He(),r=He(),a=He(),i=re(!1),o=re(void 0);return he(J(ut(n,r),me(([{scrollHeight:s,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:s,scrollTop:Math.max(0,l-d),viewportHeight:c}))),t),he(J(e,Fe(r),me(([s,{offsetTop:l}])=>({...s,top:s.top+l}))),a),{customScrollParent:o,useWindowScroll:i,windowScrollContainerState:n,windowScrollTo:a,windowViewportRect:r}},nt(Nt)),xN=ze(([{sizeRanges:t,sizes:e},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:a},{didMount:i},{useWindowScroll:o,windowScrollContainerState:s,windowViewportRect:l}])=>{const c=He(),d=re(void 0),_=re(null),p=re(null);return he(s,_),he(l,p),Qe(J(c,Fe(e,r,o,_,p,n)),([m,E,f,g,S,b,h])=>{const v=pN(E.sizeTree);g&&S!==null&&b!==null&&(f=S.scrollTop-b.offsetTop),f-=h,m({ranges:v,scrollTop:f})}),he(J(d,Ae(Ro),me(DN)),a),he(J(i,Fe(d),Ae(([,m])=>m!==void 0),rt(),me(([,m])=>m.ranges)),t),{getState:c,restoreStateFrom:d}},nt(ln,Nt,Yr,Nn,Fo));function DN(t){return{align:"start",index:0,offset:t.scrollTop}}const wN=ze(([{topItemsIndexes:t}])=>{const e=re(0);return he(J(e,Ae(n=>n>=0),me(n=>Array.from({length:n}).map((r,a)=>a))),t),{topItemCount:e}},nt(Vn));function Dp(t){let e=!1,n;return()=>(e||(e=!0,n=t()),n)}const MN=Dp(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),LN=ze(([{deviation:t,scrollBy:e,scrollingInProgress:n,scrollTop:r},{isAtBottom:a,isScrolling:i,lastJumpDueToItemResize:o,scrollDirection:s},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:_,sizes:p},{log:m},{recalcInProgress:E}])=>{const f=Lt(J(l,Fe(o),sn(([,S,b,h],[{bottom:v,items:C,offsetBottom:R,totalCount:N},O])=>{const I=v+R;let D=0;return b===N&&S.length>0&&C.length>0&&(C[0].originalIndex===0&&S[0].originalIndex===0||(D=I-h,D!==0&&(D+=O))),[D,C,N,I]},[0,[],0,0]),Ae(([S])=>S!==0),Fe(r,s,n,a,m,E),Ae(([,S,b,h,,,v])=>!v&&!h&&S!==0&&b===Hr),me(([[S],,,,,b])=>(b("Upward scrolling compensation",{amount:S},xt.DEBUG),S))));function g(S){S>0?(Pe(e,{behavior:"auto",top:-S}),Pe(t,0)):(Pe(t,0),Pe(e,{behavior:"auto",top:-S}))}return Qe(J(f,Fe(t,i)),([S,b,h])=>{h&&MN()?Pe(t,b-S):g(-S)}),Qe(J(ut(Tt(i,!1),t,E),Ae(([S,b,h])=>!S&&!h&&b!==0),me(([S,b])=>b),fn(1)),g),he(J(_,me(S=>({top:-S}))),e),Qe(J(c,Fe(p,d),me(([S,{groupIndices:b,lastSize:h,sizeTree:v},C])=>{function R(N){return N*(h+C)}if(b.length===0)return R(S);{let N=0;const O=Ur(v,0);let I=0,D=0;for(;I<S;){I++,N+=O;let M=b.length===D+1?1/0:b[D+1]-b[D]-1;I+M>S&&(N-=O,M=S-I+1),I+=M,N+=R(M),D++}return N}})),S=>{Pe(t,S),requestAnimationFrame(()=>{Pe(e,{top:S}),requestAnimationFrame(()=>{Pe(t,0),Pe(E,!1)})})}),{deviation:t}},nt(Nt,Vr,Vn,ln,Rn,Do)),PN=ze(([t,e,n,r,a,i,o,s,l,c,d])=>({...t,...e,...n,...r,...a,...i,...o,...s,...l,...c,...d}),nt(ko,IN,Nn,xp,Op,AN,vN,Fo,Ip,Rn,yp)),wp=ze(([{data:t,defaultItemSize:e,firstItemIndex:n,fixedItemSize:r,gap:a,groupIndices:i,itemSize:o,sizeRanges:s,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:_},{initialItemFinalLocationReached:p,initialTopMostItemIndex:m,scrolledToInitialItem:E},f,g,S,{listState:b,topItemsIndexes:h,...v},{scrollToIndex:C},R,{topItemCount:N},{groupCounts:O},I])=>(he(v.rangeChanged,I.scrollSeekRangeChanged),he(J(I.windowViewportRect,me(D=>D.visibleHeight)),f.viewportHeight),{data:t,defaultItemHeight:e,firstItemIndex:n,fixedItemHeight:r,gap:a,groupCounts:O,initialItemFinalLocationReached:p,initialTopMostItemIndex:m,scrolledToInitialItem:E,sizeRanges:s,topItemCount:N,topItemsIndexes:h,totalCount:d,...S,groupIndices:i,itemSize:o,listState:b,scrollToIndex:C,statefulTotalCount:c,trackItemSizes:_,...v,...I,...f,sizes:l,...g}),nt(ln,Yr,Nt,xN,yN,Vn,Gr,LN,wN,Sp,PN));function kN(t,e){const n={},r={};let a=0;const i=t.length;for(;a<i;)r[t[a]]=1,a+=1;for(const o in e)Object.hasOwn(r,o)||(n[o]=e[o]);return n}const Ga=typeof document<"u"?y.useLayoutEffect:y.useEffect;function Mp(t,e,n){const r=Object.keys(e.required||{}),a=Object.keys(e.optional||{}),i=Object.keys(e.methods||{}),o=Object.keys(e.events||{}),s=y.createContext({});function l(g,S){g.propsReady&&Pe(g.propsReady,!1);for(const b of r){const h=g[e.required[b]];Pe(h,S[b])}for(const b of a)if(b in S){const h=g[e.optional[b]];Pe(h,S[b])}g.propsReady&&Pe(g.propsReady,!0)}function c(g){return i.reduce((S,b)=>(S[b]=h=>{const v=g[e.methods[b]];Pe(v,h)},S),{})}function d(g){return o.reduce((S,b)=>(S[b]=Zv(g[e.events[b]]),S),{})}const _=y.forwardRef((g,S)=>{const{children:b,...h}=g,[v]=y.useState(()=>wa(eN(t),N=>{l(N,h)})),[C]=y.useState(np(d,v));Ga(()=>{for(const N of o)N in h&&Qe(C[N],h[N]);return()=>{Object.values(C).map(vo)}},[h,C,v]),Ga(()=>{l(v,h)}),y.useImperativeHandle(S,ep(c(v)));const R=n;return u.jsx(s.Provider,{value:v,children:n?u.jsx(R,{...kN([...r,...a,...o],h),children:b}):b})}),p=g=>{const S=y.useContext(s);return y.useCallback(b=>{Pe(S[g],b)},[S,g])},m=g=>{const S=y.useContext(s)[g],b=y.useCallback(h=>Qe(S,h),[S]);return y.useSyncExternalStore(b,()=>lt(S),()=>lt(S))},E=g=>{const S=y.useContext(s)[g],[b,h]=y.useState(np(lt,S));return Ga(()=>Qe(S,v=>{v!==b&&h(ep(v))}),[S,b]),b},f=y.version.startsWith("18")?m:E;return{Component:_,useEmitter:(g,S)=>{const b=y.useContext(s)[g];Ga(()=>Qe(b,S),[S,b])},useEmitterValue:f,usePublisher:p}}const Lp=y.createContext(void 0),Pp=y.createContext(void 0),kp=typeof document<"u"?y.useLayoutEffect:y.useEffect;function Bo(t){return"self"in t}function UN(t){return"body"in t}function Up(t,e,n,r=cr,a,i){const o=y.useRef(null),s=y.useRef(null),l=y.useRef(null),c=y.useCallback(p=>{let m,E,f;const g=p.target;if(UN(g)||Bo(g)){const b=Bo(g)?g:g.defaultView;f=i?b.scrollX:b.scrollY,m=i?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,E=i?b.innerWidth:b.innerHeight}else f=i?g.scrollLeft:g.scrollTop,m=i?g.scrollWidth:g.scrollHeight,E=i?g.offsetWidth:g.offsetHeight;const S=()=>{t({scrollHeight:m,scrollTop:Math.max(f,0),viewportHeight:E})};p.suppressFlushSync?S():ro.flushSync(S),s.current!==null&&(f===s.current||f<=0||f===m-E)&&(s.current=null,e(!0),l.current&&(clearTimeout(l.current),l.current=null))},[t,e,i]);y.useEffect(()=>{const p=a||o.current;return r(a||o.current),c({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",c,{passive:!0}),()=>{r(null),p.removeEventListener("scroll",c)}},[o,c,n,r,a]);function d(p){const m=o.current;if(!m||(i?"offsetWidth"in m&&m.offsetWidth===0:"offsetHeight"in m&&m.offsetHeight===0))return;const E=p.behavior==="smooth";let f,g,S;Bo(m)?(g=Math.max(vn(m.document.documentElement,i?"width":"height"),i?m.document.documentElement.scrollWidth:m.document.documentElement.scrollHeight),f=i?m.innerWidth:m.innerHeight,S=i?window.scrollX:window.scrollY):(g=m[i?"scrollWidth":"scrollHeight"],f=vn(m,i?"width":"height"),S=m[i?"scrollLeft":"scrollTop"]);const b=g-f;if(p.top=Math.ceil(Math.max(Math.min(b,p.top),0)),Tp(f,g)||p.top===S){t({scrollHeight:g,scrollTop:S,viewportHeight:f}),E&&e(!0);return}E?(s.current=p.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,s.current=null,e(!0)},1e3)):s.current=null,i&&(p={behavior:p.behavior,left:p.top}),m.scrollTo(p)}function _(p){i&&(p={behavior:p.behavior,left:p.top}),o.current.scrollBy(p)}return{scrollByCallback:_,scrollerRef:o,scrollToCallback:d}}const Go="-webkit-sticky",Fp="sticky",Yo=Dp(()=>{if(typeof document>"u")return Fp;const t=document.createElement("div");return t.style.position=Go,t.style.position===Go?Go:Fp});function Ho(t){return t}const FN=ze(()=>{const t=re(s=>`Item ${s}`),e=re(s=>`Group ${s}`),n=re({}),r=re(Ho),a=re("div"),i=re(cr),o=(s,l=null)=>Tt(J(n,me(c=>c[s]),rt()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:o("EmptyPlaceholder"),FooterComponent:o("Footer"),GroupComponent:o("Group","div"),groupContent:e,HeaderComponent:o("Header"),HeaderFooterTag:a,ItemComponent:o("Item","div"),itemContent:t,ListComponent:o("List","div"),ScrollerComponent:o("Scroller","div"),scrollerRef:i,ScrollSeekPlaceholder:o("ScrollSeekPlaceholder"),TopItemListComponent:o("TopItemList")}}),BN=ze(([t,e])=>({...t,...e}),nt(wp,FN)),GN=({height:t})=>u.jsx("div",{style:{height:t}}),YN={overflowAnchor:"none",position:Yo(),zIndex:1},Bp={overflowAnchor:"none"},HN={...Bp,display:"inline-block",height:"100%"},Gp=y.memo(function({showTopList:t=!1}){const e=we("listState"),n=Ht("sizeRanges"),r=we("useWindowScroll"),a=we("customScrollParent"),i=Ht("windowScrollContainerState"),o=Ht("scrollContainerState"),s=a||r?i:o,l=we("itemContent"),c=we("context"),d=we("groupContent"),_=we("trackItemSizes"),p=we("itemSize"),m=we("log"),E=Ht("gap"),f=we("horizontalDirection"),{callbackRef:g}=rN(n,p,_,t?cr:s,m,E,a,f,we("skipAnimationFrameInResizeObserver")),[S,b]=y.useState(0);qo("deviation",F=>{S!==F&&b(F)});const h=we("EmptyPlaceholder"),v=we("ScrollSeekPlaceholder")||GN,C=we("ListComponent"),R=we("ItemComponent"),N=we("GroupComponent"),O=we("computeItemKey"),I=we("isSeeking"),D=we("groupIndices").length>0,M=we("alignToBottom"),Y=we("initialItemFinalLocationReached"),K=t?{}:{boxSizing:"border-box",...f?{display:"inline-block",height:"100%",marginLeft:S!==0?S:M?"auto":0,paddingLeft:e.offsetTop,paddingRight:e.offsetBottom,whiteSpace:"nowrap"}:{marginTop:S!==0?S:M?"auto":0,paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},...Y?{}:{visibility:"hidden"}};return!t&&e.totalCount===0&&h?u.jsx(h,{...ht(h,c)}):u.jsx(C,{...ht(C,c),"data-testid":t?"virtuoso-top-item-list":"virtuoso-item-list",ref:g,style:K,children:(t?e.topItems:e.items).map(F=>{const $=F.originalIndex,x=O($+e.firstItemIndex,F.data,c);return I?y.createElement(v,{...ht(v,c),height:F.size,index:F.index,key:x,type:F.type||"item",...F.type==="group"?{}:{groupIndex:F.groupIndex}}):F.type==="group"?y.createElement(N,{...ht(N,c),"data-index":$,"data-item-index":F.index,"data-known-size":F.size,key:x,style:YN},d(F.index,c)):y.createElement(R,{...ht(R,c),...$N(R,F.data),"data-index":$,"data-item-group-index":F.groupIndex,"data-item-index":F.index,"data-known-size":F.size,key:x,style:f?HN:Bp},D?l(F.index,F.groupIndex,F.data,c):l(F.index,F.data,c))})})}),qN={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},VN={outline:"none",overflowX:"auto",position:"relative"},Ya=t=>({height:"100%",position:"absolute",top:0,width:"100%",...t?{display:"flex",flexDirection:"column"}:{}}),zN={position:Yo(),top:0,width:"100%",zIndex:1};function ht(t,e){if(typeof t!="string")return{context:e}}function $N(t,e){return{item:typeof t=="string"?void 0:e}}const WN=y.memo(function(){const t=we("HeaderComponent"),e=Ht("headerHeight"),n=we("HeaderFooterTag"),r=Hn(y.useMemo(()=>i=>{e(vn(i,"height"))},[e]),!0,we("skipAnimationFrameInResizeObserver")),a=we("context");return t?u.jsx(n,{ref:r,children:u.jsx(t,{...ht(t,a)})}):null}),KN=y.memo(function(){const t=we("FooterComponent"),e=Ht("footerHeight"),n=we("HeaderFooterTag"),r=Hn(y.useMemo(()=>i=>{e(vn(i,"height"))},[e]),!0,we("skipAnimationFrameInResizeObserver")),a=we("context");return t?u.jsx(n,{ref:r,children:u.jsx(t,{...ht(t,a)})}):null});function Yp({useEmitter:t,useEmitterValue:e,usePublisher:n}){return y.memo(function({children:r,style:a,context:i,...o}){const s=n("scrollContainerState"),l=e("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=e("scrollerRef"),_=e("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:m,scrollToCallback:E}=Up(s,c,l,d,void 0,_);return t("scrollTo",E),t("scrollBy",p),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:m,style:{..._?VN:qN,...a},tabIndex:0,...o,...ht(l,i),children:r})})}function Hp({useEmitter:t,useEmitterValue:e,usePublisher:n}){return y.memo(function({children:r,style:a,context:i,...o}){const s=n("windowScrollContainerState"),l=e("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=e("totalListHeight"),_=e("deviation"),p=e("customScrollParent"),m=y.useRef(null),E=e("scrollerRef"),{scrollByCallback:f,scrollerRef:g,scrollToCallback:S}=Up(s,c,l,E,p);return kp(()=>{var b;return g.current=p||((b=m.current)==null?void 0:b.ownerDocument.defaultView),()=>{g.current=null}},[g,p]),t("windowScrollTo",S),t("scrollBy",f),u.jsx(l,{ref:m,"data-virtuoso-scroller":!0,style:{position:"relative",...a,...d!==0?{height:d+_}:{}},...o,...ht(l,i),children:r})})}const QN=({children:t})=>{const e=y.useContext(Lp),n=Ht("viewportHeight"),r=Ht("fixedItemHeight"),a=we("alignToBottom"),i=we("horizontalDirection"),o=y.useMemo(()=>tp(n,l=>vn(l,i?"width":"height")),[n,i]),s=Hn(o,!0,we("skipAnimationFrameInResizeObserver"));return y.useEffect(()=>{e&&(n(e.viewportHeight),r(e.itemHeight))},[e,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:s,style:Ya(a),children:t})},jN=({children:t})=>{const e=y.useContext(Lp),n=Ht("windowViewportRect"),r=Ht("fixedItemHeight"),a=we("customScrollParent"),i=op(n,a,we("skipAnimationFrameInResizeObserver")),o=we("alignToBottom");return y.useEffect(()=>{e&&(r(e.itemHeight),n({offsetTop:0,visibleHeight:e.viewportHeight,visibleWidth:100}))},[e,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:i,style:Ya(o),children:t})},XN=({children:t})=>{const e=we("TopItemListComponent")||"div",n=we("headerHeight"),r={...zN,marginTop:`${n}px`},a=we("context");return u.jsx(e,{style:r,...ht(e,a),children:t})},ZN=y.memo(function(t){const e=we("useWindowScroll"),n=we("topItemsIndexes").length>0,r=we("customScrollParent"),a=we("context");return u.jsxs(r||e?tO:eO,{...t,context:a,children:[n&&u.jsx(XN,{children:u.jsx(Gp,{showTopList:!0})}),u.jsxs(r||e?jN:QN,{children:[u.jsx(WN,{}),u.jsx(Gp,{}),u.jsx(KN,{})]})]})}),{Component:JN,useEmitter:qo,useEmitterValue:we,usePublisher:Ht}=Mp(BN,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},ZN),eO=Yp({useEmitter:qo,useEmitterValue:we,usePublisher:Ht}),tO=Hp({useEmitter:qo,useEmitterValue:we,usePublisher:Ht}),nO=JN;nt(wp,ze(()=>{const t=re(c=>u.jsxs("td",{children:["Item $",c]})),e=re(null),n=re(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=re(null),a=re(null),i=re({}),o=re(Ho),s=re(cr),l=(c,d=null)=>Tt(J(i,me(_=>_[c]),rt()),d);return{components:i,computeItemKey:o,context:e,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:a,fixedHeaderContent:r,itemContent:t,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder"),TableBodyComponent:l("TableBody","tbody"),TableComponent:l("Table","table"),TableFooterComponent:l("TableFoot","tfoot"),TableHeadComponent:l("TableHead","thead"),TableRowComponent:l("TableRow","tr"),GroupComponent:l("Group","tr")}})),Yo();const qp={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},rO={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Vp,floor:Ha,max:zr,min:Vo,round:zp}=Math;function $p(t,e,n){return Array.from({length:e-t+1}).map((r,a)=>({data:n===null?null:n[a+t],index:a+t}))}function aO(t){return{...rO,items:t}}function qa(t,e){return t&&t.width===e.width&&t.height===e.height}function iO(t,e){return t&&t.column===e.column&&t.row===e.row}const oO=ze(([{increaseViewportBy:t,listBoundary:e,overscan:n,visibleRange:r},{footerHeight:a,headerHeight:i,scrollBy:o,scrollContainerState:s,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:_},p,m,{didMount:E,propsReady:f},{customScrollParent:g,useWindowScroll:S,windowScrollContainerState:b,windowScrollTo:h,windowViewportRect:v},C])=>{const R=re(0),N=re(0),O=re(qp),I=re({height:0,width:0}),D=re({height:0,width:0}),M=He(),Y=He(),K=re(0),F=re(null),$=re({column:0,row:0}),x=He(),B=He(),L=re(!1),U=re(0),z=re(!0),W=re(!1),ne=re(!1);Qe(J(E,Fe(U),Ae(([P,V])=>!!V)),()=>{Pe(z,!1)}),Qe(J(ut(E,z,D,I,U,W),Ae(([P,V,Z,ie,,oe])=>P&&!V&&Z.height!==0&&ie.height!==0&&!oe)),([,,,,P])=>{Pe(W,!0),Lo(1,()=>{Pe(M,P)}),Qt(J(c),()=>{Pe(e,[0,0]),Pe(z,!0)})}),he(J(B,Ae(P=>P!=null&&P.scrollTop>0),on(0)),N),Qe(J(E,Fe(B),Ae(([,P])=>P!=null)),([,P])=>{P&&(Pe(I,P.viewport),Pe(D,P.item),Pe($,P.gap),P.scrollTop>0&&(Pe(L,!0),Qt(J(c,Yn(1)),V=>{Pe(L,!1)}),Pe(l,{top:P.scrollTop})))}),he(J(I,me(({height:P})=>P)),_),he(J(ut(Ie(I,qa),Ie(D,qa),Ie($,(P,V)=>P&&P.column===V.column&&P.row===V.row),Ie(c)),me(([P,V,Z,ie])=>({gap:Z,item:V,scrollTop:ie,viewport:P}))),x),he(J(ut(Ie(R),r,Ie($,iO),Ie(D,qa),Ie(I,qa),Ie(F),Ie(N),Ie(L),Ie(z),Ie(U)),Ae(([,,,,,,,P])=>!P),me(([P,[V,Z],ie,oe,Ne,Ue,Oe,,de,Me])=>{const{column:ae,row:fe}=ie,{height:Te,width:Se}=oe,{width:tt}=Ne;if(Oe===0&&(P===0||tt===0))return qp;if(Se===0){const Ce=Po(Me,P),je=Ce+Math.max(Oe-1,0);return aO($p(Ce,je,Ue))}const We=Wp(tt,Se,ae);let ct,et;de?V===0&&Z===0&&Oe>0?(ct=0,et=Oe-1):(ct=We*Ha((V+fe)/(Te+fe)),et=We*Vp((Z+fe)/(Te+fe))-1,et=Vo(P-1,zr(et,We-1)),ct=Vo(et,zr(0,ct))):(ct=0,et=-1);const te=$p(ct,et,Ue),{bottom:k,top:j}=Kp(Ne,ie,oe,te),be=Vp(P/We),ke=be*Te+(be-1)*fe-k;return{bottom:k,itemHeight:Te,items:te,itemWidth:Se,offsetBottom:ke,offsetTop:j,top:j}})),O),he(J(F,Ae(P=>P!==null),me(P=>P.length)),R),he(J(ut(I,D,O,$),Ae(([P,V,{items:Z}])=>Z.length>0&&V.height!==0&&P.height!==0),me(([P,V,{items:Z},ie])=>{const{bottom:oe,top:Ne}=Kp(P,ie,V,Z);return[Ne,oe]}),rt(Fr)),e);const q=re(!1);he(J(c,Fe(q),me(([P,V])=>V||P!==0)),q);const X=Lt(J(ut(O,R),Ae(([{items:P}])=>P.length>0),Fe(q),Ae(([[P,V],Z])=>{const ie=P.items[P.items.length-1].index===V-1;return(Z||P.bottom>0&&P.itemHeight>0&&P.offsetBottom===0&&P.items.length===V)&&ie}),me(([[,P]])=>P-1),rt())),se=Lt(J(Ie(O),Ae(({items:P})=>P.length>0&&P[0].index===0),on(0),rt())),ce=Lt(J(Ie(O),Fe(L),Ae(([{items:P},V])=>P.length>0&&!V),me(([{items:P}])=>({endIndex:P[P.length-1].index,startIndex:P[0].index})),rt(pp),fn(0)));he(ce,m.scrollSeekRangeChanged),he(J(M,Fe(I,D,R,$),me(([P,V,Z,ie,oe])=>{const Ne=bp(P),{align:Ue,behavior:Oe,offset:de}=Ne;let Me=Ne.index;Me==="LAST"&&(Me=ie-1),Me=zr(0,Me,Vo(ie-1,Me));let ae=zo(V,oe,Z,Me);return Ue==="end"?ae=zp(ae-V.height+Z.height):Ue==="center"&&(ae=zp(ae-V.height/2+Z.height/2)),de&&(ae+=de),{behavior:Oe,top:ae}})),l);const H=Tt(J(O,me(P=>P.offsetBottom+P.bottom)),0);return he(J(v,me(P=>({height:P.visibleHeight,width:P.visibleWidth}))),I),{customScrollParent:g,data:F,deviation:K,footerHeight:a,gap:$,headerHeight:i,increaseViewportBy:t,initialItemCount:N,itemDimensions:D,overscan:n,restoreStateFrom:B,scrollBy:o,scrollContainerState:s,scrollHeight:Y,scrollTo:l,scrollToIndex:M,scrollTop:c,smoothScrollTargetReached:d,totalCount:R,useWindowScroll:S,viewportDimensions:I,windowScrollContainerState:b,windowScrollTo:h,windowViewportRect:v,...m,gridState:O,horizontalDirection:ne,initialTopMostItemIndex:U,totalListHeight:H,...p,endReached:X,propsReady:f,rangeChanged:ce,startReached:se,stateChanged:x,stateRestoreInProgress:L,...C}},nt(ko,Nt,Vr,xp,Nn,Fo,Rn));function Wp(t,e,n){return zr(1,Ha((t+n)/(Ha(e)+n)))}function Kp(t,e,n,r){const{height:a}=n;if(a===void 0||r.length===0)return{bottom:0,top:0};const i=zo(t,e,n,r[0].index);return{bottom:zo(t,e,n,r[r.length-1].index)+a,top:i}}function zo(t,e,n,r){const a=Wp(t.width,n.width,e.column),i=Ha(r/a),o=i*n.height+zr(0,i-1)*e.row;return o>0?o+e.row:o}const sO=ze(()=>{const t=re(_=>`Item ${_}`),e=re({}),n=re(null),r=re("virtuoso-grid-item"),a=re("virtuoso-grid-list"),i=re(Ho),o=re("div"),s=re(cr),l=(_,p=null)=>Tt(J(e,me(m=>m[_]),rt()),p),c=re(!1),d=re(!1);return he(Ie(d),c),{components:e,computeItemKey:i,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:o,itemClassName:r,ItemComponent:l("Item","div"),itemContent:t,listClassName:a,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),lO=ze(([t,e])=>({...t,...e}),nt(oO,sO)),cO=y.memo(function(){const t=at("gridState"),e=at("listClassName"),n=at("itemClassName"),r=at("itemContent"),a=at("computeItemKey"),i=at("isSeeking"),o=qt("scrollHeight"),s=at("ItemComponent"),l=at("ListComponent"),c=at("ScrollSeekPlaceholder"),d=at("context"),_=qt("itemDimensions"),p=qt("gap"),m=at("log"),E=at("stateRestoreInProgress"),f=qt("reportReadyState"),g=Hn(y.useMemo(()=>S=>{const b=S.parentElement.parentElement.scrollHeight;o(b);const h=S.firstChild;if(h){const{height:v,width:C}=h.getBoundingClientRect();_({height:v,width:C})}p({column:jp("column-gap",getComputedStyle(S).columnGap,m),row:jp("row-gap",getComputedStyle(S).rowGap,m)})},[o,_,p,m]),!0,!1);return kp(()=>{t.itemHeight>0&&t.itemWidth>0&&f(!0)},[t]),E?null:u.jsx(l,{className:e,ref:g,...ht(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},children:t.items.map(S=>{const b=a(S.index,S.data,d);return i?u.jsx(c,{...ht(c,d),height:t.itemHeight,index:S.index,width:t.itemWidth},b):y.createElement(s,{...ht(s,d),className:n,"data-index":S.index,key:b},r(S.index,S.data,d))})})}),dO=y.memo(function(){const t=at("HeaderComponent"),e=qt("headerHeight"),n=at("headerFooterTag"),r=Hn(y.useMemo(()=>i=>{e(vn(i,"height"))},[e]),!0,!1),a=at("context");return t?u.jsx(n,{ref:r,children:u.jsx(t,{...ht(t,a)})}):null}),uO=y.memo(function(){const t=at("FooterComponent"),e=qt("footerHeight"),n=at("headerFooterTag"),r=Hn(y.useMemo(()=>i=>{e(vn(i,"height"))},[e]),!0,!1),a=at("context");return t?u.jsx(n,{ref:r,children:u.jsx(t,{...ht(t,a)})}):null}),_O=({children:t})=>{const e=y.useContext(Pp),n=qt("itemDimensions"),r=qt("viewportDimensions"),a=Hn(y.useMemo(()=>i=>{r(i.getBoundingClientRect())},[r]),!0,!1);return y.useEffect(()=>{e&&(r({height:e.viewportHeight,width:e.viewportWidth}),n({height:e.itemHeight,width:e.itemWidth}))},[e,r,n]),u.jsx("div",{ref:a,style:Ya(!1),children:t})},pO=({children:t})=>{const e=y.useContext(Pp),n=qt("windowViewportRect"),r=qt("itemDimensions"),a=at("customScrollParent"),i=op(n,a,!1);return y.useEffect(()=>{e&&(r({height:e.itemHeight,width:e.itemWidth}),n({offsetTop:0,visibleHeight:e.viewportHeight,visibleWidth:e.viewportWidth}))},[e,n,r]),u.jsx("div",{ref:i,style:Ya(!1),children:t})},mO=y.memo(function({...t}){const e=at("useWindowScroll"),n=at("customScrollParent"),r=n||e?EO:gO,a=n||e?pO:_O,i=at("context");return u.jsx(r,{...t,...ht(r,i),children:u.jsxs(a,{children:[u.jsx(dO,{}),u.jsx(cO,{}),u.jsx(uO,{})]})})}),{useEmitter:Qp,useEmitterValue:at,usePublisher:qt}=Mp(lO,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},mO),gO=Yp({useEmitter:Qp,useEmitterValue:at,usePublisher:qt}),EO=Hp({useEmitter:Qp,useEmitterValue:at,usePublisher:qt});function jp(t,e,n){return e!=="normal"&&!(e!=null&&e.endsWith("px"))&&n(`${t} was not resolved to pixel value correctly`,e,xt.WARN),e==="normal"?0:parseInt(e??"0",10)}const fO=yr.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Xp({className:t,variant:e,...n}){return u.jsx("div",{className:Q(fO({variant:e}),t),...n})}function ue(t,e,{checkForDefaultPrevented:n=!0}={}){return function(a){if(t==null||t(a),n===!1||!a.defaultPrevented)return e==null?void 0:e(a)}}function SO(t,e){const n=T.createContext(e),r=i=>{const{children:o,...s}=i,l=T.useMemo(()=>s,Object.values(s));return u.jsx(n.Provider,{value:l,children:o})};r.displayName=t+"Provider";function a(i){const o=T.useContext(n);if(o)return o;if(e!==void 0)return e;throw new Error(`\`${i}\` must be used within \`${t}\``)}return[r,a]}function Xt(t,e=[]){let n=[];function r(i,o){const s=T.createContext(o),l=n.length;n=[...n,o];const c=_=>{var S;const{scope:p,children:m,...E}=_,f=((S=p==null?void 0:p[t])==null?void 0:S[l])||s,g=T.useMemo(()=>E,Object.values(E));return u.jsx(f.Provider,{value:g,children:m})};c.displayName=i+"Provider";function d(_,p){var f;const m=((f=p==null?void 0:p[t])==null?void 0:f[l])||s,E=T.useContext(m);if(E)return E;if(o!==void 0)return o;throw new Error(`\`${_}\` must be used within \`${i}\``)}return[c,d]}const a=()=>{const i=n.map(o=>T.createContext(o));return function(s){const l=(s==null?void 0:s[t])||i;return T.useMemo(()=>({[`__scope${t}`]:{...s,[t]:l}}),[s,l])}};return a.scopeName=t,[r,bO(a,...e)]}function bO(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const o=r.reduce((s,{useScope:l,scopeName:c})=>{const _=l(i)[`__scope${c}`];return{...s,..._}},{});return T.useMemo(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return n.scopeName=e.scopeName,n}var gt=globalThis!=null&&globalThis.document?T.useLayoutEffect:()=>{},TO=T[" useInsertionEffect ".trim().toString()]||gt;function On({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){const[a,i,o]=hO({defaultProp:e,onChange:n}),s=t!==void 0,l=s?t:a;{const d=T.useRef(t!==void 0);T.useEffect(()=>{const _=d.current;_!==s&&console.warn(`${r} is changing from ${_?"controlled":"uncontrolled"} to ${s?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=s},[s,r])}const c=T.useCallback(d=>{var _;if(s){const p=CO(d)?d(t):d;p!==t&&((_=o.current)==null||_.call(o,p))}else i(d)},[s,t,i,o]);return[l,c]}function hO({defaultProp:t,onChange:e}){const[n,r]=T.useState(t),a=T.useRef(n),i=T.useRef(e);return TO(()=>{i.current=e},[e]),T.useEffect(()=>{var o;a.current!==n&&((o=i.current)==null||o.call(i,n),a.current=n)},[n,a]),[n,r,i]}function CO(t){return typeof t=="function"}function Zp(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function $o(...t){return e=>{let n=!1;const r=t.map(a=>{const i=Zp(a,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a<r.length;a++){const i=r[a];typeof i=="function"?i():Zp(t[a],null)}}}}function Be(...t){return T.useCallback($o(...t),t)}var RO=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],xe=RO.reduce((t,e)=>{const n=Mt.createSlot(`Primitive.${e}`),r=T.forwardRef((a,i)=>{const{asChild:o,...s}=a,l=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...s,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function Jp(t,e){t&&fa.flushSync(()=>t.dispatchEvent(e))}function vO(t,e){return T.useReducer((n,r)=>e[n][r]??n,t)}var Dt=t=>{const{present:e,children:n}=t,r=NO(e),a=typeof n=="function"?n({present:r.isPresent}):T.Children.only(n),i=Be(r.ref,OO(a));return typeof n=="function"||r.isPresent?T.cloneElement(a,{ref:i}):null};Dt.displayName="Presence";function NO(t){const[e,n]=T.useState(),r=T.useRef(null),a=T.useRef(t),i=T.useRef("none"),o=t?"mounted":"unmounted",[s,l]=vO(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return T.useEffect(()=>{const c=Va(r.current);i.current=s==="mounted"?c:"none"},[s]),gt(()=>{const c=r.current,d=a.current;if(d!==t){const p=i.current,m=Va(c);t?l("MOUNT"):m==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&p!==m?"ANIMATION_OUT":"UNMOUNT"),a.current=t}},[t,l]),gt(()=>{if(e){let c;const d=e.ownerDocument.defaultView??window,_=m=>{const f=Va(r.current).includes(CSS.escape(m.animationName));if(m.target===e&&f&&(l("ANIMATION_END"),!a.current)){const g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=d.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},p=m=>{m.target===e&&(i.current=Va(r.current))};return e.addEventListener("animationstart",p),e.addEventListener("animationcancel",_),e.addEventListener("animationend",_),()=>{d.clearTimeout(c),e.removeEventListener("animationstart",p),e.removeEventListener("animationcancel",_),e.removeEventListener("animationend",_)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:T.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Va(t){return(t==null?void 0:t.animationName)||"none"}function OO(t){var r,a;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(a=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:a.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var yO=T[" useId ".trim().toString()]||(()=>{}),IO=0;function Zt(t){const[e,n]=T.useState(yO());return gt(()=>{n(r=>r??String(IO++))},[t]),t||(e?`radix-${e}`:"")}var za="Collapsible",[AO,J0]=Xt(za),[xO,Wo]=AO(za),em=T.forwardRef((t,e)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:o,...s}=t,[l,c]=On({prop:r,defaultProp:a??!1,onChange:o,caller:za});return u.jsx(xO,{scope:n,disabled:i,contentId:Zt(),open:l,onOpenToggle:T.useCallback(()=>c(d=>!d),[c]),children:u.jsx(xe.div,{"data-state":Qo(l),"data-disabled":i?"":void 0,...s,ref:e})})});em.displayName=za;var tm="CollapsibleTrigger",nm=T.forwardRef((t,e)=>{const{__scopeCollapsible:n,...r}=t,a=Wo(tm,n);return u.jsx(xe.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":Qo(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:e,onClick:ue(t.onClick,a.onOpenToggle)})});nm.displayName=tm;var Ko="CollapsibleContent",DO=T.forwardRef((t,e)=>{const{forceMount:n,...r}=t,a=Wo(Ko,t.__scopeCollapsible);return u.jsx(Dt,{present:n||a.open,children:({present:i})=>u.jsx(wO,{...r,ref:e,present:i})})});DO.displayName=Ko;var wO=T.forwardRef((t,e)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=t,o=Wo(Ko,n),[s,l]=T.useState(r),c=T.useRef(null),d=Be(e,c),_=T.useRef(0),p=_.current,m=T.useRef(0),E=m.current,f=o.open||s,g=T.useRef(f),S=T.useRef(void 0);return T.useEffect(()=>{const b=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(b)},[]),gt(()=>{const b=c.current;if(b){S.current=S.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const h=b.getBoundingClientRect();_.current=h.height,m.current=h.width,g.current||(b.style.transitionDuration=S.current.transitionDuration,b.style.animationName=S.current.animationName),l(r)}},[o.open,r]),u.jsx(xe.div,{"data-state":Qo(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!f,...i,ref:d,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":E?`${E}px`:void 0,...t.style},children:f&&a})});function Qo(t){return t?"open":"closed"}var MO=em;const rm=MO,am=nm,im=new URL("data:video/mp2t;base64,Ly8vIDxyZWZlcmVuY2UgbGliPSJ3ZWJ3b3JrZXIiIC8+CmltcG9ydCBtYXJrZWQgZnJvbSAnbWFya2VkJzsKCmRlY2xhcmUgY29uc3Qgc2VsZjogRGVkaWNhdGVkV29ya2VyR2xvYmFsU2NvcGU7CmNvbnN0IHNjb3BlOiBEZWRpY2F0ZWRXb3JrZXJHbG9iYWxTY29wZSA9IHNlbGY7CgpzY29wZS5wb3N0TWVzc2FnZT8uKHsgd29ya2VyX3JlYWR5OiB0cnVlIH0pOwoKc2NvcGUuYWRkRXZlbnRMaXN0ZW5lcignbWVzc2FnZScsIChldmVudDogTWVzc2FnZUV2ZW50KSA9PiB7CiAgY29uc3QgcGF5bG9hZDogYW55ID0gZXZlbnQ/LmRhdGEgPz8ge307CiAgY29uc3QgaWQgPSB0eXBlb2YgcGF5bG9hZC5pZCA9PT0gJ3N0cmluZycgPyBwYXlsb2FkLmlkIDogdW5kZWZpbmVkOwogIGNvbnN0IGtleSA9IHR5cGVvZiBwYXlsb2FkLmtleSA9PT0gJ3N0cmluZycgPyBwYXlsb2FkLmtleSA6IHVuZGVmaW5lZDsKICBjb25zdCBzb3VyY2UgPSB0eXBlb2YgcGF5bG9hZC5zb3VyY2UgPT09ICdzdHJpbmcnID8gcGF5bG9hZC5zb3VyY2UgOiB1bmRlZmluZWQ7CiAgaWYgKCFpZCB8fCB0eXBlb2Ygc291cmNlICE9PSAnc3RyaW5nJykgcmV0dXJuOwoKICB0cnkgewogICAgY29uc3QgaHRtbCA9IG1hcmtlZC5wYXJzZShzb3VyY2UpOwogICAgc2NvcGUucG9zdE1lc3NhZ2UoeyBpZCwga2V5LCBodG1sIH0pOwogIH0gY2F0Y2ggKGVycikgewogICAgc2NvcGUucG9zdE1lc3NhZ2UoeyBpZCwga2V5LCBodG1sOiBgPHByZT5FcnJvciByZW5kZXJpbmcgbWFya2Rvd246ICR7U3RyaW5nKGVycil9PC9wcmU+YCB9KTsKICB9Cn0pOwo=",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ao&&ao.tagName.toUpperCase()==="SCRIPT"&&ao.src||new URL("index.umd.js",document.baseURI).href),$r=im.toString(),LO=(()=>{try{if(typeof Worker>"u"||typeof URL>"u"||typeof Blob>"u")return!1;const t=new Blob(["export default null;"],{type:"application/javascript"}),e=URL.createObjectURL(t);return new Worker(e,{type:"module"}).terminate(),URL.revokeObjectURL(e),!0}catch{return!1}})(),PO=$r.includes("data:"),kO=(()=>{if(typeof navigator>"u")return!1;const t=navigator.userAgent.toLowerCase();return t.includes("safari")&&!t.includes("chrome")&&!t.includes("android")})(),jo=LO&&!(PO&&kO),Xo=t=>typeof t=="object"&&t!==null,Zo=t=>typeof t=="function"?t:Xo(t)&&typeof t.parse=="function"?t.parse:null;let $a=null;async function om(t){try{$a||($a=Promise.resolve().then(()=>KM));const e=await $a,n=Xo(e)?e:{},r=Zo(n.parse)??Zo(n.marked)??Zo(n.default);return r?r(t):""}catch(e){throw $a=null,e}}const UO=t=>Xo(t)&&typeof t.highlightElement=="function"?{highlightElement:t.highlightElement}:null;console.log("[MarkdownContent] worker url",$r);const Wr=[];let Kr=!1;const sm={addEventListener:()=>{},removeEventListener:()=>{},postMessage:()=>{},terminate:()=>{}};let yn=sm;const lm=t=>{console.error("[MarkdownContent] worker error",t)};function Jo(t){if(yn&&yn!==sm)try{yn.removeEventListener("error",lm)}catch{}yn=t,Kr=!0;try{yn.addEventListener("error",lm)}catch(e){console.warn("[MarkdownContent] failed to register worker error handler",e)}try{for(;Wr.length;){const e=Wr.shift();if(e)try{e()}catch{}}}catch(e){console.warn("[MarkdownContent] markWorkerOnline notify failed",e)}}function FO(t){if(!jo)return null;const e=t.indexOf("data:");if(e===-1)return null;const r=t.slice(e).match(/^data:[^;]+;base64,(.*)$/);if(!r)return null;try{const a=r[1],i=atob(a),o=Uint8Array.from(i,c=>c.charCodeAt(0)),s=new Blob([o],{type:"application/javascript"}),l=URL.createObjectURL(s);try{const c=new Worker(l,{type:"module"});return URL.revokeObjectURL(l),c}catch(c){return URL.revokeObjectURL(l),console.error("[MarkdownContent] failed to initialize worker from data URI blob",c),null}}catch(a){return console.warn("[MarkdownContent] failed to decode embedded data URI",a),null}}async function BO(t){if(jo)try{let e="";const n=await fetch(t);if(e=await n.text(),n.ok||console.warn("[MarkdownContent] fetch worker non-ok",n.status,n.statusText),!e){console.warn("[MarkdownContent] worker fetch returned empty content; aborting worker init.");return}if(e.trim().startsWith("<")){console.warn("[MarkdownContent] worker fetch returned HTML; dev server may be redirecting. Aborting worker init.");return}const r=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(r);try{const i=new Worker(a,{type:"module"});Jo(i)}catch(i){console.error("[MarkdownContent] failed to initialize worker from blob",i)}finally{URL.revokeObjectURL(a)}}catch(e){console.error("[MarkdownContent] fetch worker failed",e)}}function GO(){if($r.includes("data:")){const t=FO($r);if(t){Jo(t);return}console.warn("[MarkdownContent] data URI bootstrap failed; worker will remain offline until fallback succeeds");return}try{const t=new Worker(im,{type:"module"});Jo(t)}catch(t){console.warn("[MarkdownContent] worker constructor failed, will try fetch+blob fallback",t),BO($r)}}jo?GO():console.warn("[MarkdownContent] module workers not supported; falling back to main-thread markdown parsing");const Qr=new Map;function YO(t,e=!1){if(e){const a=t.slice(0,128);return`streaming:${Math.floor(t.length/50)*50}:${a}`}const n=t.slice(0,64),r=t.length>64?t.slice(-64):"";return`${t.length}:${n}:${r}`}function HO(t,e){const[n,r]=y.useState(t),a=y.useRef(t),i=y.useRef(null);return y.useEffect(()=>{if(!e){r(t);return}return a.current=t,i.current===null&&(i.current=requestAnimationFrame(()=>{i.current=null,r(a.current)})),()=>{i.current&&cancelAnimationFrame(i.current)}},[t,e]),n}function Wa({content:t,className:e="",fallback:n=u.jsx("div",{"aria-busy":!0,children:"Rendering…"}),isStreaming:r=!1,hideFallbackDuringStreaming:a=!0,streamingThrottleMs:i=16,useWorker:o}){const s=HO(t,r),l=YO(s,r),[c,d]=y.useState(()=>{var E;return((E=Qr.get(l))==null?void 0:E.html)??null}),_=y.useRef(null),p=y.useRef([]);y.useEffect(()=>{p.current=[];const E=Qr.get(l);if(E&&E.source===s){E.html!==c&&d(E.html);return}if(E&&E.html!==c&&d(E.html),!(o!==void 0?o:Kr&&!r)){console.log(`[MarkdownContent] Using main-thread parsing (streaming: ${r}, worker: ${o})`);let I=!1;return(async()=>{try{const D=await om(s);Qr.set(l,{html:D,source:s}),I||d(D)}catch(D){console.error("[MarkdownContent] fallback parse failed",D)}})(),()=>{I=!0}}let g=!0,S=!1;const b=`${l}::${Date.now().toString(36)}::${Math.random().toString(36).slice(2)}`;_.current=b;const h=I=>{const D=I.data;if(!D||D.id!==b||D.key&&D.key!==l||!g)return;S=!0;const M=D.html??"";Qr.set(l,{html:M,source:s}),d(M)};yn.addEventListener("message",h);const v=()=>{try{yn.postMessage({id:b,key:l,source:s})}catch(I){console.error("[MarkdownContent] worker.postMessage threw",I)}},C=()=>{if(!r||i<=0){v();return}if(typeof window>"u"){v();return}const I=window.setTimeout(()=>{if(typeof window.requestAnimationFrame=="function"){const D=window.requestAnimationFrame(()=>{v()});p.current.push({type:"raf",id:D})}else v()},i);p.current.push({type:"timeout",id:I})};Kr?C():Wr.push(C);const N=((I,D,M)=>D?M?I>2e4?15e3:I>8e3?8e3:I>2e3?3e3:1e3:I>2e4?1e4:I>8e3?5e3:I>2e3?2e3:600:Math.min(15e3,2e3+Math.floor(I*.5)))(s.length,Kr,r),O=window.setTimeout(async()=>{if(!S){console.warn("[MarkdownContent] worker timeout (ms="+N+"), falling back to main-thread parse for",l);try{const I=await om(s);Qr.set(l,{html:I,source:s}),g&&_.current===b&&d(I)}catch(I){console.error("[MarkdownContent] fallback parse failed",I)}}},N);return()=>{if(g=!1,clearTimeout(O),yn.removeEventListener("message",h),_.current===b&&(_.current=null),!Kr){const I=Wr.indexOf(C);I>=0&&Wr.splice(I,1)}p.current.forEach(I=>{I.type==="timeout"?clearTimeout(I.id):I.type==="raf"&&cancelAnimationFrame(I.id)}),p.current=[]}},[s,c,r,l,i]);const m=y.useRef(null);return y.useEffect(()=>{if(!c)return;const E=m.current;if(!E)return;const f=Array.from(E.querySelectorAll("pre code"));if(!f.length)return;let g=null,S=!1;const b=(v,C)=>{for(const R of v){if(!R.isIntersecting)continue;const N=R.target;if(!g)Promise.resolve().then(()=>S0).then(O=>{if(S)return;const I=UO(O.default??O);if(I){g=I;try{f.forEach(D=>{E.contains(D)&&(g==null||g.highlightElement(D))})}catch{}}}).catch(()=>{});else try{g.highlightElement(N)}catch{}C.unobserve(N)}},h=new IntersectionObserver(b,{root:E,threshold:.1});return f.forEach(v=>h.observe(v)),()=>{S=!0,h.disconnect()}},[c]),c?u.jsx("div",{ref:m,className:Q("markdown prose max-w-none break-words dark:prose-invert",e),dangerouslySetInnerHTML:{__html:c}}):r&&a?null:u.jsx("div",{className:Q("markdown prose max-w-none break-words dark:prose-invert",e),children:n})}async function cm(t,e){return await Gt(t,{responseType:"blob",onDownloadProgress:r=>{try{e&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function dm(t,e){return await(await cm(`/chat/files/${t}/view`,e)).text()}async function qO(t,e){const n=await cm(`/chat/files/${t}/download`,e),r=URL.createObjectURL(n);let a=`file_${t}`;try{const o=await Gt(`/chat/files/${t}`);a=(o==null?void 0:o.filename)??a}catch{}const i=document.createElement("a");i.href=r,i.download=a,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}const VO=1,zO=1e6;let es=0;function $O(){return es=(es+1)%Number.MAX_SAFE_INTEGER,es.toString()}const ts=new Map,um=t=>{if(ts.has(t))return;const e=setTimeout(()=>{ts.delete(t),jr({type:"REMOVE_TOAST",toastId:t})},zO);ts.set(t,e)},WO=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,VO)};case"UPDATE_TOAST":return{...t,toasts:t.toasts.map(n=>n.id===e.toast.id?{...n,...e.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=e;return n?um(n):t.toasts.forEach(r=>{um(r.id)}),{...t,toasts:t.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return e.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(n=>n.id!==e.toastId)}}},Ka=[];let Qa={toasts:[]};function jr(t){Qa=WO(Qa,t),Ka.forEach(e=>{e(Qa)})}function KO({...t}){const e=$O(),n=a=>jr({type:"UPDATE_TOAST",toast:{...a,id:e}}),r=()=>jr({type:"DISMISS_TOAST",toastId:e});return jr({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:a=>{a||r()}}}),{id:e,dismiss:r,update:n}}function ns(){const[t,e]=T.useState(Qa);return T.useEffect(()=>(Ka.push(e),()=>{const n=Ka.indexOf(e);n>-1&&Ka.splice(n,1)}),[t]),{...t,toast:KO,dismiss:n=>jr({type:"DISMISS_TOAST",toastId:n})}}function ft(t){const e=T.useRef(t);return T.useEffect(()=>{e.current=t}),T.useMemo(()=>(...n)=>{var r;return(r=e.current)==null?void 0:r.call(e,...n)},[])}function QO(t,e=globalThis==null?void 0:globalThis.document){const n=ft(t);T.useEffect(()=>{const r=a=>{a.key==="Escape"&&n(a)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[n,e])}var jO="DismissableLayer",rs="dismissableLayer.update",XO="dismissableLayer.pointerDownOutside",ZO="dismissableLayer.focusOutside",_m,pm=T.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Xr=T.forwardRef((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:o,onDismiss:s,...l}=t,c=T.useContext(pm),[d,_]=T.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,m]=T.useState({}),E=Be(e,N=>_(N)),f=Array.from(c.layers),[g]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),S=f.indexOf(g),b=d?f.indexOf(d):-1,h=c.layersWithOutsidePointerEventsDisabled.size>0,v=b>=S,C=ty(N=>{const O=N.target,I=[...c.branches].some(D=>D.contains(O));!v||I||(a==null||a(N),o==null||o(N),N.defaultPrevented||s==null||s())},p),R=ny(N=>{const O=N.target;[...c.branches].some(D=>D.contains(O))||(i==null||i(N),o==null||o(N),N.defaultPrevented||s==null||s())},p);return QO(N=>{b===c.layers.size-1&&(r==null||r(N),!N.defaultPrevented&&s&&(N.preventDefault(),s()))},p),T.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(_m=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),mm(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=_m)}},[d,p,n,c]),T.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),mm())},[d,c]),T.useEffect(()=>{const N=()=>m({});return document.addEventListener(rs,N),()=>document.removeEventListener(rs,N)},[]),u.jsx(xe.div,{...l,ref:E,style:{pointerEvents:h?v?"auto":"none":void 0,...t.style},onFocusCapture:ue(t.onFocusCapture,R.onFocusCapture),onBlurCapture:ue(t.onBlurCapture,R.onBlurCapture),onPointerDownCapture:ue(t.onPointerDownCapture,C.onPointerDownCapture)})});Xr.displayName=jO;var JO="DismissableLayerBranch",ey=T.forwardRef((t,e)=>{const n=T.useContext(pm),r=T.useRef(null),a=Be(e,r);return T.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),u.jsx(xe.div,{...t,ref:a})});ey.displayName=JO;function ty(t,e=globalThis==null?void 0:globalThis.document){const n=ft(t),r=T.useRef(!1),a=T.useRef(()=>{});return T.useEffect(()=>{const i=s=>{if(s.target&&!r.current){let l=function(){gm(XO,n,c,{discrete:!0})};const c={originalEvent:s};s.pointerType==="touch"?(e.removeEventListener("click",a.current),a.current=l,e.addEventListener("click",a.current,{once:!0})):l()}else e.removeEventListener("click",a.current);r.current=!1},o=window.setTimeout(()=>{e.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(o),e.removeEventListener("pointerdown",i),e.removeEventListener("click",a.current)}},[e,n]),{onPointerDownCapture:()=>r.current=!0}}function ny(t,e=globalThis==null?void 0:globalThis.document){const n=ft(t),r=T.useRef(!1);return T.useEffect(()=>{const a=i=>{i.target&&!r.current&&gm(ZO,n,{originalEvent:i},{discrete:!1})};return e.addEventListener("focusin",a),()=>e.removeEventListener("focusin",a)},[e,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function mm(){const t=new CustomEvent(rs);document.dispatchEvent(t)}function gm(t,e,n,{discrete:r}){const a=n.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&a.addEventListener(t,e,{once:!0}),r?Jp(a,i):a.dispatchEvent(i)}var as="focusScope.autoFocusOnMount",is="focusScope.autoFocusOnUnmount",Em={bubbles:!1,cancelable:!0},ry="FocusScope",ja=T.forwardRef((t,e)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...o}=t,[s,l]=T.useState(null),c=ft(a),d=ft(i),_=T.useRef(null),p=Be(e,f=>l(f)),m=T.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;T.useEffect(()=>{if(r){let f=function(h){if(m.paused||!s)return;const v=h.target;s.contains(v)?_.current=v:In(_.current,{select:!0})},g=function(h){if(m.paused||!s)return;const v=h.relatedTarget;v!==null&&(s.contains(v)||In(_.current,{select:!0}))},S=function(h){if(document.activeElement===document.body)for(const C of h)C.removedNodes.length>0&&In(s)};document.addEventListener("focusin",f),document.addEventListener("focusout",g);const b=new MutationObserver(S);return s&&b.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",f),document.removeEventListener("focusout",g),b.disconnect()}}},[r,s,m.paused]),T.useEffect(()=>{if(s){bm.add(m);const f=document.activeElement;if(!s.contains(f)){const S=new CustomEvent(as,Em);s.addEventListener(as,c),s.dispatchEvent(S),S.defaultPrevented||(ay(cy(fm(s)),{select:!0}),document.activeElement===f&&In(s))}return()=>{s.removeEventListener(as,c),setTimeout(()=>{const S=new CustomEvent(is,Em);s.addEventListener(is,d),s.dispatchEvent(S),S.defaultPrevented||In(f??document.body,{select:!0}),s.removeEventListener(is,d),bm.remove(m)},0)}}},[s,c,d,m]);const E=T.useCallback(f=>{if(!n&&!r||m.paused)return;const g=f.key==="Tab"&&!f.altKey&&!f.ctrlKey&&!f.metaKey,S=document.activeElement;if(g&&S){const b=f.currentTarget,[h,v]=iy(b);h&&v?!f.shiftKey&&S===v?(f.preventDefault(),n&&In(h,{select:!0})):f.shiftKey&&S===h&&(f.preventDefault(),n&&In(v,{select:!0})):S===b&&f.preventDefault()}},[n,r,m.paused]);return u.jsx(xe.div,{tabIndex:-1,...o,ref:p,onKeyDown:E})});ja.displayName=ry;function ay(t,{select:e=!1}={}){const n=document.activeElement;for(const r of t)if(In(r,{select:e}),document.activeElement!==n)return}function iy(t){const e=fm(t),n=Sm(e,t),r=Sm(e.reverse(),t);return[n,r]}function fm(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function Sm(t,e){for(const n of t)if(!oy(n,{upTo:e}))return n}function oy(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function sy(t){return t instanceof HTMLInputElement&&"select"in t}function In(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&sy(t)&&e&&t.select()}}var bm=ly();function ly(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=Tm(t,e),t.unshift(e)},remove(e){var n;t=Tm(t,e),(n=t[0])==null||n.resume()}}}function Tm(t,e){const n=[...t],r=n.indexOf(e);return r!==-1&&n.splice(r,1),n}function cy(t){return t.filter(e=>e.tagName!=="A")}var dy="Portal",Xa=T.forwardRef((t,e)=>{var s;const{container:n,...r}=t,[a,i]=T.useState(!1);gt(()=>i(!0),[]);const o=n||a&&((s=globalThis==null?void 0:globalThis.document)==null?void 0:s.body);return o?ro.createPortal(u.jsx(xe.div,{...r,ref:e}),o):null});Xa.displayName=dy;var os=0;function ss(){T.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??hm()),document.body.insertAdjacentElement("beforeend",t[1]??hm()),os++,()=>{os===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),os--}},[])}function hm(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var cn=function(){return cn=Object.assign||function(e){for(var n,r=1,a=arguments.length;r<a;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},cn.apply(this,arguments)};function Cm(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(t);a<r.length;a++)e.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(t,r[a])&&(n[r[a]]=t[r[a]]);return n}function uy(t,e,n){if(n||arguments.length===2)for(var r=0,a=e.length,i;r<a;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;var Za="right-scroll-bar-position",Ja="width-before-scroll-bar",_y="with-scroll-bars-hidden",py="--removed-body-scroll-bar-size";function ls(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function my(t,e){var n=y.useState(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(r){var a=n.value;a!==r&&(n.value=r,n.callback(r,a))}}}})[0];return n.callback=e,n.facade}var gy=typeof window<"u"?T.useLayoutEffect:T.useEffect,Rm=new WeakMap;function Ey(t,e){var n=my(null,function(r){return t.forEach(function(a){return ls(a,r)})});return gy(function(){var r=Rm.get(n);if(r){var a=new Set(r),i=new Set(t),o=n.current;a.forEach(function(s){i.has(s)||ls(s,null)}),i.forEach(function(s){a.has(s)||ls(s,o)})}Rm.set(n,t)},[t]),n}function fy(t){return t}function Sy(t,e){e===void 0&&(e=fy);var n=[],r=!1,a={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(i){var o=e(i,r);return n.push(o),function(){n=n.filter(function(s){return s!==o})}},assignSyncMedium:function(i){for(r=!0;n.length;){var o=n;n=[],o.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){r=!0;var o=[];if(n.length){var s=n;n=[],s.forEach(i),o=n}var l=function(){var d=o;o=[],d.forEach(i)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){o.push(d),c()},filter:function(d){return o=o.filter(d),n}}}};return a}function by(t){t===void 0&&(t={});var e=Sy(null);return e.options=cn({async:!0,ssr:!1},t),e}var vm=function(t){var e=t.sideCar,n=Cm(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return T.createElement(r,cn({},n))};vm.isSideCarExport=!0;function Ty(t,e){return t.useMedium(e),vm}var Nm=by(),cs=function(){},ei=T.forwardRef(function(t,e){var n=T.useRef(null),r=T.useState({onScrollCapture:cs,onWheelCapture:cs,onTouchMoveCapture:cs}),a=r[0],i=r[1],o=t.forwardProps,s=t.children,l=t.className,c=t.removeScrollBar,d=t.enabled,_=t.shards,p=t.sideCar,m=t.noRelative,E=t.noIsolation,f=t.inert,g=t.allowPinchZoom,S=t.as,b=S===void 0?"div":S,h=t.gapMode,v=Cm(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,R=Ey([n,e]),N=cn(cn({},v),a);return T.createElement(T.Fragment,null,d&&T.createElement(C,{sideCar:Nm,removeScrollBar:c,shards:_,noRelative:m,noIsolation:E,inert:f,setCallbacks:i,allowPinchZoom:!!g,lockRef:n,gapMode:h}),o?T.cloneElement(T.Children.only(s),cn(cn({},N),{ref:R})):T.createElement(b,cn({},N,{className:l,ref:R}),s))});ei.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ei.classNames={fullWidth:Ja,zeroRight:Za};var hy=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Cy(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=hy();return e&&t.setAttribute("nonce",e),t}function Ry(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function vy(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var Ny=function(){var t=0,e=null;return{add:function(n){t==0&&(e=Cy())&&(Ry(e,n),vy(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},Oy=function(){var t=Ny();return function(e,n){T.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&n])}},Om=function(){var t=Oy(),e=function(n){var r=n.styles,a=n.dynamic;return t(r,a),null};return e},yy={left:0,top:0,right:0,gap:0},ds=function(t){return parseInt(t||"",10)||0},Iy=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],a=e[t==="padding"?"paddingRight":"marginRight"];return[ds(n),ds(r),ds(a)]},Ay=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return yy;var e=Iy(t),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-n+e[2]-e[0])}},xy=Om(),ur="data-scroll-locked",Dy=function(t,e,n,r){var a=t.left,i=t.top,o=t.right,s=t.gap;return n===void 0&&(n="margin"),`
|
|
39
39
|
.`.concat(_y,` {
|
|
40
40
|
overflow: hidden `).concat(r,`;
|
|
41
41
|
padding-right: `).concat(s,"px ").concat(r,`;
|
|
@@ -80,7 +80,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
80
80
|
If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
81
81
|
|
|
82
82
|
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return T.useEffect(()=>{t&&(document.getElementById(t)||console.error(n))},[n,t]),null},rI="DialogDescriptionWarning",aI=({contentRef:t,descriptionId:e})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${jm(rI).contentName}}.`;return T.useEffect(()=>{var i;const a=(i=t.current)==null?void 0:i.getAttribute("aria-describedby");e&&a&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},Xm=km,iI=Fm,Zm=Gm,li=Ym,ci=Hm,$n=Vm,di=$m,Jm=Km;const oI=Xm,sI=Zm,eg=T.forwardRef(({className:t,...e},n)=>u.jsx(li,{ref:n,className:Q("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e}));eg.displayName=li.displayName;const tg=T.forwardRef(({className:t,children:e,...n},r)=>{const a=T.useMemo(()=>{let i=!1;function o(s){T.Children.forEach(s,l=>{if(i||!T.isValidElement(l))return;const c=l.type;if(c===$n||(c==null?void 0:c.displayName)===$n.displayName||(c==null?void 0:c.name)==="DialogTitle"){i=!0;return}l.props&&l.props.children&&o(l.props.children)})}return o(e),i},[e]);return u.jsxs(sI,{children:[u.jsx(eg,{}),u.jsxs(ci,{ref:r,className:Q("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...n,children:[!a&&u.jsx($n,{className:"sr-only",children:"Dialog"}),e,u.jsxs(Jm,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[u.jsx(pe.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});tg.displayName=ci.displayName;const ng=({className:t,...e})=>u.jsx("div",{className:Q("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});ng.displayName="DialogHeader";const rg=T.forwardRef(({className:t,...e},n)=>u.jsx($n,{ref:n,className:Q("text-lg font-semibold leading-none tracking-tight",t),...e}));rg.displayName=$n.displayName;const lI=T.forwardRef(({className:t,...e},n)=>u.jsx(di,{ref:n,className:Q("text-sm text-muted-foreground",t),...e}));lI.displayName=di.displayName;function cI({isOpen:t,onClose:e,fileId:n,fileName:r,mimeType:a}){const[i,o]=y.useState(!1),[s,l]=y.useState(null),[c,d]=y.useState(null),{toast:_}=ns();y.useEffect(()=>{t&&n&&p()},[t,n]);const p=async()=>{if(n){o(!0),d(null),l(null);try{const S=await dm(n);l(S)}catch(S){console.error("Failed to load file:",S),d(S instanceof Error?S.message:"Failed to load file")}finally{o(!1)}}},m=async()=>{if(n)try{await qO(n),_({title:"Download started",description:`Downloading ${r}`})}catch(S){console.error("Failed to download file:",S),_({title:"Download failed",description:String(S),variant:"destructive"})}},E=async()=>{if(n)try{const S=await dm(n),b=new Blob([S],{type:a}),h=URL.createObjectURL(b);window.open(h,"_blank"),URL.revokeObjectURL(h)}catch(S){console.error("Failed to open file externally:",S),_({title:"Failed to open file",description:String(S),variant:"destructive"})}},f=()=>i?u.jsxs("div",{className:"flex items-center justify-center py-12",children:[u.jsx(pe.Loader,{className:"h-8 w-8 animate-spin mr-3"}),u.jsx("span",{children:"Loading file..."})]}):c?u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[u.jsx("div",{className:"text-red-500 mb-4",children:"⚠️"}),u.jsx("p",{className:"text-red-600 mb-4",children:c}),u.jsx($e,{onClick:p,variant:"outline",children:"Try Again"})]}):s?a.startsWith("image/")?u.jsx("div",{className:"flex justify-center",children:u.jsx("img",{src:`data:${a};base64,${s}`,alt:r,className:"max-w-full max-h-[70vh] object-contain rounded-lg"})}):a==="application/pdf"?u.jsx("div",{className:"w-full h-[70vh] border rounded-lg overflow-hidden",children:u.jsx("iframe",{src:`data:application/pdf;base64,${s}`,className:"w-full h-full",title:r})}):a.startsWith("text/")||a.includes("json")||a.includes("xml")?u.jsx("div",{className:"bg-gray-50 dark:bg-gray-900 rounded-lg p-4 max-h-[70vh] overflow-auto",children:u.jsx("pre",{className:"whitespace-pre-wrap font-mono text-sm",children:s})}):u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[u.jsx(pe.FileText,{className:"h-16 w-16 text-gray-400 mb-4"}),u.jsx("p",{className:"text-lg font-medium mb-2",children:r}),u.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:[a," • ",s.length," bytes"]}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"This file type cannot be previewed. Use download or external view."})]}):u.jsx("div",{className:"flex items-center justify-center py-12",children:u.jsx("p",{className:"text-muted-foreground",children:"No content to display"})}),g=()=>a.startsWith("image/")?u.jsx(pe.Image,{className:"h-5 w-5"}):u.jsx(pe.FileText,{className:"h-5 w-5"});return u.jsx(oI,{open:t,onOpenChange:e,children:u.jsxs(tg,{className:"max-w-4xl max-h-[90vh] overflow-hidden",children:[u.jsx(ng,{children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[g(),u.jsxs("div",{children:[u.jsx(rg,{className:"text-left",children:r}),u.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[a," • Click download or external view for full access"]})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs($e,{variant:"outline",size:"sm",onClick:E,className:"flex items-center gap-2",children:[u.jsx(pe.ExternalLink,{className:"h-4 w-4"}),"External"]}),u.jsxs($e,{variant:"outline",size:"sm",onClick:m,className:"flex items-center gap-2",children:[u.jsx(pe.Download,{className:"h-4 w-4"}),"Download"]})]})]})}),u.jsx("div",{className:"flex-1 overflow-hidden",children:f()})]})})}const ui="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function dI({className:t}){const[e,n]=y.useState(0);return y.useEffect(()=>{const r=setInterval(()=>n(a=>(a+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:Q("inline-block text-xs opacity-70 ml-1",t),children:["Is thinking",".".repeat(e)]})}const ag=y.memo(function({message:e,messageIndex:n,isStreamingMessage:r=!1,streamingDebounceMs:a=16,isEditing:i=!1,showActions:o=!0,showTimestamp:s=!0,showAgentName:l=!0,layoutSize:c="desktop",truncateToolMessages:d=!0,toolMessagePreviewLength:_=200,truncateUserMessages:p=!0,userMessagePreviewLength:m=200,customStyles:E={},onEdit:f,onRegenerate:g,onCancelEdit:S,onCopy:b}){const[h,v]=y.useState(!1),[C,R]=y.useState(!1),[N,O]=y.useState(!1),[I,D]=y.useState(!1),{currentThreadId:M}=xa();ns();const[Y,K]=y.useState({}),[F,$]=y.useState(!1),[x,B]=y.useState(null),L=c==="phone"||c==="half-screen",U=e.role,z=U==="tool",W=y.useMemo(()=>{switch(U){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[U]),ne=y.useMemo(()=>uI(e.content),[e.content]),q=y.useMemo(()=>EI(e.content),[e.content]),X=y.useMemo(()=>e.content.filter(de=>de.type==="image_url"),[e.content]),se=y.useMemo(()=>e.content.filter(de=>de.type==="file"),[e.content]),ce=SI(ne,r);y.useEffect(()=>{r&&ne!==ce&&console.log("[MessageComponent] Streaming update:",{messageId:e.id,isStreamingMessage:r,textLength:ne.length,batchedLength:ce.length,textPreview:ne.slice(-50),batchedPreview:ce.slice(-50)})},[r,ne,ce,e.id]);const H=async()=>{try{const de=z?gr(e.content):ne;await navigator.clipboard.writeText(de),v(!0),setTimeout(()=>v(!1),2e3),b==null||b(de)}catch(de){console.error("Failed to copy:",de)}},P=()=>{if(!f)return;const de=z?gr(e.content):ne;f(e.id,de)},V=()=>g==null?void 0:g(n),Z=()=>{const Me=Q(L?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",W);switch(U){case"user":return u.jsx(pe.User,{className:Me});case"assistant":return u.jsx(pe.Bot,{className:Me});case"tool":return u.jsx(pe.Wrench,{className:Me});default:return u.jsx(pe.Bot,{className:Me})}},ie=()=>{const de="group relative mb-4 flex w-full";switch(U){case"user":return Q(de,"justify-end");case"assistant":case"tool":case"system":return Q(de,"justify-start");default:return de}},oe=()=>{const de=Q("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",L&&"px-3 py-2 text-sm");switch(U){case"user":return Q(de,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return Q(de,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return Q(de,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return Q(de,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return Q(de,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},Ne=de=>{if(!de)return"";try{return new Date(de).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}},Ue=()=>{if(!(ne.trim().length>0||X.length>0||se.length>0))return u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(pe.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]});if(e.model==="reflection"){const fe=ne.trim(),Te=fs(fe);if(Te&&typeof Te=="object")return u.jsx(bI,{data:Te})}if(z&&q.name==="get_issues"){const fe=e.content.find(tt=>tt.type==="tool_result"),Te=(fe==null?void 0:fe.output)??gr(e.content),Se=sg(Te);if(Se)return u.jsx(TI,{issues:Se})}if(z&&!N){const fe=gr(e.content).slice(0,80).replace(/\s+/g," ");return u.jsx("div",{className:Q("text-xs font-mono opacity-70 flex items-center justify-between gap-2 text-current",L&&"text-[10px]"),children:u.jsxs("span",{className:"truncate max-w-full text-current",children:[fe,fe.length>=80?"…":""]})})}if(z&&d){const fe=gr(e.content),Te=fe.length>_;return u.jsx(rm,{open:C,onOpenChange:R,children:u.jsxs("div",{className:"font-mono text-sm text-current",children:[u.jsx("pre",{className:Q("whitespace-pre-wrap break-words text-current",L&&"text-xs"),children:Te&&!C?fe.substring(0,_)+"...":fe}),Te&&u.jsx(am,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"sm",className:"h-6 text-xs text-current",children:C?u.jsxs(u.Fragment,{children:[u.jsx(pe.ChevronUp,{className:"h-3 w-3 mr-1"}),"Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(pe.ChevronDown,{className:"h-3 w-3 mr-1"}),"Show more (",fe.length-_," chars)"]})})})]})})}if(z&&N&&!d){const fe=hI(e.content);if(fe&&_I(fe))return u.jsx(Wa,{content:fe.trim(),hideFallbackDuringStreaming:!0});const Te=gr(e.content);return u.jsx("div",{className:"font-mono text-sm text-current",children:u.jsx("pre",{className:Q("whitespace-pre-wrap break-words text-current",L&&"text-xs"),children:Te})})}const Me=X.length>0&&U!=="tool",ae=se.length>0&&U!=="tool"&&!1;return u.jsxs("div",{children:[r?u.jsxs("div",{className:Q("relative transition-all duration-200 ease-out",L?"text-xs":"text-sm"),style:{minHeight:80},children:[(()=>{const fe=fs(ce);if(fe!==null)return u.jsx(ig,{data:fe});const Te=mI(pI(ce)),Se=ce.trim().length===0;return u.jsx(u.Fragment,{children:Se?u.jsx("div",{className:"w-full",children:u.jsxs("div",{className:"animate-pulse space-y-2",children:[u.jsx("div",{className:"h-3 bg-slate-200 dark:bg-slate-700 rounded w-3/4"}),u.jsx("div",{className:"h-3 bg-slate-200 dark:bg-slate-700 rounded w-5/6"}),u.jsx("div",{className:"h-3 bg-slate-200 dark:bg-slate-700 rounded w-2/3"})]})}):u.jsx("pre",{className:Q("whitespace-pre-wrap break-words font-sans leading-relaxed transition-opacity duration-200",L&&"text-xs"),children:Te})})})(),u.jsx("div",{className:"mt-2",children:u.jsx(dI,{className:Q(W,L?"text-xs":"text-sm")})})]}):(()=>{const fe=fs(ne.trim());if(fe!==null)return u.jsx(ig,{data:fe});if(U==="user"&&p){const Te=ne.trim();if(Te.length>m)return u.jsxs(rm,{open:I,onOpenChange:D,children:[u.jsx("div",{className:Q("text-sm text-[hsl(var(--chat-bubble-user-text))]",L&&"text-xs"),children:I?u.jsx(Wa,{content:Te,hideFallbackDuringStreaming:!0}):u.jsxs("pre",{className:Q("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",L&&"text-xs"),children:[Te.substring(0,m),"..."]})}),u.jsx(am,{asChild:!0,children:u.jsx($e,{variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",children:I?u.jsxs(u.Fragment,{children:[u.jsx(pe.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(pe.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",Te.length-m," chars)"]})})})]})}return u.jsx(Wa,{content:ne.trim(),isStreaming:r,hideFallbackDuringStreaming:!0,streamingThrottleMs:a,useWorker:!r})})(),Me&&u.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:X.map((fe,Te)=>{const Se=fe,tt=typeof Se.width=="number"?Se.width:void 0,We=typeof Se.height=="number"?Se.height:void 0,ct=tt&&We&&We>0?`${tt} / ${We}`:"4 / 3",et=tt&&We&&We>0?Math.max(120,Math.round(We/tt*140)):160;return u.jsxs("div",{className:"relative border rounded overflow-hidden bg-gray-100 dark:bg-gray-900/40",style:{aspectRatio:ct,minHeight:et},"data-placeholder-height":et,children:[u.jsx("img",{src:Se.url,alt:Se.alt??"image",loading:"lazy",className:"absolute inset-0 h-full w-full object-contain"}),u.jsxs("div",{className:"absolute top-1 right-1 bg-background/70 rounded px-1 py-0.5 text-[10px] flex items-center gap-1",children:[u.jsx(pe.Image,{className:"h-3 w-3"}),u.jsx("span",{children:"image"})]})]},Te)})}),ae]})},Oe=y.useMemo(()=>fI(e),[e]);return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:Q(ie(),E.container),children:u.jsxs("div",{className:Q(oe(),E.content),children:[(s||l||z)&&u.jsxs("div",{className:Q("flex items-center justify-between mb-2 pb-2 border-b border-current/10",L&&"mb-1 pb-1",W,E.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[Z(),l&&Oe&&u.jsx("span",{className:Q("font-medium",L?"text-xs":"text-sm"),children:Oe}),z&&q.name&&u.jsxs(Xp,{variant:"outline",className:Q("text-xs flex items-center gap-1 cursor-pointer",W,"border border-current/40",L&&"text-xs h-4"),onClick:()=>O(de=>!de),children:[u.jsx("span",{children:q.name}),u.jsx("span",{className:"inline-flex items-center",children:N?u.jsx(pe.ChevronUp,{className:"h-3 w-3"}):u.jsx(pe.ChevronDown,{className:"h-3 w-3"})})]}),z&&!q.name&&u.jsx($e,{variant:"ghost",size:"sm",className:Q("h-6 px-1",W,"hover:bg-foreground/10"),onClick:()=>O(de=>!de),children:u.jsxs("span",{className:"text-xs flex items-center gap-1",children:["Tool Output ",N?u.jsx(pe.ChevronUp,{className:"h-3 w-3"}):u.jsx(pe.ChevronDown,{className:"h-3 w-3"})]})})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[s&&u.jsx("span",{className:Q("text-xs opacity-60",W,L&&"text-xs"),children:Ne(e.createdAt)}),o&&!i&&u.jsxs("div",{className:Q("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",E.actions),children:[u.jsx($e,{variant:"ghost",size:"sm",onClick:H,className:Q("h-6 w-6 p-0 hover:bg-foreground/10",W,L&&"h-5 w-5"),children:u.jsx(pe.Copy,{className:Q(h?"text-success":W,L?"h-3 w-3":"h-4 w-4")})}),U==="user"&&f&&u.jsx($e,{variant:"ghost",size:"sm",onClick:P,className:Q("h-6 w-6 p-0 hover:bg-foreground/10",W,L&&"h-5 w-5"),children:u.jsx(pe.Edit,{className:Q(W,L?"h-3 w-3":"h-4 w-4")})}),U==="assistant"&&g&&u.jsx($e,{variant:"ghost",size:"sm",onClick:V,className:Q("h-6 w-6 p-0 hover:bg-foreground/10",W,L&&"h-5 w-5"),children:u.jsx(pe.RotateCcw,{className:Q(W,L?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsx("div",{className:"relative",children:Ue()}),z&&N&&(q.toolCallId||q.name)&&u.jsxs("div",{className:Q("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",L&&"text-xs"),children:[q.name&&u.jsxs("div",{children:["Function: ",q.name]}),q.toolCallId&&u.jsxs("div",{children:["Call ID: ",q.toolCallId]})]}),!(s||l||z)&&o&&!i&&u.jsxs("div",{className:Q("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",E.actions),children:[u.jsx($e,{variant:"ghost",size:"sm",onClick:H,className:Q("h-6 w-6 p-0 hover:bg-background/50 text-current",L&&"h-5 w-5"),children:u.jsx(pe.Copy,{className:Q(h?"text-success":"text-current",L?"h-3 w-3":"h-4 w-4")})}),U==="user"&&f&&u.jsx($e,{variant:"ghost",size:"sm",onClick:P,className:Q("h-6 w-6 p-0 hover:bg-background/50 text-current",L&&"h-5 w-5"),children:u.jsx(pe.Edit,{className:Q("text-current",L?"h-3 w-3":"h-4 w-4")})}),U==="assistant"&&g&&u.jsx($e,{variant:"ghost",size:"sm",onClick:V,className:Q("h-6 w-6 p-0 hover:bg-background/50 text-current",L&&"h-5 w-5"),children:u.jsx(pe.RotateCcw,{className:Q("text-current",L?"h-3 w-3":"h-4 w-4")})})]})]})}),x&&u.jsx(cI,{isOpen:F,onClose:()=>{$(!1),B(null)},fileId:x.id,fileName:x.name,mimeType:x.mimeType})]})},(t,e)=>e.isStreamingMessage?!1:t.message.id===e.message.id&&t.message.content===e.message.content&&t.isStreamingMessage===e.isStreamingMessage&&t.isEditing===e.isEditing);function uI(t){const e=t.filter(n=>n.type==="text").map(n=>n.text).join("");return e||JSON.stringify(t)}function _I(t){return t.includes(`
|
|
83
|
-
`)||t.includes("```")||/[-*] /.test(t)||/#+\s/.test(t)}function pI(t){let e=t;try{(e.match(/```/g)||[]).length%2===1&&(e+="\n```"),(e.replace(/```[\s\S]*?```/g,"").match(new RegExp("(?<!`)`(?!`)","g"))||[]).length%2===1&&(e+="`")}catch{}return e}function mI(t){let e=t;try{const n=[],r=[],a="\0F",i="\0I";let o=e.replace(/```[\s\S]*?```/g,s=>(n.push(s),`${a}${n.length-1}\0`));o=o.replace(/`[^`]*`/g,s=>(r.push(s),`${i}${r.length-1}\0`)),o=o.replace(/\b([A-Za-z0-9_&\/-]+)\b(\s+\1\b)+/g,"$1").replace(/\b([A-Za-z0-9_&\/-]+\s+[A-Za-z0-9_&\/-]+)\b(\s+\1\b)+/g,"$1").replace(/([\.,;:!\?\-])\1+/g,"$1").replace(/([:;!\?\)])([A-Za-z])/g,"$1 $2").replace(/\s{3,}/g," "),o=o.replace(/\u0000F(\d+)\u0000/g,(s,l)=>n[Number(l)]??""),o=o.replace(/\u0000I(\d+)\u0000/g,(s,l)=>r[Number(l)]??""),e=o}catch{}return e}function fs(t){const e=t==null?void 0:t.trim();if(!e||!(e.startsWith("{")||e.startsWith("[")))return null;try{return JSON.parse(e)}catch{return null}}function ig({data:t}){if(Array.isArray(t))return t.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:ui,children:u.jsx("ul",{className:"list-disc pl-5",children:t.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Zr(t)});if(t&&typeof t=="object"){const e=Array.isArray(t.distilled_facts)?t.distilled_facts:null,n=Array.isArray(t.follow_up_queries)?t.follow_up_queries:null,r=typeof t.is_sufficient=="boolean"?t.is_sufficient:void 0;if(e||n||typeof r=="boolean")return u.jsxs("div",{className:ui,children:[typeof r=="boolean"&&u.jsxs("p",{children:[u.jsx("strong",{children:"Is sufficient:"})," ",r?"Yes":"No"]}),n&&n.length>0&&u.jsxs("div",{children:[u.jsx("p",{children:u.jsx("strong",{children:"Follow-up queries:"})}),u.jsx("ul",{className:"list-disc pl-5",children:n.map((i,o)=>u.jsx("li",{children:String(i)},o))})]}),e&&e.length>0&&u.jsxs("div",{children:[u.jsx("p",{children:u.jsx("strong",{children:"Facts:"})}),u.jsx("ul",{className:"list-disc pl-5",children:e.map((i,o)=>u.jsx("li",{children:String(i)},o))})]})]});const a=Object.entries(t);return u.jsx("div",{className:ui,children:u.jsx("dl",{className:"mt-0",children:a.map(([i,o])=>u.jsxs("div",{className:"mb-1",children:[u.jsxs("dt",{className:"inline font-medium mr-1",children:[i,":"]}),u.jsx("dd",{className:"inline",children:gI(o)})]},i))})})}return u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Zr(t)})}function gI(t){if(t==null)return String(t);const e=typeof t;if(e==="string"||e==="number"||e==="boolean")return String(t);if(Array.isArray(t)&&t.every(r=>r===null||["string","number","boolean"].includes(typeof r)))return t.join(", ");try{return u.jsx("code",{className:"text-xs",children:JSON.stringify(_i(t))})}catch{return String(t)}}function og(t){return!!(t&&typeof t=="object"&&(t.type==="file"||t.mimeType||t.filename||t.sourceType==="base64"))}function _i(t){if(typeof t=="string")return t.length>2e3?t.slice(0,2e3)+"... [truncated]":t;if(t&&typeof t=="object"){if(Array.isArray(t)){const n=t.map(_i).filter(r=>r!==void 0);return n.length?n:void 0}if(og(t))return;const e={};for(const n of Object.keys(t)){const r=t[n];if(n==="data"&&typeof r=="string"&&r.length>100)e[n]=`[base64 ${r.length} chars omitted]`;else{const a=_i(r);a!==void 0&&(e[n]=a)}}return Object.keys(e).length?e:void 0}return t}function Zr(t){if(typeof t=="string")return t;if(og(t))return"";try{const e=_i(t);return e===void 0?"":typeof e=="string"?e:JSON.stringify(e,null,2)}catch{return""}}function EI(t){const e=t.find(r=>r.type==="tool_call"),n=t.find(r=>r.type==="tool_result");return{name:e==null?void 0:e.name,toolCallId:(n==null?void 0:n.toolCallId)??(e==null?void 0:e.id)}}function fI(t){return t.name&&t.name.trim()?t.name:t.model&&t.model.includes("/")?t.model.split("/").pop()||null:t.model||null}function SI(t,e){const[n,r]=y.useState(t),a=y.useRef(t),i=y.useRef(null);return y.useEffect(()=>{if(!e){r(t);return}return a.current=t,i.current===null&&(i.current=requestAnimationFrame(()=>{i.current=null,r(a.current)})),()=>{i.current&&cancelAnimationFrame(i.current)}},[t,e]),n}function bI({data:t}){return u.jsx("dl",{className:"grid grid-cols-1 gap-y-2",children:Object.entries(t).map(([e,n])=>u.jsxs("div",{className:"flex",children:[u.jsxs("dt",{className:"font-semibold mr-2",children:[e,":"]}),u.jsx("dd",{className:"flex-1 break-words",children:Array.isArray(n)?n.map((r,a)=>u.jsxs("div",{className:"ml-4 break-words",children:["- ",String(r)]},a)):String(n)})]},e))})}function sg(t){if(!t)return null;if(typeof t=="object"&&!Array.isArray(t)){if(t.desirability||t.feasibility||t.viability||t.other)return{desirability:Array.isArray(t.desirability)?t.desirability:[],feasibility:Array.isArray(t.feasibility)?t.feasibility:[],viability:Array.isArray(t.viability)?t.viability:[],other:Array.isArray(t.other)?t.other:[]};if(t.output&&typeof t.output!="object")t=t.output;else if(t.output&&typeof t.output=="object")return sg(t.output)}const e=String(t),n={desirability:[],feasibility:[],viability:[],other:[]};let r=e;const a=Math.min(...["desirability=","feasibility=","viability=","other="].map(o=>{const s=r.toLowerCase().indexOf(o);return s===-1?Number.MAX_SAFE_INTEGER:s}));a!==Number.MAX_SAFE_INTEGER&&(r=r.slice(a));for(const o of Object.keys(n)){const l=new RegExp(o+"\\s*=\\s*\\[([\\s\\S]*?)\\]","i").exec(r);if(!l)continue;const c=l[1],d=/Issue\(([\s\S]*?)\)(?:,|$)/g;let _=null;for(;(_=d.exec(c))!==null;){const p=_[1],m=/title\s*=\s*(['"])([\s\S]*?)\1/.exec(p),E=/description\s*=\s*(['"])([\s\S]*?)\1/.exec(p),f=m?m[2].trim():"",g=E?E[2].trim():"";n[o].push({title:f,description:g})}}return Object.values(n).some(o=>o.length>0)?n:null}function TI({issues:t}){const e=[{key:"desirability",title:"Desirability"},{key:"feasibility",title:"Feasibility"},{key:"viability",title:"Viability"},{key:"other",title:"Other"}];return u.jsx("div",{className:ui,children:e.map(n=>{const r=t[n.key];return!r||!r.length?null:u.jsxs("div",{className:"mb-4",children:[u.jsxs("h4",{className:"font-semibold mb-2",children:[n.title," (",r.length,")"]}),u.jsx("ol",{className:"list-decimal pl-5 space-y-2",children:r.map((a,i)=>u.jsxs("li",{children:[u.jsx("div",{className:"font-medium",children:a.title}),u.jsx("div",{className:"text-sm text-muted-foreground",children:a.description})]},i))})]},n.key)})})}function gr(t){const e=t.filter(n=>n.type==="tool_result");if(e.length)try{return e.length===1?Zr(e[0].output):Zr(e.map(n=>({toolCallId:n.toolCallId,output:n.output})))}catch{}return Zr(t)}function hI(t){const e=t.find(r=>r.type==="tool_result");if(!e)return null;const n=e.output;return typeof n=="string"?n:null}const lg=(t,e)=>(t==null?void 0:t.id)??`message-${e}`,Ss=y.forwardRef(({messages:t,isStreaming:e,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:a,enableMessageEditing:i,editingMessageId:o,onStartReached:s,onEdit:l,onRegenerate:c,onCancelEdit:d,className:_,style:p,emptyMessage:m,followNewMessages:E=!0,isNavigatingCheckpoint:f=!1,onScrollAway:g,onAtBottom:S},b)=>{const h=y.useRef(null),v=y.useRef(null),C=y.useRef(!1),[R,N]=y.useState(!0),O=y.useCallback(M=>{N(M),g&&g(!M),S&&S(M)},[g,S]),I=y.useMemo(()=>{if(s)return async()=>{if(!C.current){C.current=!0;try{await s()}finally{C.current=!1}}}},[s]),D=y.useRef(!1);return y.useEffect(()=>{if(!E||f){D.current!==!1&&(D.current=!1);return}const M=e&&R?"auto":!1;D.current!==M&&(D.current=M)},[e,R,E,f]),t.length===0?u.jsx("div",{className:_,style:p,children:u.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-center max-w-md mx-auto",children:m||"No messages yet. Start a conversation!"})}):u.jsx("div",{className:_,style:p,children:u.jsx(nO,{ref:M=>{h.current=M},scrollerRef:M=>{v.current=M instanceof HTMLDivElement?M:null},data:t,followOutput:D.current,overscan:
|
|
83
|
+
`)||t.includes("```")||/[-*] /.test(t)||/#+\s/.test(t)}function pI(t){let e=t;try{(e.match(/```/g)||[]).length%2===1&&(e+="\n```"),(e.replace(/```[\s\S]*?```/g,"").match(new RegExp("(?<!`)`(?!`)","g"))||[]).length%2===1&&(e+="`")}catch{}return e}function mI(t){let e=t;try{const n=[],r=[],a="\0F",i="\0I";let o=e.replace(/```[\s\S]*?```/g,s=>(n.push(s),`${a}${n.length-1}\0`));o=o.replace(/`[^`]*`/g,s=>(r.push(s),`${i}${r.length-1}\0`)),o=o.replace(/\b([A-Za-z0-9_&\/-]+)\b(\s+\1\b)+/g,"$1").replace(/\b([A-Za-z0-9_&\/-]+\s+[A-Za-z0-9_&\/-]+)\b(\s+\1\b)+/g,"$1").replace(/([\.,;:!\?\-])\1+/g,"$1").replace(/([:;!\?\)])([A-Za-z])/g,"$1 $2").replace(/\s{3,}/g," "),o=o.replace(/\u0000F(\d+)\u0000/g,(s,l)=>n[Number(l)]??""),o=o.replace(/\u0000I(\d+)\u0000/g,(s,l)=>r[Number(l)]??""),e=o}catch{}return e}function fs(t){const e=t==null?void 0:t.trim();if(!e||!(e.startsWith("{")||e.startsWith("[")))return null;try{return JSON.parse(e)}catch{return null}}function ig({data:t}){if(Array.isArray(t))return t.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:ui,children:u.jsx("ul",{className:"list-disc pl-5",children:t.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Zr(t)});if(t&&typeof t=="object"){const e=Array.isArray(t.distilled_facts)?t.distilled_facts:null,n=Array.isArray(t.follow_up_queries)?t.follow_up_queries:null,r=typeof t.is_sufficient=="boolean"?t.is_sufficient:void 0;if(e||n||typeof r=="boolean")return u.jsxs("div",{className:ui,children:[typeof r=="boolean"&&u.jsxs("p",{children:[u.jsx("strong",{children:"Is sufficient:"})," ",r?"Yes":"No"]}),n&&n.length>0&&u.jsxs("div",{children:[u.jsx("p",{children:u.jsx("strong",{children:"Follow-up queries:"})}),u.jsx("ul",{className:"list-disc pl-5",children:n.map((i,o)=>u.jsx("li",{children:String(i)},o))})]}),e&&e.length>0&&u.jsxs("div",{children:[u.jsx("p",{children:u.jsx("strong",{children:"Facts:"})}),u.jsx("ul",{className:"list-disc pl-5",children:e.map((i,o)=>u.jsx("li",{children:String(i)},o))})]})]});const a=Object.entries(t);return u.jsx("div",{className:ui,children:u.jsx("dl",{className:"mt-0",children:a.map(([i,o])=>u.jsxs("div",{className:"mb-1",children:[u.jsxs("dt",{className:"inline font-medium mr-1",children:[i,":"]}),u.jsx("dd",{className:"inline",children:gI(o)})]},i))})})}return u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Zr(t)})}function gI(t){if(t==null)return String(t);const e=typeof t;if(e==="string"||e==="number"||e==="boolean")return String(t);if(Array.isArray(t)&&t.every(r=>r===null||["string","number","boolean"].includes(typeof r)))return t.join(", ");try{return u.jsx("code",{className:"text-xs",children:JSON.stringify(_i(t))})}catch{return String(t)}}function og(t){return!!(t&&typeof t=="object"&&(t.type==="file"||t.mimeType||t.filename||t.sourceType==="base64"))}function _i(t){if(typeof t=="string")return t.length>2e3?t.slice(0,2e3)+"... [truncated]":t;if(t&&typeof t=="object"){if(Array.isArray(t)){const n=t.map(_i).filter(r=>r!==void 0);return n.length?n:void 0}if(og(t))return;const e={};for(const n of Object.keys(t)){const r=t[n];if(n==="data"&&typeof r=="string"&&r.length>100)e[n]=`[base64 ${r.length} chars omitted]`;else{const a=_i(r);a!==void 0&&(e[n]=a)}}return Object.keys(e).length?e:void 0}return t}function Zr(t){if(typeof t=="string")return t;if(og(t))return"";try{const e=_i(t);return e===void 0?"":typeof e=="string"?e:JSON.stringify(e,null,2)}catch{return""}}function EI(t){const e=t.find(r=>r.type==="tool_call"),n=t.find(r=>r.type==="tool_result");return{name:e==null?void 0:e.name,toolCallId:(n==null?void 0:n.toolCallId)??(e==null?void 0:e.id)}}function fI(t){return t.name&&t.name.trim()?t.name:t.model&&t.model.includes("/")?t.model.split("/").pop()||null:t.model||null}function SI(t,e){const[n,r]=y.useState(t),a=y.useRef(t),i=y.useRef(null);return y.useEffect(()=>{if(!e){r(t);return}return a.current=t,i.current===null&&(i.current=requestAnimationFrame(()=>{i.current=null,r(a.current)})),()=>{i.current&&cancelAnimationFrame(i.current)}},[t,e]),n}function bI({data:t}){return u.jsx("dl",{className:"grid grid-cols-1 gap-y-2",children:Object.entries(t).map(([e,n])=>u.jsxs("div",{className:"flex",children:[u.jsxs("dt",{className:"font-semibold mr-2",children:[e,":"]}),u.jsx("dd",{className:"flex-1 break-words",children:Array.isArray(n)?n.map((r,a)=>u.jsxs("div",{className:"ml-4 break-words",children:["- ",String(r)]},a)):String(n)})]},e))})}function sg(t){if(!t)return null;if(typeof t=="object"&&!Array.isArray(t)){if(t.desirability||t.feasibility||t.viability||t.other)return{desirability:Array.isArray(t.desirability)?t.desirability:[],feasibility:Array.isArray(t.feasibility)?t.feasibility:[],viability:Array.isArray(t.viability)?t.viability:[],other:Array.isArray(t.other)?t.other:[]};if(t.output&&typeof t.output!="object")t=t.output;else if(t.output&&typeof t.output=="object")return sg(t.output)}const e=String(t),n={desirability:[],feasibility:[],viability:[],other:[]};let r=e;const a=Math.min(...["desirability=","feasibility=","viability=","other="].map(o=>{const s=r.toLowerCase().indexOf(o);return s===-1?Number.MAX_SAFE_INTEGER:s}));a!==Number.MAX_SAFE_INTEGER&&(r=r.slice(a));for(const o of Object.keys(n)){const l=new RegExp(o+"\\s*=\\s*\\[([\\s\\S]*?)\\]","i").exec(r);if(!l)continue;const c=l[1],d=/Issue\(([\s\S]*?)\)(?:,|$)/g;let _=null;for(;(_=d.exec(c))!==null;){const p=_[1],m=/title\s*=\s*(['"])([\s\S]*?)\1/.exec(p),E=/description\s*=\s*(['"])([\s\S]*?)\1/.exec(p),f=m?m[2].trim():"",g=E?E[2].trim():"";n[o].push({title:f,description:g})}}return Object.values(n).some(o=>o.length>0)?n:null}function TI({issues:t}){const e=[{key:"desirability",title:"Desirability"},{key:"feasibility",title:"Feasibility"},{key:"viability",title:"Viability"},{key:"other",title:"Other"}];return u.jsx("div",{className:ui,children:e.map(n=>{const r=t[n.key];return!r||!r.length?null:u.jsxs("div",{className:"mb-4",children:[u.jsxs("h4",{className:"font-semibold mb-2",children:[n.title," (",r.length,")"]}),u.jsx("ol",{className:"list-decimal pl-5 space-y-2",children:r.map((a,i)=>u.jsxs("li",{children:[u.jsx("div",{className:"font-medium",children:a.title}),u.jsx("div",{className:"text-sm text-muted-foreground",children:a.description})]},i))})]},n.key)})})}function gr(t){const e=t.filter(n=>n.type==="tool_result");if(e.length)try{return e.length===1?Zr(e[0].output):Zr(e.map(n=>({toolCallId:n.toolCallId,output:n.output})))}catch{}return Zr(t)}function hI(t){const e=t.find(r=>r.type==="tool_result");if(!e)return null;const n=e.output;return typeof n=="string"?n:null}const lg=(t,e)=>(t==null?void 0:t.id)??`message-${e}`,Ss=y.forwardRef(({messages:t,isStreaming:e,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:a,enableMessageEditing:i,editingMessageId:o,onStartReached:s,onEdit:l,onRegenerate:c,onCancelEdit:d,className:_,style:p,emptyMessage:m,followNewMessages:E=!0,isNavigatingCheckpoint:f=!1,onScrollAway:g,onAtBottom:S},b)=>{const h=y.useRef(null),v=y.useRef(null),C=y.useRef(!1),[R,N]=y.useState(!0),O=y.useCallback(M=>{N(M),g&&g(!M),S&&S(M)},[g,S]),I=y.useMemo(()=>{if(s)return async()=>{if(!C.current){C.current=!0;try{await s()}finally{C.current=!1}}}},[s]),D=y.useRef(!1);return y.useEffect(()=>{if(!E||f){D.current!==!1&&(D.current=!1);return}const M=e&&R?"auto":!1;D.current!==M&&(D.current=M)},[e,R,E,f]),t.length===0?u.jsx("div",{className:_,style:p,children:u.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-center max-w-md mx-auto",children:m||"No messages yet. Start a conversation!"})}):u.jsx("div",{className:_,style:p,children:u.jsx(nO,{ref:M=>{h.current=M},scrollerRef:M=>{v.current=M instanceof HTMLDivElement?M:null},data:t,followOutput:D.current,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,alignToBottom:!0,startReached:()=>{I&&I()},atBottomStateChange:O,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(M,Y)=>lg(Y,M),itemContent:(M,Y)=>{const K=lg(Y,M);return u.jsx("div",{className:"mb-4 last:mb-0","data-message-id":K,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(ag,{message:Y,messageIndex:M,isStreamingMessage:e&&n===Y.id,streamingDebounceMs:r,isEditing:o===Y.id,showActions:i,showTimestamp:!1,showAgentName:!0,layoutSize:a,truncateToolMessages:!1,toolMessagePreviewLength:200,onEdit:l,onRegenerate:()=>c(M),onCancelEdit:d})})}})})});Ss.displayName="MessageList";const pi=1e4;function CI(t){if(typeof t!="string")return String(t);const e=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>.*?<\/embed>/gi,/<form[^>]*>.*?<\/form>/gi];let n=t;for(const a of e)n=n.replace(a,"");return/<[^>]+>/.test(n)&&!/<(?!\/?(?:code|strong|em|b|i|br|p|ul|ol|li|h[1-6])\b)[^>]+>/i.test(n)?n.replace(/<code>(.*?)<\/code>/gi,"`$1`").replace(/<strong>(.*?)<\/strong>/gi,"**$1**").replace(/<b>(.*?)<\/b>/gi,"**$1**").replace(/<em>(.*?)<\/em>/gi,"*$1*").replace(/<i>(.*?)<\/i>/gi,"*$1*").replace(/<br\s*\/?>/gi,`
|
|
84
84
|
`).replace(/<p>(.*?)<\/p>/gi,`$1
|
|
85
85
|
|
|
86
86
|
`).replace(/<h([1-6])>(.*?)<\/h[1-6]>/gi,(a,i,o)=>`${"#".repeat(parseInt(i))} ${o}
|