teodor-new-chat-ui 4.3.142 → 4.3.143
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 +2 -4
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -4361,12 +4361,10 @@ function wv({
|
|
|
4361
4361
|
C((U) => {
|
|
4362
4362
|
const K = (ht) => ht.map((bt) => `${bt.threadId}:${bt.updatedAt ?? ""}:${bt.messageCount ?? ""}`).join("|"), he = Ji(U);
|
|
4363
4363
|
return K(he) === K(I) || I.length === 0 && he.length > 0 && !xt.current ? U : os(I);
|
|
4364
|
-
});
|
|
4364
|
+
}), R || _(!1);
|
|
4365
4365
|
}), P(null), xt.current || (xt.current = !0);
|
|
4366
4366
|
} catch (I) {
|
|
4367
|
-
i == null || i(String(I)), console.error("[ChatSessionProvider] Failed to refresh threads:", I), P(String(I));
|
|
4368
|
-
} finally {
|
|
4369
|
-
R || _(!1);
|
|
4367
|
+
i == null || i(String(I)), console.error("[ChatSessionProvider] Failed to refresh threads:", I), P(String(I)), R || _(!1);
|
|
4370
4368
|
}
|
|
4371
4369
|
}, [c, i]), Me = Ee(!1), Kt = Ee(null), Le = Ee(null), wt = Ee(""), [jn, Lt] = we("idle"), un = Ee({
|
|
4372
4370
|
attempts: 0,
|
package/dist/index.umd.js
CHANGED
|
@@ -35,7 +35,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
35
35
|
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=br(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ss.assertOptions(r,{silentJSONParsing:zn.transitional(zn.boolean),forcedJSONParsing:zn.transitional(zn.boolean),clarifyTimeoutError:zn.transitional(zn.boolean)},!1),o!=null&&(M.isFunction(o)?n.paramsSerializer={serialize:o}:ss.assertOptions(o,{encode:zn.function,serialize:zn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ss.assertOptions(n,{baseUrl:zn.spelling("baseURL"),withXsrfToken:zn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&M.merge(s.common,s[n.method]);s&&M.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=ln.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(l=l&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let d,f=0,h;if(!l){const m=[Ac.bind(this),void 0];for(m.unshift(...a),m.push(...c),h=m.length,d=Promise.resolve(n);f<h;)d=d.then(m[f++],m[f++]);return d}h=a.length;let p=n;for(;f<h;){const m=a[f++],g=a[f++];try{p=m(p)}catch(y){g.call(this,y);break}}try{d=Ac.call(this,p)}catch(m){return Promise.reject(m)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=br(this.defaults,t);const n=xc(t.baseURL,t.url,t.allowAbsoluteUrls);return cc(n,t.params,t.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(t){Sr.prototype[t]=function(n,r){return this.request(br(r||{},{method:t,url:n,data:(r||{}).data}))}}),M.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(br(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Sr.prototype[t]=n(),Sr.prototype[t+"Form"]=n(!0)});let vy=class Ym{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new Ur(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Ym(function(o){t=o}),cancel:t}}};function wy(e){return function(n){return e.apply(null,n)}}function by(e){return M.isObject(e)&&e.isAxiosError===!0}const Wi={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(Wi).forEach(([e,t])=>{Wi[t]=e});function Pc(e){const t=new Sr(e),n=Gl(Sr.prototype.request,t);return M.extend(n,Sr.prototype,t,{allOwnKeys:!0}),M.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pc(br(e,o))},n}const Pt=Pc(mo);Pt.Axios=Sr,Pt.CanceledError=Ur,Pt.CancelToken=vy,Pt.isCancel=pc,Pt.VERSION=_c,Pt.toFormData=es,Pt.AxiosError=Fe,Pt.Cancel=Pt.CanceledError,Pt.all=function(t){return Promise.all(t)},Pt.spread=wy,Pt.isAxiosError=by,Pt.mergeConfig=br,Pt.AxiosHeaders=ln,Pt.formToJSON=e=>fc(M.isHTMLForm(e)?new FormData(e):e),Pt.getAdapter=Nc.getAdapter,Pt.HttpStatusCode=Wi,Pt.default=Pt;const{Axios:kT,AxiosError:TT,CanceledError:ET,isCancel:IT,CancelToken:NT,VERSION:AT,all:_T,Cancel:jT,isAxiosError:PT,spread:RT,toFormData:OT,AxiosHeaders:MT,HttpStatusCode:DT,formToJSON:LT,getAdapter:FT,mergeConfig:$T}=Pt,Rc=typeof window<"u"?window.__API_BASE_URL__:void 0,Oc=Rc?Zn(Rc):void 0;function Zn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let is=null;const Vi=new Set;let Ki=null;function Mc(){return is}function qi(e){is=e,Vi.forEach(t=>t(e))}function Dc(e){return Vi.add(e),()=>Vi.delete(e)}function Sy(e){Ki=e}const Cy=3e4,ky=9e4,vn=Pt.create({...Oc?{baseURL:Oc}:{},timeout:Cy,withCredentials:!0});vn.interceptors.request.use(e=>(is&&(e.headers.Authorization=`Bearer ${is}`),e)),vn.interceptors.response.use(e=>{if(Ki&&(e!=null&&e.data))try{Ki(e.data)}catch(t){console.warn("[chat-api] Error in token sync handler:",t)}return e},e=>Promise.reject(e));async function wn(e,t){return vn.defaults.baseURL?(await vn.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Gi(e,t,n){return vn.defaults.baseURL?(await vn.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Lc(e,t,n){return vn.defaults.baseURL?(await vn.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fc(e,t){return vn.defaults.baseURL?(await vn.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function bn(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class $c{get baseUrl(){const t=vn.defaults.baseURL;return t?Zn(String(t)):""}updateConfig(t){t.baseUrl&&(vn.defaults.baseURL=Zn(String(t.baseUrl))),t.authToken!==void 0&&qi(t.authToken)}getAuthToken(){return Mc()}setAuthToken(t){qi(t)}onTokenChange(t){return Dc(t)}async listThreads(){const t=await wn("/threads"),n=bn(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Gi("/threads",t?{title:t}:void 0);return bn(r)}async updateThread(t,n){const r=await Lc(`/threads/${t}`,{title:n});return bn(r)}async deleteThread(t){const n=await Fc(`/threads/${t}`);return bn(n)}async threadInfo(t){const n=await wn(`/threads/${t}/info`);return bn(n)}async listAgents(){const t=await wn("/agents"),n=bn(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await wn(`/agents/${t}`);return bn(n)}async getAgentSchema(t){const n=await wn(`/agents/${t}/schema`);return bn(n)}async getState(t){const n=await wn(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return bn(n)}async getStateHistory(t){const n=await wn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:ky});return bn(n)}async cancelRun(t){const n=await Gi("/runs/cancel",{threadId:t});return bn(n)}async listCheckpointSummaries(t){const n=await wn(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=bn(n);return(r==null?void 0:r.items)??[]}}const sr=new $c,zc=b.createContext(null);function Ty({children:e,apiConfig:t}){const n=sr;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(zc.Provider,{value:r,children:e})}function Yi(){const e=b.useContext(zc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Ey(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Iy(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Ey(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Ny={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Xi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Wr(e,t){return`${e??""}::${t??""}`}function as(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!Xi(r))return{threadId:n,latest:null,checkpoints:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=_y(t),i=Bc(r,0);return{threadId:n,latest:i,checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Bc(e,t){if(!Xi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,P)=>Ly(_,P)).filter(_=>!!_),d=cn(e.config),f=cn(d==null?void 0:d.configurable),h=Lt(f,["checkpoint_id","checkpointId"]),p=Lt(f,["checkpoint_ns","checkpointNs"]),m=cn(e==null?void 0:e.parentConfig),g=cn(m==null?void 0:m.configurable),y=Lt(g,["checkpoint_id","checkpointId"])??null,x=Lt(g,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,C=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),T=c[c.length-1]??null,k=cn(e==null?void 0:e.metadata),S=Lt(k,["branch_label","branchLabel"]),E=Lt(g,["checkpoint_id","checkpointId"]),j=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:h??null,checkpointNs:p??null,nextCursor:y,nextCursorNs:x,interrupt:Ay(a,c,t),createdAt:C,parentId:E??null,branchLabel:S??null,lastMessageId:(T==null?void 0:T.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:k??null,config:d??null,parentConfig:m??null,next:j??null,tasks:l??null,values:i??null}}function Ay(e,t,n){const r=My(e,n);return r||Oy(t,n)}function _y(e){const t=new Map;e.forEach((o,s)=>{if(!Xi(o))return;const i=Bc(o,s);if(!(i!=null&&i.checkpointId))return;const a=Wr(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,jy(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Uc(s.createdAt??"")-Uc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function jy(e,t){return{...e,metadata:ls(e.metadata,t.metadata)??null,config:ls(e.config,t.config)??null,parentConfig:ls(e.parentConfig,t.parentConfig)??null,next:Py(e.next,t.next)??null,tasks:Ry(e.tasks,t.tasks)??null,values:ls(e.values,t.values)??null}}function ls(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Py(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Ry(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Oy(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function My(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Dy(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=yo(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=yo(r.state,`${o}-state`);if(s)return s}}return null}function Dy(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,m=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",g=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:m,interrupts:g,state:y!==void 0?y:f}}const n=cn(e);if(!n)return null;const r=Lt(n,["id","task_id","taskId"])??t,o=Lt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function yo(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Hc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=yo(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=yo(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=yo(l,t,n+1,r);if(c)return c}}return null}function Hc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=Lt(n,["type","event","kind"]),o=Lt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Hc(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Uc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ly(e,t){if(!e||typeof e!="object")return null;const n=e,r=cn(e)??{},o=cn(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Ny[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=cn(o.additional_kwargs)??cn(o.additionalKwargs),d=cn(o.response_metadata)??cn(o.responseMetadata),f=Lt(c,["createdAt","created_at"])??Lt(o,["created_at","createdAt"]),h=Lt(c,["checkpointId","checkpoint_id"]),p=Lt(c,["checkpointNs","checkpoint_ns"]),m=Fy(o.content),g={id:l,role:i,content:m};f&&(g.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(g.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(g.model=String(d.model_name)),!g.model&&typeof o.model=="string"&&(g.model=o.model),h&&(g.checkpointId=h),p&&(g.checkpointNs=p);const y=Hy(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),x=d?{...d}:void 0;y&&Object.keys(y).length&&(g.additionalKwargs=y),x&&Object.keys(x).length&&(g.responseMetadata=x);const w=$y((c==null?void 0:c.tool_calls)??o.tool_calls);if(w.length&&(g.content=[...g.content,...w]),i==="tool"){const C=zy(o,g.content);C&&(g.content=C)}return g}function Fy(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Wc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Wc(e);return t?[t]:[]}return[]}function Wc(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=Lt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=Lt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Vc(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=Lt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Vc(e,t){var s;const n=Lt(e,["id","call_id"])??t,r=Lt(e,["name"])??Lt(cn(e.function),["name"]);if(!n||!r)return null;const o=By(e.args??e.arguments??((s=cn(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function $y(e){return Array.isArray(e)?e.map((t,n)=>Vc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function zy(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function By(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function cn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Lt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function Hy(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}function Uy(e){return e.type!=="thread_info"&&e.type!=="token"}const Wy={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function Vy(e,t){var n;switch(t.type){case"reset":return{messages:Ji(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=Ji(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),o}case"prepend":{const r=Ji(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}:e}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return qc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>qc(o,s),e):e}case"interrupt_response":return{...e,messages:Gc(e.messages),pendingInterrupt:null};default:return e}}function Kc(e=[]){const[t,n]=b.useReducer(Vy,{...Wy,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function qc(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=Yy(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},h={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:h}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??Yc(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(T=>T.id===a&&T.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},h=f[a]??{lastSeq:null,lastText:Zc(d.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof h.lastSeq=="number"&&p<=h.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:h.lastSeq}),e;const{newParts:m,newMeta:g,changed:y}=Ky(d.content,t.delta,h,p);if(!y)return e;const x={...d,content:m},w=cs(l,c,x),C={...f,[a]:g};return{...e,messages:w,messagesStreamMeta:C}}if(t.type==="message_end"){const a=e.assemblingId??Yc(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(h=>{var p;return(h==null?void 0:h.type)==="text"&&((p=h.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=d.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const h=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:h}}}return e}if(t.type==="tool_start"){const a=Xc(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=Jc(e,d,c),h=f>=0?e.messages[f]:null,p=l??d[0]??`${c}-${Date.now()}`,m=(h==null?void 0:h.id)??`tool-${p}`,g=d[0]??p,y={type:"tool_call",id:g,name:c,args:t.args};if(h){const C=Qi(h,d,c,t.args),T={...h,name:h.name??c,additionalKwargs:C},k=f,S=k>=0?cs(e.messages,k,T):e.messages,E=us(T,d),j=ea(e.toolIndex,m,E);return{...e,messages:S,toolIndex:j}}const x={id:m,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:Qi(void 0,d.length?d:[g],c,t.args)},w=us(x,d.length?d:[g]);return{...e,messages:[...e.messages,x],toolIndex:ea(e.toolIndex,m,w)}}if(t.type==="tool_end"){const a=Xc(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=Jc(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",h=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,p=(d==null?void 0:d.id)??`tool-${h}`,m=us(d,a);let g=t.output;if(typeof t.output=="string")try{const S=t.output.trim();(S.startsWith("{")||S.startsWith("["))&&(g=JSON.parse(S))}catch{g=t.output}const y={type:"text",text:typeof g=="string"?g:JSON.stringify(g)},x=(d==null?void 0:d.createdAt)??new Date().toISOString(),w=Qi(d??void 0,m.length?m:a,f),C={id:p,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[y],createdAt:x,additionalKwargs:w},T=c>=0?cs(e.messages,c,C):[...e.messages,C],k=us(C,a.length?a:m);return{...e,messages:T,toolIndex:ea(e.toolIndex,p,k)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=Gy(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=as(t),l=a.interrupt,c=a.latest,d=l===null?Gc(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return e}function Ji(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function cs(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Gc(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function Yc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Xc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function Zi(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function Qi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=Zi(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function us(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=Zi(e);for(const o of r)n.add(o);return Array.from(n)}function ea(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function Jc(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(Zi(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function Zc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Ky(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??Zc(e);let l="",c=e.slice();if(s){const f=qy(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=c[c.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",m={...h,text:p+l};c=[...c.slice(0,c.length-1),m]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function Qc(e){return e.replace(/\s+/g," ").trim()}function qy(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=Qc(e),o=Qc(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function Gy(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return cs(e,r,s)}return e}function Yy(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function eu(e={}){const t=b.useMemo(()=>Zn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,h]=b.useState(""),[p,m]=b.useState(null),[g,y]=b.useState(0),[x,w]=b.useState(!1),C=b.useRef(null),T=b.useRef(!0),k=b.useRef(0),S=b.useRef(null),E=b.useRef(null),j=b.useRef(null),_=b.useRef(null),P=b.useCallback(O=>{o(O)},[]),D=b.useCallback(()=>{h(""),m(null),d(null),E.current=null,j.current=null,_.current=null},[]),z=b.useCallback(()=>{var O;console.debug("[use-chat] stop() invoked - aborting stream"),(O=C.current)==null||O.abort(),C.current=null,S.current=null,l(!1),w(!1),k.current=0,y(0)},[]),B=b.useCallback((O,H,R)=>{C.current&&(C.current.abort(),C.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),m(null),E.current=null,j.current=null,_.current=null;const V=new AbortController;C.current=V;let $=null,F=null,ne=!1;return S.current={threadId:O.threadId??null,headers:{}},(async()=>{var ye,je,J,ue,ke,te,L,q,ie,ce,U,We,re,xe,Pe,$e,rt,Se;const Q=Ye=>{var ot;try{const et=JSON.parse(JSON.stringify(Ye));return(ot=et==null?void 0:et.payload)!=null&&ot.files_info&&Array.isArray(et.payload.files_info)&&(et.payload.files_info=et.payload.files_info.map(Xe=>({...Xe,data:Xe!=null&&Xe.data?`<base64 ${String(Xe.data).length} chars>`:Xe==null?void 0:Xe.data}))),et}catch{return Ye}};try{let Ye={};try{if(r)Ye={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ve=window.__AUTH_TOKEN__,Mt=((ye=window.localStorage)==null?void 0:ye.getItem("authToken"))||null;let _t=null;try{const Te=(je=window.localStorage)==null?void 0:je.getItem("chat-settings");Te&&(_t=((J=JSON.parse(Te))==null?void 0:J.apiKey)||null)}catch{}const G=Ve||Mt||_t||null;G&&(Ye={Authorization:`Bearer ${G}`})}}catch{}console.debug("[use-chat] POST",t+n,Q(O));let ot={};if(typeof window<"u")try{const ft=(ue=window.localStorage)==null?void 0:ue.getItem("authSessionId");ft&&(ot={"X-Session-Id":ft})}catch{}const et={...Ye,...ot,...s.current},Xe={"Content-Type":"application/json",Accept:"text/event-stream",...et},Ke=await fetch(t+n,{method:"POST",headers:Xe,body:JSON.stringify(O),signal:V.signal,credentials:i});if(S.current&&(S.current.headers=et),!Ke.ok||!Ke.body){const ft=await Ke.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ke.status,ft==null?void 0:ft.slice(0,500));const Ve=`stream ${Ke.status}${ft?": "+ft:""}`;throw(ke=R==null?void 0:R.onConnectionError)==null||ke.call(R,Ve),ne=!0,$="error",F=Ve,new Error(Ve)}w(!0);const tt=Ke.body.getReader(),Ot=new TextDecoder;let St="",nt=[];k.current=0,y(0);let yt=0,Nt=null;const st=()=>{if(nt.length){const ft=nt.join("");nt=[],T.current&&h(Ve=>Ve+ft)}Nt=null},Gt=()=>{typeof window<"u"&&Nt==null&&(Nt=requestAnimationFrame(st))};let Yt=Date.now();const Xt=setInterval(()=>{var ft;if(Date.now()-Yt>18e5){const Ve="Stream idle timeout";d(Ve),$="error",F=Ve,V.abort(),(ft=R==null?void 0:R.onError)==null||ft.call(R,Ve)}},5e3),Jt=1024*1024;try{const ft=Ke.headers.get("X-Thread-Id")||Ke.headers.get("x-thread-id"),Ve=Ke.headers.get("X-Thread-Created")||Ke.headers.get("x-thread-created"),Mt=ft??null,_t=String(Ve??"").toLowerCase()==="true";for(S.current&&!S.current.threadId&&(S.current={...S.current,threadId:Mt}),(te=R==null?void 0:R.onOpen)==null||te.call(R,{threadId:Mt,created:_t});;){const{value:G,done:Te}=await tt.read();if(Te)break;St+=Ot.decode(G,{stream:!0}),St.length>Jt&&(St="",console.warn("Stream buffer reset: exceeded 1MB"));let ve;for(;(ve=St.indexOf(`
|
|
36
36
|
|
|
37
37
|
`))>=0;){const pt=St.slice(0,ve);St=St.slice(ve+2);const mt=Jy(pt);if(!mt)continue;let ct;try{ct=JSON.parse(mt)}catch{console.debug("[use-chat] malformed SSE:",mt.slice(0,200));continue}const Me=Xy(ct)?ct.data:ct;Yt=Date.now();const Ut=Me.seq;if(Ut!==void 0){if(Ut<=yt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Ut,lastProcessedSeq:yt,type:Me.type});continue}yt>0&&Ut>yt+1&&((L=R==null?void 0:R.onGap)==null||L.call(R,{from:yt,to:Ut})),yt=Ut,k.current=Ut,y(Ut)}if(console.debug("[use-chat] received event",{seq:Me.seq,type:Me.type,preview:(()=>{var Le;try{return Me.type==="message_delta"?{deltaTypes:(Le=Me.delta)==null?void 0:Le.map(xt=>xt.type),textLen:(Me.delta||[]).filter(xt=>xt.type==="text").map(xt=>String(xt.text||"").length)}:Me.content||Me.delta?{hasContent:!0}:{}}catch(xt){return{err:String(xt)}}})()}),Me.type==="checkpoint")E.current=Me.checkpointId??null,j.current=Me.checkpointNs??null,m(Me.checkpointId??null);else if(Me.type==="state_history"){_.current=Me;try{const xt=as(Me).latest;xt&&(E.current=xt.checkpointId??null,j.current=xt.checkpointNs??null,m(xt.checkpointId??null))}catch(Le){console.warn("[use-chat] Failed to hydrate state_history payload",Le)}}try{H==null||H(Me)}catch(Le){console.error("[use-chat] Error in onEvent callback:",Le,"for event:",Me.type)}if(Me.type==="token"&&e.autoAppendAssistant!==!1)nt.push(Me.content),Gt();else if(Me.type==="message_delta"){const Le=Me.delta.filter(xt=>xt.type==="text").map(xt=>xt.text).join("");Le&&e.autoAppendAssistant!==!1&&(nt.push(Le),Gt())}else if(Me.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(q=R==null?void 0:R.onHeartbeat)==null||q.call(R,Me)}catch(Le){console.warn("[use-chat] heartbeat callback failed",Le)}}else if(Nt!==null&&cancelAnimationFrame(Nt),st(),Me.type==="checkpoint")m(Me.checkpointId);else if(Me.type==="error"){const Le=Me;if(d(Le.message),$="error",F=Le.message,Le.error_type==="auth_error"||Le.code==="TOKEN_EXPIRED"||((ie=Le.message)==null?void 0:ie.includes("token"))||((ce=Le.message)==null?void 0:ce.includes("401"))||((U=Le.message)==null?void 0:U.includes("unauthorized"))||((We=Le.message)==null?void 0:We.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Le.message);try{(re=R==null?void 0:R.onAuthError)==null||re.call(R,Le.message)}catch(Ln){console.warn("[use-chat] onAuthError handler failed",Ln)}V.abort()}}}}st(),$===null&&!V.signal.aborted&&($="complete")}catch(ft){if(ft.name==="AbortError")$=$??"aborted";else{const Ve=ft.message||String(ft);$="error",F=Ve,d(Ve),(xe=R==null?void 0:R.onError)==null||xe.call(R,Ve)}}finally{try{await tt.cancel()}catch{}finally{(Pe=tt.releaseLock)==null||Pe.call(tt)}Nt!==null&&typeof window<"u"&&window.cancelAnimationFrame(Nt),clearInterval(Xt)}}catch(Ye){if(Ye.name==="AbortError")$=$??"aborted";else{const ot=Ye.message||String(Ye);$="error",F=ot,d(ot),($e=R==null?void 0:R.onError)==null||$e.call(R,ot),ne||((rt=R==null?void 0:R.onConnectionError)==null||rt.call(R,ot),ne=!0)}}finally{const Ye=k.current,ot=E.current,et=j.current,Xe=_.current,Ke=$??(V.signal.aborted?"aborted":F?"error":"complete");try{(Se=R==null?void 0:R.onClosed)==null||Se.call(R,{reason:Ke,lastSeq:Ye,lastCheckpointId:ot,lastCheckpointNs:et,lastStateHistory:Xe,error:F})}catch(tt){console.warn("[use-chat] onClosed callback failed",tt)}l(!1),w(!1),C.current=null,k.current=0,y(0),S.current=null}})(),{close:()=>V.abort()}},[t,n,r,e.autoAppendAssistant]);return b.useEffect(()=>()=>{var O;T.current=!1,(O=C.current)==null||O.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:p,lastSeq:g,connected:x,stream:B,stop:z,clear:D,setToken:P}}function Xy(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Jy(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
|
|
38
|
-
`)}const tu=200;function Zy({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o,onStreamClosed:s,onConnectionError:i,onAuthError:a,onHeartbeat:l}){const c=b.useRef(null),d=b.useRef(null),f=b.useRef(new Map),h=b.useRef(null),p=b.useCallback(_=>{try{const P=globalThis.structuredClone;if(typeof P=="function")return P(_)}catch{}try{return JSON.parse(JSON.stringify(_))}catch{return _}},[]),m=b.useCallback((_,P)=>{if(!_)return;const D=f.current.get(_)??[],z=p(P),B=D.length>=tu?[...D.slice(D.length-tu+1),z]:[...D,z];f.current.set(_,B)},[p]),g=b.useCallback(_=>{_&&f.current.set(_,[])},[]),y=b.useCallback(_=>{const P=_??d.current;if(!P)return;const D=f.current.get(P);D!=null&&D.length&&D.forEach(z=>{try{n(z)}catch(B){console.error("[useChatStreamingService] Failed to replay buffered event",B)}})},[n]),x=b.useCallback(_=>{var z,B,O,H,R;const P=_.seq??null;if(P!==null){const V=c.current;if(V!==null){if(P<=V)return;P>V+1&&(o==null||o({from:V,to:P}))}c.current=P}if(_.type==="thread_info"){d.current=_.threadId,h.current&&(h.current.threadIdGuess=_.threadId),g(_.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",_);try{t(_)}catch(V){console.error("[useChatStreamingService] Error in onThreadInfo handler:",V)}return}if(_.type==="heartbeat"){try{l==null||l(_)}catch(V){console.error("[useChatStreamingService] Error in onHeartbeat handler:",V)}return}if(_.type==="error"){const V=_;if(V.error_type==="auth_error"||V.code==="TOKEN_EXPIRED"||((z=V.message)==null?void 0:z.includes("token"))||((B=V.message)==null?void 0:B.includes("401"))||((O=V.message)==null?void 0:O.includes("unauthorized"))||((H=V.message)==null?void 0:H.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",V.message);try{a==null||a(V.message)}catch(F){console.warn("[useChatStreamingService] onAuthError handler failed",F)}}}const D=_.threadId??(_.type==="state_history"?_.threadId:void 0)??d.current??((R=h.current)==null?void 0:R.threadIdGuess)??null;if(_.type==="state_history"&&(d.current=D??d.current),Uy(_)){_.type==="checkpoint"||_.type==="state_history"?g(D??null):m(D??null,_);try{n(_)}catch(V){console.error("[useChatStreamingService] Error in onMessageEvent handler:",V)}return}try{r==null||r(_)}catch(V){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",V)}},[m,g,n,o,t,r]),{stream:w,stop:C,isStreaming:T,error:k,setToken:S}=eu({baseUrl:e,token:void 0}),E=b.useCallback((_,P)=>{c.current=null,d.current=_.threadId??null,h.current={request:_,callbacks:P,manualStop:!1,threadIdGuess:_.threadId??null},w(_,x,{onOpen:P==null?void 0:P.onOpen,onError:D=>{var z;(z=P==null?void 0:P.onError)==null||z.call(P,D)},onGap:(P==null?void 0:P.onGap)??o,onConnectionError:D=>{var z;i==null||i(D),(z=P==null?void 0:P.onConnectionError)==null||z.call(P,D)},onAuthError:D=>{var z;a==null||a(D),(z=P==null?void 0:P.onAuthError)==null||z.call(P,D)},onHeartbeat:D=>{var z;try{l==null||l(D)}catch(B){console.warn("[useChatStreamingService] onHeartbeat handler failed",B)}try{(z=P==null?void 0:P.onHeartbeat)==null||z.call(P,D)}catch(B){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",B)}},onClosed:D=>{var H,R,V,$;const z=((H=h.current)==null?void 0:H.manualStop)??!1,B=d.current??((R=h.current)==null?void 0:R.threadIdGuess)??((V=D.lastStateHistory)==null?void 0:V.threadId)??null;(D.reason==="complete"||D.reason==="aborted"&&z)&&g(B);const O={...D,threadId:B,manualStop:z};try{s==null||s(O)}catch(F){console.warn("[useChatStreamingService] onStreamClosed handler failed",F)}try{($=P==null?void 0:P.onClosed)==null||$.call(P,O)}catch(F){console.warn("[useChatStreamingService] downstream onClosed handler failed",F)}h.current&&(h.current=null)}})},[g,x,a,i,l,o,s,w]),j=b.useCallback(()=>{h.current&&(h.current.manualStop=!0),C()},[C]);return b.useMemo(()=>({startStream:E,stop:j,isStreaming:T,error:k,setAuthToken:S,replayBufferedEvents:y}),[E,j,T,k,S,y])}const nu=50,Qy=750,ta="chat-history@1",ex=5,tx=1e3,nx=15e3,ds=300;function ru(e,t=ds){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:t});return}catch{}window.setTimeout(e,t)}function Cr(){return typeof window<"u"&&typeof window.localStorage<"u"}function na(e){if(!Cr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function ra(e,t){if(!Cr())return!1;try{return window.localStorage.setItem(e,t),!0}catch{return!1}}function oa(e){if(Cr())try{window.localStorage.removeItem(e)}catch{}}function sa(e){return e==null?e:{...e}}function rx(e){return e==null?e:{...e}}function ox(e){if(Array.isArray(e))return e.slice();if(e==null)return e}function sx(e){if(Array.isArray(e))return e.map(t=>({...t}));if(e==null)return e}function un(e,t={}){const n=t.cloneMessages??!1,r=Array.isArray(e==null?void 0:e.messages)?e.messages:[],o=sa(e==null?void 0:e.metadata),s=sa(e==null?void 0:e.config),i=sa(e==null?void 0:e.parentConfig),a=ox(e==null?void 0:e.next),l=sx(e==null?void 0:e.tasks),c=rx(e==null?void 0:e.values),d={checkpointId:(e==null?void 0:e.checkpointId)??null,checkpointNs:(e==null?void 0:e.checkpointNs)??null,createdAt:(e==null?void 0:e.createdAt)??null,parentId:(e==null?void 0:e.parentId)??null,branchLabel:(e==null?void 0:e.branchLabel)??null,lastMessageId:(e==null?void 0:e.lastMessageId)??null,messagesLen:typeof(e==null?void 0:e.messagesLen)=="number"?e.messagesLen:r.length,hasMessages:typeof(e==null?void 0:e.hasMessages)=="boolean"?e.hasMessages:r.length>0,messages:n?r.slice():r,nextCursor:(e==null?void 0:e.nextCursor)??null,nextCursorNs:(e==null?void 0:e.nextCursorNs)??null,interrupt:(e==null?void 0:e.interrupt)??null};return o!==void 0&&(d.metadata=o),s!==void 0&&(d.config=s),i!==void 0&&(d.parentConfig=i),a!==void 0&&(d.next=a),l!==void 0&&(d.tasks=l),c!==void 0&&(d.values=c),d}function ix(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function ou(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}function ia(e,t){return`${e}${t}`}function ax(e,t){const n=na(ia(e,t));if(!n)return null;try{const r=JSON.parse(n);return typeof(r==null?void 0:r.threadId)!="string"?null:{threadId:r.threadId,snapshot:un(r.snapshot,{cloneMessages:!0}),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0}}catch{return null}}function lx(e,t,n=100){if(!Cr())return;const r=un(t.snapshot,{cloneMessages:!0}),o={threadId:t.threadId,snapshot:{...r,messages:r.messages.slice(-n)},updatedAt:Date.now()},s=ia(e,t.threadId),i=JSON.stringify(o);if(!ra(s,i))try{const a=[];for(let l=0;l<window.localStorage.length;l++){const c=window.localStorage.key(l);if(!c||c===s||!c.startsWith(e))continue;const d=window.localStorage.getItem(c);if(!d){a.push({key:c,updatedAt:0});continue}try{const f=JSON.parse(d),h=typeof(f==null?void 0:f.updatedAt)=="number"&&Number.isFinite(f.updatedAt)?f.updatedAt:0;a.push({key:c,updatedAt:h})}catch{a.push({key:c,updatedAt:0})}}a.sort((l,c)=>l.updatedAt-c.updatedAt);for(const l of a)if(window.localStorage.removeItem(l.key),ra(s,i))break}catch{}}function cx(e,t){oa(ia(e,t))}function ux(e){if(Cr())try{for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n&&n.startsWith(e)&&window.localStorage.removeItem(n)}}catch{}}function su(e,t,n){return`${e}__${t??""}__${n??""}`}function fs(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?{...e}:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function dx(e,t){return fs(e,t)}function fx(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function hx(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function iu(e,t){const n=fs(e.metadata,t.metadata),r=fs(e.config,t.config),o=fs(e.parentConfig,t.parentConfig),s=fx(e.next,t.next),i=hx(e.tasks,t.tasks),a=dx(e.values,t.values),l={};return n!==void 0&&(l.metadata=n??null),r!==void 0&&(l.config=r??null),o!==void 0&&(l.parentConfig=o??null),s!==void 0&&(l.next=s??null),i!==void 0&&(l.tasks=i??null),a!==void 0&&(l.values=a??null),l}function au(e){return Array.isArray(e)?e.filter(t=>!!(t&&(t.checkpointId||t.checkpointNs))).map(t=>{const n=un(t,{cloneMessages:!0});return{...n,messages:Array.isArray(n.messages)?n.messages:[],values:n.values??null}}):[]}const px="cachedThreads",mx="v1",aa=200;function gx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function la(e,t){return`cachedThreads:v1:${e}:${gx(t||"anon")}`}function yx(){const e=na(px);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function xx(e){const t=na(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function ca(e,t){ra(e,JSON.stringify(t))}function ua(e){const t=xx(e);if(t.length>0)return t;const n=yx();if(n.length>0)try{ca(e,n.slice(0,aa))}catch{}return n}function hs(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function da(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function vx({currentThreadId:e,currentThreadIdRef:t}){const[n,r]=b.useState([]),o=b.useRef(new Map),s=b.useRef(new Map),i=b.useCallback(m=>{if(!m){r([]);return}const g=o.current.get(m);if(!g||!g.length){r([]);return}r(g.map(y=>un(y,{cloneMessages:!0})))},[]);b.useEffect(()=>{i(e)},[e,i]);const a=b.useCallback((m,g,y)=>{if(!m)return;const x=y==="replace"?[]:o.current.get(m)??[],w=y==="replace"?g:[...g,...x];if(!w.length){y==="replace"&&o.current.set(m,[]),m===t.current&&r([]);return}const C=new Map;for(const k of w){if(!(k!=null&&k.checkpointId))continue;const S=`${k.checkpointId}::${k.checkpointNs??""}`,E=un(k,{cloneMessages:!0}),j=C.get(S);if(!j){C.set(S,E);continue}const _=iu(j,E);C.set(S,{...j,..._})}const T=Array.from(C.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});o.current.set(m,T),m===t.current&&i(m)},[t,i]),l=b.useCallback((m,g,y)=>{if(!m)return;const x=s.current.get(m),w=y==="replace"||!x?new Map:new Map(x);if(g&&typeof g=="object")for(const[C,T]of Object.entries(g)){if(!(T!=null&&T.checkpointId))continue;const k=C||Wr(T.checkpointId,T.checkpointNs??null);w.set(k,un(T,{cloneMessages:!0}))}s.current.set(m,w)},[]),c=b.useCallback((m,g)=>{if(!m)return!1;const y=au(g);if(!y.length)return!1;const x=o.current.get(m)??[],w=new Map,C=(k,{preferExisting:S})=>{for(const E of k){if(!(E!=null&&E.checkpointId)&&!(E!=null&&E.checkpointNs))continue;const j=Wr(E.checkpointId??null,E.checkpointNs??null);j&&(S&&w.has(j)?w.set(j,E):w.has(j)&&S||w.set(j,E))}};C(y,{preferExisting:!1}),C(x,{preferExisting:!0});const T=Array.from(w.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});return o.current.set(m,T),m===t.current&&r(T.map(k=>un(k,{cloneMessages:!0}))),!0},[t]),d=b.useCallback(m=>{m&&(o.current.delete(m),s.current.delete(m),m===t.current&&r([]))},[t]),f=b.useCallback(()=>{r([])},[]),h=b.useCallback(m=>m?s.current.get(m)??null:null,[]),p=b.useCallback((m,g)=>{var y;if(m)return(y=s.current.get(m))==null?void 0:y.get(g)},[]);return{threadCheckpoints:n,syncActiveThreadCheckpoints:i,updateCheckpointCache:a,updateCheckpointSnapshots:l,applyCheckpointSummaries:c,clearThreadCaches:d,resetThreadCheckpoints:f,getSnapshotCache:h,getSnapshotFromCache:p}}const lu=b.createContext(null),cu=b.createContext(null),uu=b.createContext(null),wx=b.createContext(!1);function bx({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onAuthError:a,onThreadChange:l}){const{api:c,baseUrl:d}=Yi(),f=b.useMemo(()=>Zn(d),[d]),h=b.useMemo(()=>{try{return new URL(d).host}catch{return"unknown"}},[d]),p=b.useMemo(()=>`threadPayload:${mx}:${h}:`,[h]),m=b.useCallback(I=>ax(p,I),[p]),g=b.useCallback((I,A=100)=>{lx(p,I,A)},[p]),y=b.useCallback(I=>{cx(p,I)},[p]),x=b.useCallback(()=>{ux(p)},[p]),[w,C]=b.useState(()=>{var I;return la(h,(I=c.getAuthToken)==null?void 0:I.call(c))}),[T,k]=b.useState(()=>{var A;const I=ua(la(h,(A=c.getAuthToken)==null?void 0:A.call(c)));return hs(I)}),S=b.useMemo(()=>da(T),[T]),[E,j]=b.useState(t),[_,P]=b.useState(!1),[D,z]=b.useState(!1),[B,O]=b.useState(null),[H,R]=b.useState(null),[V,$]=b.useState(null),F=b.useCallback(()=>{const I=ua(w);b.startTransition(()=>{k(hs(I))})},[w]),[ne,Q]=b.useState(!1),[ye,je]=b.useState(!1),[J,ue]=b.useState(null),[ke,te]=b.useState(void 0),[L,q]=b.useState(void 0),[ie,ce]=b.useState(void 0),{state:U,dispatch:We,seed:re,prepend:xe,pushUser:Pe,onEvent:$e,reset:rt}=Kc(),Se=b.useRef(E);b.useEffect(()=>{Se.current=E},[E]);const Ye=b.useRef(!1),ot=b.useRef([]),et=b.useRef(null),Xe=b.useRef(null),Ke=b.useRef(new Map),tt=b.useRef(E),Ot=b.useRef(!1),St=b.useRef(null),nt=b.useRef(new Map),yt=b.useRef(new Map),{threadCheckpoints:Nt,syncActiveThreadCheckpoints:st,updateCheckpointCache:Gt,updateCheckpointSnapshots:Yt,applyCheckpointSummaries:Xt,clearThreadCaches:Jt,resetThreadCheckpoints:ft,getSnapshotCache:Ve,getSnapshotFromCache:Mt}=vx({currentThreadId:E,currentThreadIdRef:Se}),_t=b.useCallback(()=>{var K;const I=yt.current;if(I.size<=nu)return;const A=Array.from(I.entries()).sort((fe,le)=>fe[1].timestamp-le[1].timestamp),W=I.size-nu;for(let fe=0;fe<W;fe++){const le=(K=A[fe])==null?void 0:K[0];le&&I.delete(le)}},[]),G=b.useCallback((I,A)=>{if(!I)return null;const W=Array.isArray(I.checkpoints)?I.checkpoints:[];return W.length===0?null:{version:I.version===ta?I.version:ta,threadId:I.threadId??A,checkpoints:W}},[]),Te=b.useCallback((I,A)=>{const{threadId:W,checkpointId:K=null,checkpointNs:fe=null}=I,le=su(W,K,fe);if(A!=null&&A.force)nt.current.delete(le),yt.current.delete(le);else{if(A!=null&&A.preferCache){const kt=yt.current.get(le);if(kt)return Promise.resolve(kt.result)}const Be=nt.current.get(le);if(Be)return Be}const bt=(async()=>{try{const Be=await c.getStateHistory({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0}),kt=G(Be,W);if(kt)return{payload:kt,usedHistoryApi:!0};throw new Error("History response missing checkpoints")}catch(Be){console.warn("[ChatSessionProvider] getStateHistory failed, falling back to getState:",Be);const kt=await c.getState({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0});return{payload:{version:ta,threadId:W,checkpoints:[kt]},usedHistoryApi:!1}}})().then(Be=>(yt.current.set(le,{result:Be,timestamp:Date.now()}),_t(),Be)).finally(()=>{nt.current.get(le)===bt&&nt.current.delete(le)});return nt.current.set(le,bt),bt},[c,G,_t]),ve=b.useCallback((I,A)=>new Promise((W,K)=>{const fe=async()=>{Ye.current=!0;try{await I(),W()}catch(le){K(le)}finally{Ye.current=!1;const le=ot.current.shift();le&&le().catch(()=>{})}};Ye.current?ot.current.push(fe):fe().catch(le=>{K(le)})}),[]),pt=b.useRef(S.length),mt=b.useRef(!1);b.useEffect(()=>{pt.current=S.length},[S.length]),b.useEffect(()=>{const I=U.pendingInterrupt??ix(U.messages);ou(V,I)||$(I??null)},[V,U.messages,U.pendingInterrupt]);const ct=b.useCallback(async()=>{const I=pt.current>0;I||P(!0);try{const A=await c.listThreads();b.startTransition(()=>{k(W=>{const K=ht=>ht.map(bt=>`${bt.threadId}:${bt.updatedAt??""}:${bt.messageCount??""}`).join("|"),fe=da(W);return K(fe)===K(A)||A.length===0&&fe.length>0&&!mt.current?W:hs(A)})}),O(null),mt.current||(mt.current=!0)}catch(A){i==null||i(String(A)),console.error("[ChatSessionProvider] Failed to refresh threads:",A),O(String(A))}finally{I||P(!1)}},[c,i]),Me=b.useRef(!1),Ut=b.useRef(null),Le=b.useRef(null),xt=b.useRef(""),[Ln,Dt]=b.useState("idle"),fn=b.useRef({attempts:0,timer:null,reason:null}),io=b.useRef(null),ao=b.useRef(0),Lr=b.useRef(()=>{}),Fr=b.useRef(()=>{}),N=b.useRef(()=>{}),Y=I=>{if(!I||typeof I!="object")return!1;const A=I;return A.code==="ECONNABORTED"?!0:(typeof A.message=="string"?A.message.toLowerCase():"").includes("timeout")},ae=b.useCallback(async I=>{const A=await c.listCheckpointSummaries(I);return au(A??[])},[c]),Ce=b.useCallback((I,A)=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const W=I.map(fe=>`${fe.threadId}:${fe.updatedAt??""}:${fe.messageCount??""}`).join("|");if(I.length===0){try{oa(w)}catch{}xt.current="";return}if(W===xt.current)return;const K=()=>{try{const fe=I.slice(0,aa);ca(w,fe),xt.current=W}catch{}finally{Le.current=null}};if(A!=null&&A.immediate){K();return}Le.current=window.setTimeout(()=>{ru(K)},ds)},[w]),Ge=b.useCallback(()=>{Ce(S,{immediate:!0})},[Ce,S]),qe=b.useCallback((I,A,W,K)=>{var Ul;const fe=W??Se.current;if(!fe)return;const le=un(I),ht=fe===Se.current,bt=(K==null?void 0:K.persist)!==!1;if(A==="replace"){if(bt){const Vt={threadId:fe,snapshot:un(I,{cloneMessages:!0})};Ke.current.set(fe,Vt),tt.current=fe}if(!ht)return;re(le.messages,{checkpointId:le.checkpointId??null,checkpointNs:le.checkpointNs??null,pendingInterrupt:le.interrupt??null}),$(le.interrupt??null),ue(le.nextCursor??null),Q(!!le.nextCursor),te(le.checkpointId??void 0),q(le.checkpointNs??void 0),ce(le.nextCursorNs??void 0);return}const Be=Ke.current.get(fe),kt=(Be==null?void 0:Be.snapshot)??null,Ht=Array.isArray(kt==null?void 0:kt.messages)?kt.messages:[],pn=un(kt),Jn=Array.isArray(I==null?void 0:I.messages)?I.messages:[],Wt=new Set,jt=[...Jn,...Ht].filter(Vt=>{const Wl=Vt==null?void 0:Vt.id;return Wl?Wt.has(Wl)?!1:(Wt.add(Wl),!0):!0}),or=iu(pn,le),$r={checkpointId:pn.checkpointId??le.checkpointId??null,checkpointNs:pn.checkpointNs??le.checkpointNs??null,createdAt:le.createdAt??pn.createdAt??null,parentId:le.parentId??pn.parentId??null,branchLabel:le.branchLabel??pn.branchLabel??null,lastMessageId:((Ul=jt[jt.length-1])==null?void 0:Ul.id)??null,messagesLen:jt.length,hasMessages:jt.length>0,messages:jt,nextCursor:le.nextCursor??pn.nextCursor??null,nextCursorNs:le.nextCursorNs??pn.nextCursorNs??null,interrupt:pn.interrupt??le.interrupt??null,...or};if(Ke.current.set(fe,{threadId:fe,snapshot:un($r,{cloneMessages:!0})}),!ht)return;Jn.length&&xe(Jn);const lo=I&&Object.prototype.hasOwnProperty.call(I,"checkpointId")?I.checkpointId:void 0,An=I&&Object.prototype.hasOwnProperty.call(I,"checkpointNs")?I.checkpointNs:void 0,zr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursor")?I.nextCursor:void 0,xr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursorNs")?I.nextCursorNs:void 0;ue(Vt=>zr!==void 0?zr??Vt??null:Vt??null),Q(Vt=>zr!==void 0?!!zr:Vt),te(Vt=>lo!==void 0?lo??Vt??void 0:Vt??void 0),q(Vt=>An!==void 0?An??Vt??void 0:Vt??void 0),ce(Vt=>xr!==void 0?xr??void 0:Vt)},[xe,re,$]),He=b.useCallback(I=>{if(I.threadId!=null&&I.threadId!==Se.current)return;const A=un(I.snapshot,{cloneMessages:!0});re(A.messages,{checkpointId:A.checkpointId??null,checkpointNs:A.checkpointNs??null,pendingInterrupt:A.interrupt??null}),$(A.interrupt??null),ue(A.nextCursor??null),Q(!!A.nextCursor),te(A.checkpointId??void 0),q(A.checkpointNs??void 0),ce(A.nextCursorNs??void 0),tt.current=I.threadId,st(I.threadId??Se.current??null)},[re,$,st]),Re=b.useCallback(I=>{if(!I)return;Ke.current.delete(I),y(I),Jt(I);const A=`${I}__`;for(const W of nt.current.keys())W.startsWith(A)&&nt.current.delete(W);for(const W of yt.current.keys())W.startsWith(A)&&yt.current.delete(W);tt.current===I&&(tt.current=null)},[Jt,y]),At=b.useCallback(()=>{const I=Se.current;I&&Re(I),rt([]),Q(!1),je(!1),ue(null),te(void 0),q(void 0),ce(void 0)},[Re,rt]),gt=b.useCallback(({from:I,to:A})=>{const W=Se.current;W&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${I} -> ${A}) for thread ${W}`)},[]),Ct=b.useCallback(I=>{const A=I.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:A,title:I.title,created:I.created,currentThreads:S.length});const W={threadId:A,title:I.title||`Thread ${A.slice(0,8)}`,createdAt:I.createdAt||new Date().toISOString(),updatedAt:I.updatedAt||new Date().toISOString(),messageCount:I.messageCount||0};Se.current!==A&&(!Se.current&&U.messages.length<=1&&(Xe.current=A),j(A)),b.startTransition(()=>{k(K=>{const fe=K.byId[A];return fe?fe.title===W.title&&fe.updatedAt===W.updatedAt&&fe.messageCount===W.messageCount?K:{byId:{...K.byId,[A]:W},order:K.order}:{byId:{...K.byId,[A]:W},order:[A,...K.order]}})})},[U.messages.length]),{startStream:Zt,stop:Fn,isStreaming:hn,error:zt,setAuthToken:$n,replayBufferedEvents:Z}=Zy({baseUrl:f,onThreadInfo:Ct,onMessageEvent:$e,onUnhandledEvent:I=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${I.type}`,I)},onSequenceGap:gt,onStreamClosed:I=>{Lr.current(I)},onConnectionError:I=>{Fr.current(I)},onAuthError:a,onHeartbeat:I=>{N.current(I)}}),se=b.useCallback(()=>{const I=fn.current;I.timer!==null&&(window.clearTimeout(I.timer),I.timer=null),I.reason=null},[]),de=b.useCallback((I,A)=>{Dt("connecting"),Zt(I,{onOpen:W=>{var K;se(),fn.current.attempts=0,Dt("connected"),(K=A==null?void 0:A.onOpen)==null||K.call(A,W)},onError:W=>{var K;(K=A==null?void 0:A.onError)==null||K.call(A,W)},onGap:(A==null?void 0:A.onGap)??gt,onConnectionError:W=>{var K;Fr.current(W),(K=A==null?void 0:A.onConnectionError)==null||K.call(A,W)},onHeartbeat:W=>{var K;N.current(W),(K=A==null?void 0:A.onHeartbeat)==null||K.call(A,W)},onClosed:W=>{var K;Lr.current(W),(K=A==null?void 0:A.onClosed)==null||K.call(A,W)}})},[se,gt,Dt,Zt]),Ie=b.useCallback(()=>{const I=Se.current;if(!I)return null;const A=io.current,W=U.lastCheckpointId??(A==null?void 0:A.lastCheckpointId)??null,K=U.lastCheckpointNs??(A==null?void 0:A.lastCheckpointNs)??null,fe={};return W&&(fe.checkpointId=W),K&&(fe.checkpointNs=K),{threadId:I,checkpointId:W,checkpointNs:K,command:{kind:"resume",value:fe}}},[U.lastCheckpointId,U.lastCheckpointNs]),lt=b.useCallback(I=>{const A=fn.current;if(A.timer!==null)return;if(A.attempts>=ex){Dt("error");return}A.attempts+=1,A.reason=I;const W=Math.min(tx*Math.pow(2,A.attempts-1),nx);Dt("reconnecting"),A.timer=window.setTimeout(()=>{A.timer=null,A.reason=null;const K=Ie();if(!K){Dt("error");return}Z(K.threadId??void 0),de(K)},W)},[Ie,Z,Dt,de]),Je=b.useCallback(I=>{var A;if(io.current=I,I.manualStop||I.reason==="complete"){se(),fn.current.attempts=0,Dt("idle");return}if(I.error&&(I.error.includes("token")||I.error.includes("401")||I.error.includes("unauthorized")||I.error.includes("Unauthorized")||I.error.includes("TOKEN_EXPIRED")||I.error.includes("auth_error"))){console.error("[ChatSessionProvider] Auth error detected:",I.error);try{a==null||a(I.error)}catch(K){console.error("[ChatSessionProvider] Error in onAuthError handler:",K)}return}if(I.reason==="error"||I.reason==="aborted"){if((A=I.error)!=null&&A.includes("Stream idle timeout")){console.warn("[ChatSessionProvider] Idle timeout - not scheduling resume (watchdog is generous)");return}lt(`closed:${I.reason}`)}},[se,lt,Dt,a]),it=b.useCallback(I=>{console.warn("[ChatSessionProvider] Stream connection error:",I),lt("connection-error")},[lt]),Bt=b.useCallback(I=>{ao.current=Date.now(),Dt(A=>A==="reconnecting"?"connected":A)},[Dt]);Lr.current=Je,Fr.current=it,N.current=Bt,b.useEffect(()=>()=>{se()},[se]);const sn=b.useCallback(()=>{se(),fn.current.attempts=0,Dt("idle"),Fn()},[se,Dt,Fn]);b.useEffect(()=>{Me.current=hn},[hn]),b.useEffect(()=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const I=S.map(W=>`${W.threadId}:${W.updatedAt??""}:${W.messageCount??""}`).join("|");if(S.length===0){try{oa(w)}catch{}xt.current="";return}if(I===xt.current)return;const A=()=>{try{const W=S.slice(0,aa);ca(w,W),xt.current=I}catch{}finally{Le.current=null}};return Le.current=window.setTimeout(()=>{ru(A),Le.current=null},ds),()=>{Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)}},[S,Ce]),b.useEffect(()=>{var K;const I=c.getAuthToken();$n(I);const A=fe=>{const le=la(h,fe);St.current!==le&&(St.current=le,Ot.current=!1),C(le);const ht=ua(le);b.startTransition(()=>{k(hs(ht))}),fe&&!Ot.current&&(Ot.current=!0)};A(I);const W=(K=c.onTokenChange)==null?void 0:K.call(c,fe=>{fe!==I&&($n(fe),x(),nt.current.clear(),yt.current.clear(),A(fe))});return()=>{W==null||W()}},[c,h,$n,x]);const Xn=b.useCallback(async I=>{var K;const A=`Thread ${(K=crypto.randomUUID)==null?void 0:K.call(crypto)}`,W={threadId:A,title:I||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};k(fe=>({byId:{...fe.byId,[A]:W},order:[A,...fe.order]})),j(A);try{const fe=await c.createThread(I),le=typeof fe=="string"?fe:fe.threadId;return k(ht=>{const bt=ht.byId[A];if(!bt)return ht;const Be={...ht.byId};delete Be[A],Be[le]={...bt,threadId:le};const kt=ht.order.map(Ht=>Ht===A?le:Ht);return{byId:Be,order:kt}}),j(le),setTimeout(()=>ct(),10),O(null),le}catch(fe){throw k(le=>{if(!le.byId[A])return le;const ht={...le.byId};delete ht[A];const bt=le.order.filter(Be=>Be!==A);return{byId:ht,order:bt}}),j(null),O(String(fe)),fe}},[c,ct]),Ko=b.useCallback(async I=>{try{await c.deleteThread(I);let A=null;k(W=>{if(!W.byId[I])return W;const K={...W.byId};delete K[I];const fe=W.order.filter(ht=>ht!==I),le={byId:K,order:fe};return A=da(le),le}),A&&Ce(A,{immediate:!0}),Re(I),Se.current===I&&(Xe.current=I,j(null),Se.current=null,tt.current=null,At()),await ct(),O(null)}catch(A){throw O(String(A)),A}},[c,At,Re,ct,Ce]),_i=b.useCallback(async(I,A)=>{try{await c.updateThread(I,A),k(W=>{const K=W.byId[I];return K?{byId:{...W.byId,[I]:{...K,title:A}},order:W.order}:W}),O(null)}catch(W){throw await ct(),O(String(W)),W}},[c,ct]),Nn=b.useCallback(async(I,A,W,K=!1)=>{await ve(async()=>{if(Xe.current===I&&!K){Xe.current=null;return}if(et.current===I&&!K)return;j(Wt=>Wt===I?Wt:I),Se.current=I;const ht=su(I,A??null,W??null),bt=yt.current.get(ht),Be=!K&&!A&&!W&&bt&&Date.now()-bt.timestamp<Qy,kt=!K&&!A&&!W;let Ht=!1;if(kt){const Wt=Ke.current.get(I);if(Wt)He(Wt),Ht=!0;else{const jt=m(I);jt&&(Ke.current.set(I,jt),He(jt),Ht=!0)}}const pn=K||!Ht||!!A||!!W,Jn=async Wt=>{Wt&&z(!0),et.current=I;try{const jt=await Te({threadId:I,checkpointId:A,checkpointNs:W},{force:K}),{latest:or,checkpoints:$r,snapshots:lo}=as(jt.payload);qe(or,"replace",I),Gt(I,$r,"replace"),Yt(I,lo,"replace"),R(null),jt.usedHistoryApi||ae(I).then(An=>{Xt(I,An)}).catch(An=>{console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries:",An)})}catch(jt){if(Y(jt))try{const or=await ae(I),$r=Xt(I,or);if(Q(!1),ue(null),ce(void 0),te(void 0),q(void 0),$r){R("History request timed out. Select a checkpoint to load manually.");return}}catch(or){console.warn("[ChatSessionProvider] Failed to fetch checkpoint summaries after timeout:",or)}throw(!Ht||K||Wt)&&(i==null||i(String(jt))),R(String(jt)),jt}finally{et.current=null,Wt&&z(!1)}};pn?await Jn(!0):kt&&Ht&&!Be&&Jn(!1).catch(Wt=>{console.warn("[ChatSessionProvider] Background refresh failed:",Wt)})},`loadThread-${I}`)},[He,Xt,qe,ve,ae,Te,Y,i,Gt,Yt]),ji=b.useCallback(async()=>{await ve(async()=>{const I=Se.current;I&&Re(I),Xe.current=null,j(null),Se.current=null,tt.current=null,At(),te(void 0),q(void 0),ce(void 0),ft();try{localStorage.removeItem("lastThreadId")}catch(A){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",A)}},"clearCurrentThread")},[At,Re,ve,ft]),Um=b.useCallback(async(I,A)=>{const W=Se.current;if(!W)throw new Error("No active thread");const K=Wr(I,A??null),fe=Mt(W,K);if(fe){await ve(async()=>{qe(fe,"replace",W,{persist:!1})},`navigateToCheckpoint-${W}-${K}`);return}await Nn(W,I,A??void 0,!0)},[qe,ve,Mt,Nn]),Wm=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");await Nn(Se.current,void 0,void 0,!0)},[Nn]),Vm=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");if(ye||!ne)return;const I=J;if(I){je(!0);try{const A=Se.current,W=await Te({threadId:A,checkpointId:I??ke??null,checkpointNs:ie??L??null}),{latest:K,checkpoints:fe,snapshots:le}=as(W.payload),ht=Ve(A);let bt=fe.length>0;if(bt&&ht&&ht.size>0&&(bt=fe.some(Be=>{if(!(Be!=null&&Be.checkpointId))return!1;const kt=Wr(Be.checkpointId,Be.checkpointNs??null);return!ht.has(kt)})),!bt){ue(null),ce(void 0),Q(!1),R(null);return}if(qe(K,"prepend",A??void 0),A&&(Gt(A,fe,"prepend"),Yt(A,le,"prepend"),!W.usedHistoryApi))try{const Be=await ae(A);Xt(A,Be)}catch(Be){console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries during prepend:",Be)}R(null)}catch(A){throw R(String(A)),A}finally{je(!1)}}},[qe,Te,Ve,ne,ke,L,ie,J,ae,Xt,ye,Gt,Yt]),Km=b.useCallback(I=>{if(I!=null&&I.threadId){if(I.checkpointId){const A=Wr(I.checkpointId,I.checkpointNs??null),W=un({...I,interrupt:I.interrupt??null},{cloneMessages:!0});Yt(I.threadId,{[A]:W},"prepend")}qe(I,"replace",I.threadId)}},[qe,Yt]),qo=b.useCallback(async(I,A)=>{var zr;const W=Se.current,K=(I==null?void 0:I.text)??"",fe=(I==null?void 0:I.attachments)??[],le=fe.length?fe:(A==null?void 0:A.attachments)??[],ht=I==null?void 0:I.messageAdditionalKwargs,bt={...(A==null?void 0:A.payloadExtras)??{},...(I==null?void 0:I.payload)??{}};if(!W&&!Object.keys(bt).length&&le.length===0&&!K.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!W&&!bt.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:Be,filesInfo:kt}=await Iy(c,le),Ht=[...Be];K&&K.trim()&&Ht.push({type:"text",text:K.trim()});const pn=!!W,Jn=pn?(A==null?void 0:A.checkpointId)??U.lastCheckpointId??void 0:void 0,Wt=pn?(A==null?void 0:A.checkpointNs)??U.lastCheckpointNs??void 0:void 0,jt={id:((zr=crypto.randomUUID)==null?void 0:zr.call(crypto))||`user-${Date.now()}`,role:"user",content:Ht,createdAt:new Date().toISOString(),...Jn!=null?{checkpointId:Jn}:{},...Wt!=null?{checkpointNs:Wt}:{}};ht&&Object.keys(ht).length&&(jt.additionalKwargs={...jt.additionalKwargs??{},...ht}),Ht.length>0&&Pe(jt);const or={...jt,content:Ht},$r=le.length>0,lo={messages:Ht.length>0?[or]:[],files_info:kt,...o&&$r&&s?{active_agent:s}:{},...bt},An={threadId:W??null,payload:lo,checkpointId:Jn??null,checkpointNs:Wt??null,nodeFilter:(A==null?void 0:A.nodeFilter)??null,config:A==null?void 0:A.config,command:(A==null?void 0:A.command)??null};An.threadId||delete An.threadId,An.command||delete An.command,de(An,{onError:xr=>{console.warn("[ChatSessionProvider] Stream error:",xr)},onOpen:({threadId:xr})=>{!Se.current&&xr&&(U.messages.length<=1&&(Xe.current=xr),j(xr))},onGap:gt})},[c,o,s,gt,U.lastCheckpointId,U.lastCheckpointNs,U.messages.length,Pe,de]),qm=b.useCallback(async(I,A,W)=>{if(!Se.current)throw new Error("No active thread to handle interrupt");const fe=A?W??!0:!1;try{try{We({type:"interrupt_response",payload:{interruptId:I}})}catch(le){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",le)}await qo({payload:{}},{checkpointId:U.lastCheckpointId??void 0,checkpointNs:U.lastCheckpointNs??void 0,command:{kind:"resume",value:fe}}),$(null)}catch(le){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${I}:`,le),le}},[We,U.lastCheckpointId,U.lastCheckpointNs,qo]);b.useEffect(()=>{if(l==null||l(E),E)try{localStorage.setItem("lastThreadId",E)}catch(I){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",I)}},[E,l]),b.useEffect(()=>((async()=>{try{if(ct().catch(A=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",A),i==null||i(String(A))}),!r&&!t)try{const A=localStorage.getItem("lastThreadId");A&&(j(A),n&&await Nn(A))}catch(A){console.warn("[ChatSessionProvider] Failed to restore last thread:",A)}else t&&n&&await Nn(t)}catch(A){console.error("[ChatSessionProvider] Initialization failed:",A),i==null||i(String(A))}})(),()=>{}),[]),b.useEffect(()=>{const I=Se.current;if(!I||tt.current!==I)return;U.messages.length&&U.messages[U.messages.length-1];const A=un({checkpointId:U.lastCheckpointId??null,checkpointNs:U.lastCheckpointNs??null,messages:U.messages.slice(),nextCursor:J??null,nextCursorNs:ie??null,interrupt:U.pendingInterrupt??V??null}),W=Ke.current.get(I),K=W==null?void 0:W.snapshot,fe=!K||K.messages.length!==A.messages.length||K.messages.some((Be,kt)=>{var Ht;return(Be==null?void 0:Be.id)!==((Ht=A.messages[kt])==null?void 0:Ht.id)}),le=((K==null?void 0:K.checkpointId)??null)!==A.checkpointId||((K==null?void 0:K.checkpointNs)??null)!==A.checkpointNs,ht=((K==null?void 0:K.nextCursor)??null)!==A.nextCursor||((K==null?void 0:K.nextCursorNs)??null)!==A.nextCursorNs,bt=!ou((K==null?void 0:K.interrupt)??null,A.interrupt??null);if(fe||le||ht||bt){const Be={threadId:I,snapshot:A};Ke.current.set(I,Be),Ut.current&&window.clearTimeout(Ut.current),Ut.current=window.setTimeout(()=>{try{g(Be,100)}catch(kt){console.warn("[ChatSessionProvider] Failed to persist thread payload:",kt)}},ds)}},[J,ie,U.lastCheckpointId,U.lastCheckpointNs,U.messages,U.pendingInterrupt,V,g]);const hT=b.useMemo(()=>({threads:S,currentThreadId:E,setCurrentThreadId:j,isLoading:_,error:B,actions:{createThread:Xn,deleteThread:Ko,renameThread:_i,refreshThreads:()=>ct()},persistThreadsCache:Ge,hydrateFromCache:F}),[S,E,_,B,Xn,Ko,_i,ct,Ge,F,j]),pT=b.useMemo(()=>{const I=U.lastBranch??null,A=U.assemblingId??null,W=I||A?{branchLabel:(I==null?void 0:I.branchLabel)??null,lastBranch:I,assemblingMessageId:A}:null;return{threadId:E,messages:U.messages,interrupt:V,checkpoint:{id:U.lastCheckpointId??null,namespace:U.lastCheckpointNs??null},checkpoints:Nt,metadata:W,isLoading:D,isHistoryLoading:ye,error:H,hasMore:ne,loadOlder:Vm,seedFromSnapshot:Km,clearState:At,navigateToCheckpoint:Um,returnToLatest:Wm,loadThread:Nn,clearThread:ji,respondToInterrupt:qm}},[ji,At,E,V,ne,ye,D,Vm,Nn,U.assemblingId,U.lastBranch,U.lastCheckpointId,U.lastCheckpointNs,U.messages,Um,qm,Wm,Km,H,Nt]),mT=b.useMemo(()=>({isStreaming:hn,error:zt,connectionState:Ln,submit:qo,send:qo,stop:sn,setAuthToken:$n}),[Ln,hn,zt,sn,qo,$n]);return u.jsx(wx.Provider,{value:!0,children:u.jsx(uu.Provider,{value:mT,children:u.jsx(lu.Provider,{value:hT,children:u.jsx(cu.Provider,{value:pT,children:e})})})})}function ps(){const e=b.useContext(lu);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function ms(){const e=b.useContext(cu);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function du(){const e=b.useContext(uu);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function gs({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(Ty,{apiConfig:t,children:u.jsx(bx,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onAuthError:l,onThreadChange:c,children:e})})}function oe(...e){return Jm.twMerge(Xm.clsx(e))}const Sx=Go.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"}}),ut=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?vr.Slot:"button";return u.jsx(i,{className:oe(Sx({variant:t,size:n,className:e})),ref:s,...o})});ut.displayName="Button";const fu=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:oe("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",e),ref:n,...t}));fu.displayName="Textarea";function hu({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const m=i!==void 0,[g,y]=b.useState(e),x=(m?i:g)??"",[w,C]=b.useTransition(),T=b.useRef(null),k=b.useRef(0),S=b.useRef(null);b.useEffect(()=>{m||(y(e??""),S.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,m]);const E=b.useCallback(()=>{const H=T.current;H&&(H.style.height="auto",H.style.height=`${H.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,x]);const j=b.useCallback((H,{fromUser:R})=>{m||y(H),R&&(a==null||a(H))},[m,a]),_=b.useCallback(async H=>{H&&H.preventDefault();const R=(x??"").trim();if(!R&&!p)return;const V=++k.current;S.current={id:V,shouldClear:!0},C(()=>{var $,F,ne;try{const Q=l(R);Q&&typeof Q.then=="function"?Q.then(()=>{var ye,je;((ye=S.current)==null?void 0:ye.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((je=S.current)==null?void 0:je.id)===V&&(S.current=null)}).catch(()=>{var ye;((ye=S.current)==null?void 0:ye.id)===V&&(S.current=null)}):((($=S.current)==null?void 0:$.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((F=S.current)==null?void 0:F.id)===V&&(S.current=null))}catch{((ne=S.current)==null?void 0:ne.id)===V&&(S.current=null)}})},[x,l,p,m,a]),P=b.useCallback(H=>{const R=H.target.value;j(R,{fromUser:!0}),S.current&&(S.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[j]),D=b.useCallback(H=>{H.key==="Enter"&&!H.shiftKey?(H.preventDefault(),_()):H.key==="Escape"&&t&&(H.preventDefault(),c==null||c())},[_,t,c]),O=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return u.jsx("form",{onSubmit:H=>void _(H),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(fu,{ref:T,value:x,onChange:P,onKeyDown:D,placeholder:t?"Edit your message...":n,className:O,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(ut,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(he.Square,{size:16})}):u.jsx(ut,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!p||w,children:u.jsx(he.Send,{size:16})})})]})})}const Cx=b.memo(hu),ys=0,ir=1,Vr=2,pu=4;function mu(e){return()=>e}function kx(e){e()}function gu(e,t){return n=>e(t(n))}function yu(e,t){return()=>e(t)}function Tx(e,t){return n=>e(t,n)}function fa(e){return e!==void 0}function Ex(...e){return()=>{e.map(kx)}}function Kr(){}function xs(e,t){return t(e),e}function Ix(e,t){return t(e)}function Tt(...e){return e}function dt(e,t){return e(ir,t)}function ze(e,t){e(ys,t)}function ha(e){e(Vr)}function Rt(e){return e(pu)}function we(e,t){return dt(e,Tx(t,ys))}function jn(e,t){const n=e(ir,r=>{n(),t(r)});return n}function xu(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function vu(e,t){return e===t}function Et(e=vu){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function _e(e){return t=>n=>{e(n)&&t(n)}}function pe(e){return t=>gu(t,e)}function Bn(e){return t=>()=>{t(e)}}function X(e,...t){const n=Nx(...t);return(r,o)=>{switch(r){case Vr:ha(e);return;case ir:return dt(e,n(o))}}}function Hn(e,t){return n=>r=>{n(t=e(t,r))}}function kr(e){return t=>n=>{e>0?e--:t(n)}}function Qn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Ue(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);dt(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function Nx(...e){return t=>e.reduceRight(Ix,t)}function Ax(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case ir:return s?n===s?void 0:(r(),n=s,t=dt(e,s),t):(r(),Kr);case Vr:r(),n=null;return}}}function ee(e){let t=e;const n=Ze();return(r,o)=>{switch(r){case ys:t=o;break;case ir:{o(t);break}case pu:return t}return n(r,o)}}function en(e,t){return xs(ee(t),n=>we(e,n))}function Ze(){const e=[];return(t,n)=>{switch(t){case ys:e.slice().forEach(r=>{r(n)});return;case Vr:e.splice(0,e.length);return;case ir:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function mn(e){return xs(Ze(),t=>we(e,t))}function at(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:_x(),singleton:n}}const _x=()=>Symbol();function jx(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(l=>n(l)));return i&&t.set(s,a),a};return n(e)}function Ft(...e){const t=Ze(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);dt(s,l=>{n[i]=l,r=r|a,r===o&&ze(t,n)})}),function(s,i){switch(s){case Vr:{ha(t);return}case ir:return r===o&&i(n),dt(t,i)}}}function Ne(e,t=vu){return X(e,Et(t))}function pa(...e){return function(t,n){switch(t){case Vr:return;case ir:return Ex(...e.map(r=>dt(r,n)))}}}var dn=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(dn||{});const Px={0:"debug",3:"error",1:"log",2:"warn"},Rx=()=>typeof globalThis>"u"?window:globalThis,ar=at(()=>{const e=ee(3);return{log:ee((t,n,r=1)=>{var o;const s=(o=Rx().VIRTUOSO_LOG_LEVEL)!=null?o:Rt(e);r>=s&&console[Px[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function Tr(e,t,n){return ma(e,t,n).callbackRef}function ma(e,t,n){const r=b.useRef(null);let o=i=>{};const s=b.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const l=i[0].target;l.offsetParent!==null&&e(l)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function Ox(e,t,n,r,o,s,i,a,l){const c=b.useCallback(d=>{const f=Mx(d.children,t,a?"offsetWidth":"offsetHeight",o);let h=d.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const p=h.lastElementChild.dataset.viewportType==="window";let m;p&&(m=h.ownerDocument.defaultView);const g=i?a?i.scrollLeft:i.scrollTop:p?a?m.scrollX||m.document.documentElement.scrollLeft:m.scrollY||m.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,y=i?a?i.scrollWidth:i.scrollHeight:p?a?m.document.documentElement.scrollWidth:m.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,x=i?a?i.offsetWidth:i.offsetHeight:p?a?m.innerWidth:m.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:y,scrollTop:Math.max(g,0),viewportHeight:x}),s==null||s(a?wu("column-gap",getComputedStyle(d).columnGap,o):wu("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return ma(c,n,l)}function Mx(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},dn.ERROR),d===c)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function wu(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,dn.WARN),t==="normal"?0:parseInt(t??"0",10)}function bu(e,t,n){const r=b.useRef(null),o=b.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,h;if(t){const p=t.getBoundingClientRect(),m=c.top-p.top;h=p.height-Math.max(0,m),f=m+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,c.top),f=c.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=ma(o,!0,n),a=b.useCallback(()=>{o(i.current)},[o,i]);return b.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const rn=at(()=>{const e=Ze(),t=Ze(),n=ee(0),r=Ze(),o=ee(0),s=Ze(),i=Ze(),a=ee(0),l=ee(0),c=ee(0),d=ee(0),f=Ze(),h=Ze(),p=ee(!1),m=ee(!1),g=ee(!1);return we(X(e,pe(({scrollTop:y})=>y)),t),we(X(e,pe(({scrollHeight:y})=>y)),i),we(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:m,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:g,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),xo={lvl:0};function Su(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:l}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=l}return s.push({end:1/0,start:r,value:o}),s}function vt(e){return e===xo}function vo(e,t){if(!vt(e))return t===e.k?e.v:t<e.k?vo(e.l,t):vo(e.r,t)}function Pn(e,t,n="k"){if(vt(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=Pn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return Pn(e.l,t,n)}function gn(e,t,n){return vt(e)?Tu(t,n,1):t===e.k?$t(e,{k:t,v:n}):t<e.k?Eu($t(e,{l:gn(e.l,t,n)})):Eu($t(e,{r:gn(e.r,t,n)}))}function qr(){return xo}function vs(e,t,n){if(vt(e))return[];const r=Pn(e,t)[0];return Dx(ya(e,r,n))}function ga(e,t){if(vt(e))return xo;const{k:n,l:r,r:o}=e;if(t===n){if(vt(r))return o;if(vt(o))return r;{const[s,i]=ku(r);return ws($t(e,{k:s,l:Cu(r),v:i}))}}else return t<n?ws($t(e,{l:ga(r,t)})):ws($t(e,{r:ga(o,t)}))}function Er(e){return vt(e)?[]:[...Er(e.l),{k:e.k,v:e.v},...Er(e.r)]}function ya(e,t,n){if(vt(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(ya(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(ya(s,t,n))),a}function ws(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(xa(t))return Iu($t(e,{lvl:n-1}));if(!vt(t)&&!vt(t.r))return $t(t.r,{l:$t(t,{r:t.r.l}),lvl:n,r:$t(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(xa(e))return va($t(e,{lvl:n-1}));if(!vt(r)&&!vt(r.l)){const o=r.l,s=xa(o)?r.lvl-1:r.lvl;return $t(o,{l:$t(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:va($t(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function $t(e,t){return Tu(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function Cu(e){return vt(e.r)?e.l:ws($t(e,{r:Cu(e.r)}))}function xa(e){return vt(e)||e.lvl>e.r.lvl}function ku(e){return vt(e.r)?[e.k,e.v]:ku(e.r)}function Tu(e,t,n,r=xo,o=xo){return{k:e,l:r,lvl:n,r:o,v:t}}function Eu(e){return va(Iu(e))}function Iu(e){const{l:t}=e;return!vt(t)&&t.lvl===e.lvl?$t(t,{r:$t(e,{l:t.r})}):e}function va(e){const{lvl:t,r:n}=e;return!vt(n)&&!vt(n.r)&&n.lvl===t&&n.r.lvl===t?$t(n,{l:$t(e,{r:n.l}),lvl:t+1}):e}function Dx(e){return Su(e,({k:t,v:n})=>({index:t,value:n}))}function Nu(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function wo(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const wa=at(()=>({recalcInProgress:ee(!1)}),[],{singleton:!0});function Au(e,t,n){return e[bs(e,t,n)]}function bs(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function Lx(e,t,n,r){const o=bs(e,t,r),s=bs(e,n,r,o);return e.slice(o,s+1)}function lr(e,t){return Math.round(e.getBoundingClientRect()[t])}function Ss(e){return!vt(e.groupOffsetTree)}function ba({index:e},t){return t===e?0:t<e?-1:1}function Fx(){return{groupIndices:[],groupOffsetTree:qr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:qr()}}function $x(e,t){let n=vt(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),vt(e)){e=gn(e,0,s);continue}const a=vs(e,i-1,o+1);if(a.some(Kx(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=ga(e,f)):(c=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=gn(e,o+1,h));c&&(e=gn(e,i,s))}return[e,n]}function zx(e){return typeof e.groupIndex<"u"}function Bx({offset:e},t){return t===e?0:t<e?-1:1}function bo(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Au(t,e,ba),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function _u(e,t){if(!Ss(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function ju(e,t,n){if(zx(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=_u(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function Hx(e,t,n,r=0){return r>0&&(t=Math.max(t,Au(e,r,ba).offset)),Su(Lx(e,t,n,Bx),Vx)}function Ux(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,dn.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&vt(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((m,g)=>gn(gn(m,g,h),g+1,p),i)}else[i,a]=$x(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=Sa(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>gn(h,p,bo(p,f,o)),qr()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function Wx(e){return Er(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function Pu(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function Sa(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=bs(o,t-1,ba),a=o[l].offset;const c=Pn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===Pn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of vs(n,t,1/0)){const f=c-s,h=f*i+a+f*r;o.push({index:c,offset:h,size:d}),s=c,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function Vx(e){return{index:e.index,value:e}}function Kx(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const qx={offsetHeight:"height",offsetWidth:"width"},Un=at(([{log:e},{recalcInProgress:t}])=>{const n=Ze(),r=Ze(),o=en(r,0),s=Ze(),i=Ze(),a=ee(0),l=ee([]),c=ee(void 0),d=ee(void 0),f=ee((k,S)=>lr(k,qx[S])),h=ee(void 0),p=ee(0),m=Fx(),g=en(X(n,Ue(l,e,p),Hn(Ux,m),Et()),m),y=en(X(l,Et(),Hn((k,S)=>({current:S,prev:k.current}),{current:[],prev:[]}),pe(({prev:k})=>k)),[]);we(X(l,_e(k=>k.length>0),Ue(g,p),pe(([k,S,E])=>{const j=k.reduce((_,P,D)=>gn(_,P,bo(P,S.offsetTree,E)||D),qr());return{...S,groupIndices:k,groupOffsetTree:j}})),g),we(X(r,Ue(g),_e(([k,{lastIndex:S}])=>k<S),pe(([k,{lastIndex:S,lastSize:E}])=>[{endIndex:S,size:E,startIndex:k}])),n),we(c,d);const x=en(X(c,pe(k=>k===void 0)),!0);we(X(d,_e(k=>k!==void 0&&vt(Rt(g).sizeTree)),pe(k=>[{endIndex:0,size:k,startIndex:0}])),n);const w=mn(X(n,Ue(g),Hn(({sizes:k},[S,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:m}),pe(k=>k.changed)));dt(X(a,Hn((k,S)=>({diff:k.prev-S,prev:S}),{diff:0,prev:0}),pe(k=>k.diff)),k=>{const{groupIndices:S}=Rt(g);if(k>0)ze(t,!0),ze(s,k+Pu(k,S));else if(k<0){const E=Rt(y);E.length>0&&(k-=Pu(-k,E)),ze(i,k)}}),dt(X(a,Ue(e)),([k,S])=>{k<0&&S("`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:a},dn.ERROR)});const C=mn(s);we(X(s,Ue(g),pe(([k,S])=>{const E=S.groupIndices.length>0,j=[],_=S.lastSize;if(E){const P=vo(S.sizeTree,0);let D=0,z=0;for(;D<k;){const O=S.groupIndices[z],H=S.groupIndices.length===z+1?1/0:S.groupIndices[z+1]-O-1;j.push({endIndex:O,size:P,startIndex:O}),j.push({endIndex:O+1+H-1,size:_,startIndex:O+1}),z++,D+=H+1}const B=Er(S.sizeTree);return D!==k&&B.shift(),B.reduce((O,{k:H,v:R})=>{let V=O.ranges;return O.prevSize!==0&&(V=[...O.ranges,{endIndex:H+k-1,size:O.prevSize,startIndex:O.prevIndex}]),{prevIndex:H+k,prevSize:R,ranges:V}},{prevIndex:k,prevSize:0,ranges:j}).ranges}return Er(S.sizeTree).reduce((P,{k:D,v:z})=>({prevIndex:D+k,prevSize:z,ranges:[...P.ranges,{endIndex:D+k-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const T=mn(X(i,Ue(g,p),pe(([k,{offsetTree:S},E])=>{const j=-k;return bo(j,S,E)})));return we(X(i,Ue(g,p),pe(([k,S,E])=>{if(S.groupIndices.length>0){if(vt(S.sizeTree))return S;let j=qr();const _=Rt(y);let P=0,D=0,z=0;for(;P<-k;){z=_[D];const B=_[D+1]-z-1;D++,P+=B+1}if(j=Er(S.sizeTree).reduce((B,{k:O,v:H})=>gn(B,Math.max(0,O+k),H),j),P!==-k){const B=vo(S.sizeTree,z);j=gn(j,0,B);const O=Pn(S.sizeTree,-k+1)[1];j=gn(j,1,O)}return{...S,sizeTree:j,...Sa(S.offsetTree,0,j,E)}}else{const j=Er(S.sizeTree).reduce((_,{k:P,v:D})=>gn(_,Math.max(0,P+k),D),qr());return{...S,sizeTree:j,...Sa(S.offsetTree,0,j,E)}}})),g),{beforeUnshiftWith:C,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:p,groupIndices:l,itemSize:f,listRefresh:w,shiftWith:i,shiftWithOffset:T,sizeRanges:n,sizes:g,statefulTotalCount:o,totalCount:r,trackItemSizes:x,unshiftWith:s}},Tt(ar,wa),{singleton:!0});function Gx(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Ru=at(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Ze(),i=Ze(),a=mn(X(s,pe(Gx)));return we(X(a,pe(l=>l.totalCount)),n),we(X(a,pe(l=>l.groupIndices)),e),we(X(Ft(o,t,r),_e(([l,c])=>Ss(c)),pe(([l,c,d])=>Pn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),Et(),pe(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},Tt(Un,rn)),cr=at(([{log:e}])=>{const t=ee(!1),n=mn(X(t,_e(r=>r),Et()));return dt(t,r=>{r&&Rt(e)("props updated",{},dn.DEBUG)}),{didMount:n,propsReady:t}},Tt(ar),{singleton:!0}),Yx=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Ou(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Yx)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const So=at(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=Ze(),m=Ze(),g=ee(0);let y=null,x=null,w=null;function C(){y&&(y(),y=null),w&&(w(),w=null),x&&(clearTimeout(x),x=null),ze(l,!1)}return we(X(p,Ue(n,f,r,g,a,i,h),Ue(e,s,o),pe(([[T,k,S,E,j,_,P,D],z,B,O])=>{const H=Ou(T),{align:R,behavior:V,offset:$}=H,F=E-1,ne=ju(H,k,F);let Q=bo(ne,k.offsetTree,z)+_;R==="end"?(Q+=B+Pn(k.sizeTree,ne)[1]-S+O,ne===F&&(Q+=P)):R==="center"?Q+=(B+Pn(k.sizeTree,ne)[1]-S+O)/2:Q-=j,$&&(Q+=$);const ye=je=>{C(),je?(D("retrying to scroll to",{location:T},dn.DEBUG),ze(p,T)):(ze(m,!0),D("list did not change, scroll successful",{},dn.DEBUG))};if(C(),V==="smooth"){let je=!1;w=dt(t,J=>{je=je||J}),y=jn(d,()=>{ye(je)})}else y=jn(X(t,Xx(150)),ye);return x=setTimeout(()=>{C()},1200),ze(l,!0),D("scrolling from index to",{behavior:V,index:ne,top:Q},dn.DEBUG),{behavior:V,top:Q}})),c),{scrollTargetReached:m,scrollToIndex:p,topListHeight:g}},Tt(Un,rn,ar),{singleton:!0});function Xx(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function Ca(e,t){e==0?t():requestAnimationFrame(()=>{Ca(e-1,t)})}function ka(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const Co=at(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=ee(!0),l=ee(0),c=ee(!0);return we(X(i,Ue(l),_e(([d,f])=>!!f),Bn(!1)),a),we(X(i,Ue(l),_e(([d,f])=>!!f),Bn(!1)),c),dt(X(Ft(t,i),Ue(a,n,e,c),_e(([[,d],f,{sizeTree:h},p,m])=>d&&(!vt(h)||fa(p))&&!f&&!m),Ue(l)),([,d])=>{jn(o,()=>{ze(c,!0)}),Ca(4,()=>{jn(r,()=>{ze(a,!0)}),ze(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},Tt(Un,rn,So,cr),{singleton:!0});function Mu(e,t){return Math.abs(e-t)<1.01}const ko="up",To="down",Jx="none",Zx={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Qx=0,Eo=at(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=ee(!1),a=ee(!0),l=Ze(),c=Ze(),d=ee(4),f=ee(Qx),h=en(X(pa(X(Ne(o),kr(1),Bn(!0)),X(Ne(o),kr(1),Bn(!1),xu(100))),Et()),!1),p=en(X(pa(X(n,Bn(!0)),X(n,Bn(!1),xu(200))),Et()),!1);we(X(Ft(Ne(o),Ne(f)),pe(([w,C])=>w<=C),Et()),a),we(X(a,Qn(50)),c);const m=mn(X(Ft(r,Ne(s),Ne(t),Ne(e),Ne(d)),Hn((w,[{scrollHeight:C,scrollTop:T},k,S,E,j])=>{const _=T+k-C>-j,P={scrollHeight:C,scrollTop:T,viewportHeight:k};if(_){let z,B;return T>w.state.scrollTop?(z="SCROLLED_DOWN",B=w.state.scrollTop-T):(z="SIZE_DECREASED",B=w.state.scrollTop-T||w.scrollTopDelta),{atBottom:!0,atBottomBecause:z,scrollTopDelta:B,state:P}}let D;return P.scrollHeight>w.state.scrollHeight?D="SIZE_INCREASED":k<w.state.viewportHeight?D="VIEWPORT_HEIGHT_DECREASING":T<w.state.scrollTop?D="SCROLLING_UPWARDS":D="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:D,state:P}},Zx),Et((w,C)=>w&&w.atBottom===C.atBottom))),g=en(X(r,Hn((w,{scrollHeight:C,scrollTop:T,viewportHeight:k})=>{if(Mu(w.scrollHeight,C))return{changed:!1,jump:0,scrollHeight:C,scrollTop:T};{const S=C-(T+k)<1;return w.scrollTop!==T&&S?{changed:!0,jump:w.scrollTop-T,scrollHeight:C,scrollTop:T}:{changed:!0,jump:0,scrollHeight:C,scrollTop:T}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),_e(w=>w.changed),pe(w=>w.jump)),0);we(X(m,pe(w=>w.atBottom)),i),we(X(i,Qn(50)),l);const y=ee(To);we(X(r,pe(({scrollTop:w})=>w),Et(),Hn((w,C)=>Rt(p)?{direction:w.direction,prevScrollTop:C}:{direction:C<w.prevScrollTop?ko:To,prevScrollTop:C},{direction:To,prevScrollTop:0}),pe(w=>w.direction)),y),we(X(r,Qn(50),Bn(Jx)),y);const x=ee(0);return we(X(h,_e(w=>!w),Bn(0)),x),we(X(o,Qn(100),Ue(h),_e(([w,C])=>!!C),Hn(([w,C],[T])=>[C,T],[0,0]),pe(([w,C])=>C-w)),x),{atBottomState:m,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:g,scrollDirection:y,scrollVelocity:x}},Tt(rn)),Cs="top",ks="bottom",Du="none";function Lu(e,t,n){return typeof e=="number"?n===ko&&t===Cs||n===To&&t===ks?e:0:n===ko?t===Cs?e.main:e.reverse:t===ks?e.main:e.reverse}function Fu(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const Ta=at(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Ze(),i=ee(0),a=ee(0),l=ee(0),c=en(X(Ft(Ne(r),Ne(o),Ne(n),Ne(s,wo),Ne(l),Ne(i),Ne(t),Ne(e),Ne(a)),pe(([d,f,h,[p,m],g,y,x,w,C])=>{const T=d-w,k=y+x,S=Math.max(h-T,0);let E=Du;const j=Fu(C,Cs),_=Fu(C,ks);return p-=w,p+=h+x,m+=h+x,m-=w,p>d+k-j&&(E=ko),m<d-S+f+_&&(E=To),E!==Du?[Math.max(T-h-Lu(g,Cs,E)-j,0),T-S-x+f+Lu(g,ks,E)+_]:null}),_e(d=>d!=null),Et(wo)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},Tt(rn),{singleton:!0});function ev(e,t,n){if(Ss(t)){const r=_u(e,t);return[{index:Pn(t.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:e,offset:0,size:0}]}const Ea={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Ts(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const g=e[e.length-1];d=g.offset+g.size}const f=n-i,h=a+f*l+(f-1)*r,p=c,m=h-d;return{bottom:d,firstItemIndex:s,items:zu(e,o,s),offsetBottom:m,offsetTop:c,top:p,topItems:zu(t,o,s),topListHeight:t.reduce((g,y)=>y.size+g,0),totalCount:n}}function $u(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-i>=e)break;i++}const a=e+i,l=ka(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return Ts(c,[],a,o,n,r)}function zu(e,t,n){if(e.length===0)return[];if(!Ss(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=vs(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const Ir=at(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:m}])=>{const g=ee([]),y=ee(0),x=Ze();we(s.topItemsIndexes,g);const w=en(X(Ft(p,m,Ne(l,wo),Ne(o),Ne(r),Ne(c),d,Ne(g),Ne(t),Ne(n),e),_e(([S,E,,j,,,,,,,_])=>{const P=_&&_.length!==j;return S&&!E&&!P}),pe(([,,[S,E],j,_,P,D,z,B,O,H])=>{const R=_,{offsetTree:V,sizeTree:$}=R,F=Rt(y);if(j===0)return{...Ea,totalCount:j};if(S===0&&E===0)return F===0?{...Ea,totalCount:j}:$u(F,P,_,B,O,H||[]);if(vt($))return F>0?null:Ts(ev(ka(P,j),R,H),[],j,O,R,B);const ne=[];if(z.length>0){const ue=z[0],ke=z[z.length-1];let te=0;for(const L of vs($,ue,ke)){const q=L.value,ie=Math.max(L.start,ue),ce=Math.min(L.end,ke);for(let U=ie;U<=ce;U++)ne.push({data:H==null?void 0:H[U],index:U,offset:te,size:q}),te+=q}}if(!D)return Ts([],ne,j,O,R,B);const Q=z.length>0?z[z.length-1]+1:0,ye=Hx(V,S,E,Q);if(ye.length===0)return null;const je=j-1,J=xs([],ue=>{for(const ke of ye){const te=ke.value;let L=te.offset,q=ke.start;const ie=te.size;if(te.offset<S){q+=Math.floor((S-te.offset+O)/(ie+O));const U=q-ke.start;L+=U*ie+U*O}q<Q&&(L+=(Q-q)*ie,q=Q);const ce=Math.min(ke.end,je);for(let U=q;U<=ce&&!(L>=E);U++)ue.push({data:H==null?void 0:H[U],index:U,offset:L,size:ie}),L+=ie+O}});return Ts(J,ne,j,O,R,B)}),_e(S=>S!==null),Et()),Ea);we(X(e,_e(fa),pe(S=>S==null?void 0:S.length)),o),we(X(w,pe(S=>S.topListHeight)),f),we(f,a),we(X(w,pe(S=>[S.top,S.bottom])),i),we(X(w,pe(S=>S.items)),x);const C=mn(X(w,_e(({items:S})=>S.length>0),Ue(o,e),_e(([{items:S},E])=>S[S.length-1].originalIndex===E-1),pe(([,S,E])=>[S-1,E]),Et(wo),pe(([S])=>S))),T=mn(X(w,Qn(200),_e(({items:S,topItems:E})=>S.length>0&&S[0].originalIndex===E.length),pe(({items:S})=>S[0].index),Et())),k=mn(X(w,_e(({items:S})=>S.length>0),pe(({items:S})=>{let E=0,j=S.length-1;for(;S[E].type==="group"&&E<j;)E++;for(;S[j].type==="group"&&j>E;)j--;return{endIndex:S[j].index,startIndex:S[E].index}}),Et(Nu)));return{endReached:C,initialItemCount:y,itemsRendered:x,listState:w,rangeChanged:k,startReached:T,topItemsIndexes:g,...h}},Tt(Un,Ru,Ta,Co,So,Eo,cr,wa),{singleton:!0}),Bu=at(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Ze(),i=en(X(Ft(n,e,r,t,o),pe(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return we(Ne(i),s),{totalListHeight:i,totalListHeightChanged:s}},Tt(rn,Ir),{singleton:!0}),tv=at(([{viewportHeight:e},{totalListHeight:t}])=>{const n=ee(!1),r=en(X(Ft(n,e,t),_e(([o])=>o),pe(([,o,s])=>Math.max(0,o-s)),Qn(0),Et()),0);return{alignToBottom:n,paddingTopAddition:r}},Tt(rn,Bu),{singleton:!0}),Hu=at(()=>({context:ee(null)})),nv=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,Uu=at(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Ze();return we(X(d,Ue(t,l,n,s,o,r,a),Ue(e),pe(([[f,h,p,m,g,y,x,w],C])=>{const{align:T,behavior:k,calculateViewLocation:S=nv,done:E,...j}=f,_=ju(f,h,m-1),P=bo(_,h.offsetTree,C)+g+y,D=P+Pn(h.sizeTree,_)[1],z=w+y,B=w+p-x,O=S({itemBottom:D,itemTop:P,locationParams:{align:T,behavior:k,...j},viewportBottom:B,viewportTop:z});return O?E&&jn(X(i,_e(H=>!H),kr(Rt(i)?1:2)),E):E&&E(),O}),_e(f=>f!==null)),c),{scrollIntoView:d}},Tt(Un,rn,So,Ir,ar),{singleton:!0});function Wu(e){return e?e==="smooth"?"smooth":"auto":!1}const rv=(e,t)=>typeof e=="function"?Wu(e(t)):t&&Wu(e),ov=at(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const m=ee(!1),g=Ze();let y=null;function x(k){ze(i,{align:"end",behavior:k,index:"LAST"})}dt(X(Ft(X(Ne(t),kr(1)),l),Ue(Ne(m),s,a,f),pe(([[k,S],E,j,_,P])=>{let D=S&&_,z="auto";return D&&(z=rv(E,j||P),D=D&&!!z),{followOutputBehavior:z,shouldFollow:D,totalCount:k}}),_e(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:S})=>{y&&(y(),y=null),Rt(n)?requestAnimationFrame(()=>{Rt(d)("following output to ",{totalCount:S},dn.DEBUG),x(k)}):y=jn(e,()=>{Rt(d)("following output to ",{totalCount:S},dn.DEBUG),x(k),y=null})});function w(k){const S=jn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!y&&(Rt(d)("scrolling to bottom due to increased size",{},dn.DEBUG),x("auto"))});setTimeout(S,100)}dt(X(Ft(Ne(m),t,c),_e(([k,,S])=>k&&S),Hn(({value:k},[,S])=>({refreshed:k===S,value:S}),{refreshed:!1,value:0}),_e(({refreshed:k})=>k),Ue(m,t)),([,k])=>{Rt(a)&&w(k!==!1)}),dt(g,()=>{w(Rt(m)!==!1)}),dt(Ft(Ne(m),o),([k,S])=>{k&&!S.atBottom&&S.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&x("auto")});const C=ee(null),T=Ze();return we(pa(X(Ne(r),pe(k=>{var S;return(S=k==null?void 0:k.length)!=null?S:0})),X(Ne(t))),T),dt(X(Ft(X(T,kr(1)),l),Ue(Ne(C),a,f,h),pe(([[k,S],E,j,_,P])=>S&&j&&(E==null?void 0:E({context:P,totalCount:k,scrollingInProgress:_}))),_e(k=>!!k),Qn(0)),k=>{y&&(y(),y=null),Rt(n)?requestAnimationFrame(()=>{Rt(d)("scrolling into view",{}),ze(p,k)}):y=jn(e,()=>{Rt(d)("scrolling into view",{}),ze(p,k),y=null})}),{autoscrollToBottom:g,followOutput:m,scrollIntoViewOnChange:C}},Tt(Un,Eo,So,Co,cr,ar,rn,Hu,Uu)),sv=at(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(we(X(a,Ue(s),_e(([,l])=>l!==0),Ue(o,r,t,n,e),pe(([[,l],c,d,f,h,p=[]])=>$u(l,c,d,f,h,p))),i),{}),Tt(Un,Co,Ir,cr),{singleton:!0}),iv=at(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=ee(0);return dt(X(e,Ue(r),_e(([,o])=>o!==0),pe(([,o])=>({top:o}))),o=>{jn(X(n,kr(1),_e(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{ze(t,o)})})}),{initialScrollTop:r}},Tt(cr,rn,Ir),{singleton:!0}),Vu=at(([{scrollVelocity:e}])=>{const t=ee(!1),n=Ze(),r=ee(!1);return we(X(e,Ue(r,t,n),_e(([o,s])=>!!s),pe(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),Et()),t),dt(X(Ft(t,e,n),Ue(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},Tt(Eo),{singleton:!0}),Ia=at(([{scrollContainerState:e,scrollTo:t}])=>{const n=Ze(),r=Ze(),o=Ze(),s=ee(!1),i=ee(void 0);return we(X(Ft(n,r),pe(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),we(X(t,Ue(r),pe(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},Tt(rn)),av=at(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Ze(),d=ee(void 0),f=ee(null),h=ee(null);return we(a,f),we(l,h),dt(X(c,Ue(t,r,i,f,h,n)),([p,m,g,y,x,w,C])=>{const T=Wx(m.sizeTree);y&&x!==null&&w!==null&&(g=x.scrollTop-w.offsetTop),g-=C,p({ranges:T,scrollTop:g})}),we(X(d,_e(fa),pe(lv)),o),we(X(s,Ue(d),_e(([,p])=>p!==void 0),Et(),pe(([,p])=>p.ranges)),e),{getState:c,restoreStateFrom:d}},Tt(Un,rn,Co,cr,Ia));function lv(e){return{align:"start",index:0,offset:e.scrollTop}}const cv=at(([{topItemsIndexes:e}])=>{const t=ee(0);return we(X(t,_e(n=>n>=0),pe(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},Tt(Ir));function Ku(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const uv=Ku(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),dv=at(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:m}])=>{const g=mn(X(l,Ue(i),Hn(([,x,w,C],[{bottom:T,items:k,offsetBottom:S,totalCount:E},j])=>{const _=T+S;let P=0;return w===E&&x.length>0&&k.length>0&&(k[0].originalIndex===0&&x[0].originalIndex===0||(P=_-C,P!==0&&(P+=j))),[P,k,E,_]},[0,[],0,0]),_e(([x])=>x!==0),Ue(r,a,n,o,p,m),_e(([,x,w,C,,,T])=>!T&&!C&&x!==0&&w===ko),pe(([[x],,,,,w])=>(w("Upward scrolling compensation",{amount:x},dn.DEBUG),x))));function y(x){x>0?(ze(t,{behavior:"auto",top:-x}),ze(e,0)):(ze(e,0),ze(t,{behavior:"auto",top:-x}))}return dt(X(g,Ue(e,s)),([x,w,C])=>{C&&uv()?ze(e,w-x):y(-x)}),dt(X(Ft(en(s,!1),e,m),_e(([x,w,C])=>!x&&!C&&w!==0),pe(([x,w])=>w),Qn(1)),y),we(X(f,pe(x=>({top:-x}))),t),dt(X(c,Ue(h,d),pe(([x,{groupIndices:w,lastSize:C,sizeTree:T},k])=>{function S(E){return E*(C+k)}if(w.length===0)return S(x);{let E=0;const j=vo(T,0);let _=0,P=0;for(;_<x;){_++,E+=j;let D=w.length===P+1?1/0:w[P+1]-w[P]-1;_+D>x&&(E-=j,D=x-_+1),_+=D,E+=S(D),P++}return E}})),x=>{ze(e,x),requestAnimationFrame(()=>{ze(t,{top:x}),requestAnimationFrame(()=>{ze(e,0),ze(m,!1)})})}),{deviation:e}},Tt(rn,Eo,Ir,Un,ar,wa)),fv=at(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),Tt(Ta,sv,cr,Vu,Bu,iv,tv,Ia,Uu,ar,Hu)),qu=at(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m},g,y,x,{listState:w,topItemsIndexes:C,...T},{scrollToIndex:k},S,{topItemCount:E},{groupCounts:j},_])=>(we(T.rangeChanged,_.scrollSeekRangeChanged),we(X(_.windowViewportRect,pe(P=>P.visibleHeight)),g.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:j,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m,sizeRanges:a,topItemCount:E,topItemsIndexes:C,totalCount:d,...x,groupIndices:s,itemSize:i,listState:w,scrollToIndex:k,statefulTotalCount:c,trackItemSizes:f,...T,..._,...g,sizes:l,...y}),Tt(Un,Co,rn,av,ov,Ir,So,dv,cv,Ru,fv));function hv(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const Es=typeof document<"u"?b.useLayoutEffect:b.useEffect;function Gu(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=b.createContext({});function l(y,x){y.propsReady&&ze(y.propsReady,!1);for(const w of r){const C=y[t.required[w]];ze(C,x[w])}for(const w of o)if(w in x){const C=y[t.optional[w]];ze(C,x[w])}y.propsReady&&ze(y.propsReady,!0)}function c(y){return s.reduce((x,w)=>(x[w]=C=>{const T=y[t.methods[w]];ze(T,C)},x),{})}function d(y){return i.reduce((x,w)=>(x[w]=Ax(y[t.events[w]]),x),{})}const f=b.forwardRef((y,x)=>{const{children:w,...C}=y,[T]=b.useState(()=>xs(jx(e),E=>{l(E,C)})),[k]=b.useState(yu(d,T));Es(()=>{for(const E of i)E in C&&dt(k[E],C[E]);return()=>{Object.values(k).map(ha)}},[C,k,T]),Es(()=>{l(T,C)}),b.useImperativeHandle(x,mu(c(T)));const S=n;return u.jsx(a.Provider,{value:T,children:n?u.jsx(S,{...hv([...r,...o,...i],C),children:w}):w})}),h=y=>{const x=b.useContext(a);return b.useCallback(w=>{ze(x[y],w)},[x,y])},p=y=>{const x=b.useContext(a)[y],w=b.useCallback(C=>dt(x,C),[x]);return b.useSyncExternalStore(w,()=>Rt(x),()=>Rt(x))},m=y=>{const x=b.useContext(a)[y],[w,C]=b.useState(yu(Rt,x));return Es(()=>dt(x,T=>{T!==w&&C(mu(T))}),[x,w]),w},g=b.version.startsWith("18")?p:m;return{Component:f,useEmitter:(y,x)=>{const w=b.useContext(a)[y];Es(()=>dt(w,x),[x,w])},useEmitterValue:g,usePublisher:h}}const Yu=b.createContext(void 0),Xu=b.createContext(void 0),Ju=typeof document<"u"?b.useLayoutEffect:b.useEffect;function Na(e){return"self"in e}function pv(e){return"body"in e}function Zu(e,t,n,r=Kr,o,s){const i=b.useRef(null),a=b.useRef(null),l=b.useRef(null),c=b.useCallback(h=>{let p,m,g;const y=h.target;if(pv(y)||Na(y)){const w=Na(y)?y:y.defaultView;g=s?w.scrollX:w.scrollY,p=s?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,m=s?w.innerWidth:w.innerHeight}else g=s?y.scrollLeft:y.scrollTop,p=s?y.scrollWidth:y.scrollHeight,m=s?y.offsetWidth:y.offsetHeight;const x=()=>{e({scrollHeight:p,scrollTop:Math.max(g,0),viewportHeight:m})};h.suppressFlushSync?x():Pi.flushSync(x),a.current!==null&&(g===a.current||g<=0||g===p-m)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);b.useEffect(()=>{const h=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",c,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const m=h.behavior==="smooth";let g,y,x;Na(p)?(y=Math.max(lr(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),g=s?p.innerWidth:p.innerHeight,x=s?window.scrollX:window.scrollY):(y=p[s?"scrollWidth":"scrollHeight"],g=lr(p,s?"width":"height"),x=p[s?"scrollLeft":"scrollTop"]);const w=y-g;if(h.top=Math.ceil(Math.max(Math.min(w,h.top),0)),Mu(g,y)||h.top===x){e({scrollHeight:y,scrollTop:x,viewportHeight:g}),m&&t(!0);return}m?(a.current=h.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),p.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const Aa="-webkit-sticky",Qu="sticky",_a=Ku(()=>{if(typeof document>"u")return Qu;const e=document.createElement("div");return e.style.position=Aa,e.style.position===Aa?Aa:Qu});function ja(e){return e}const mv=at(()=>{const e=ee(a=>`Item ${a}`),t=ee(a=>`Group ${a}`),n=ee({}),r=ee(ja),o=ee("div"),s=ee(Kr),i=(a,l=null)=>en(X(n,pe(c=>c[a]),Et()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),gv=at(([e,t])=>({...e,...t}),Tt(qu,mv)),yv=({height:e})=>u.jsx("div",{style:{height:e}}),xv={overflowAnchor:"none",position:_a(),zIndex:1},ed={overflowAnchor:"none"},vv={...ed,display:"inline-block",height:"100%"},td=b.memo(function({showTopList:e=!1}){const t=Oe("listState"),n=Sn("sizeRanges"),r=Oe("useWindowScroll"),o=Oe("customScrollParent"),s=Sn("windowScrollContainerState"),i=Sn("scrollContainerState"),a=o||r?s:i,l=Oe("itemContent"),c=Oe("context"),d=Oe("groupContent"),f=Oe("trackItemSizes"),h=Oe("itemSize"),p=Oe("log"),m=Sn("gap"),g=Oe("horizontalDirection"),{callbackRef:y}=Ox(n,h,f,e?Kr:a,p,m,o,g,Oe("skipAnimationFrameInResizeObserver")),[x,w]=b.useState(0);Pa("deviation",O=>{x!==O&&w(O)});const C=Oe("EmptyPlaceholder"),T=Oe("ScrollSeekPlaceholder")||yv,k=Oe("ListComponent"),S=Oe("ItemComponent"),E=Oe("GroupComponent"),j=Oe("computeItemKey"),_=Oe("isSeeking"),P=Oe("groupIndices").length>0,D=Oe("alignToBottom"),z=Oe("initialItemFinalLocationReached"),B=e?{}:{boxSizing:"border-box",...g?{display:"inline-block",height:"100%",marginLeft:x!==0?x:D?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:x!==0?x:D?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...z?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&C?u.jsx(C,{...tn(C,c)}):u.jsx(k,{...tn(k,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:y,style:B,children:(e?t.topItems:t.items).map(O=>{const H=O.originalIndex,R=j(H+t.firstItemIndex,O.data,c);return _?b.createElement(T,{...tn(T,c),height:O.size,index:O.index,key:R,type:O.type||"item",...O.type==="group"?{}:{groupIndex:O.groupIndex}}):O.type==="group"?b.createElement(E,{...tn(E,c),"data-index":H,"data-item-index":O.index,"data-known-size":O.size,key:R,style:xv},d(O.index,c)):b.createElement(S,{...tn(S,c),...Cv(S,O.data),"data-index":H,"data-item-group-index":O.groupIndex,"data-item-index":O.index,"data-known-size":O.size,key:R,style:g?vv:ed},P?l(O.index,O.groupIndex,O.data,c):l(O.index,O.data,c))})})}),wv={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},bv={outline:"none",overflowX:"auto",position:"relative"},Is=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),Sv={position:_a(),top:0,width:"100%",zIndex:1};function tn(e,t){if(typeof e!="string")return{context:t}}function Cv(e,t){return{item:typeof e=="string"?void 0:t}}const kv=b.memo(function(){const e=Oe("HeaderComponent"),t=Sn("headerHeight"),n=Oe("HeaderFooterTag"),r=Tr(b.useMemo(()=>s=>{t(lr(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),Tv=b.memo(function(){const e=Oe("FooterComponent"),t=Sn("footerHeight"),n=Oe("HeaderFooterTag"),r=Tr(b.useMemo(()=>s=>{t(lr(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null});function nd({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:m}=Zu(a,c,l,d,void 0,f);return e("scrollTo",m),e("scrollBy",h),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?bv:wv,...o},tabIndex:0,...i,...tn(l,s),children:r})})}function rd({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=b.useRef(null),m=t("scrollerRef"),{scrollByCallback:g,scrollerRef:y,scrollToCallback:x}=Zu(a,c,l,m,h);return Ju(()=>{var w;return y.current=h||((w=p.current)==null?void 0:w.ownerDocument.defaultView),()=>{y.current=null}},[y,h]),e("windowScrollTo",x),e("scrollBy",g),u.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...tn(l,s),children:r})})}const Ev=({children:e})=>{const t=b.useContext(Yu),n=Sn("viewportHeight"),r=Sn("fixedItemHeight"),o=Oe("alignToBottom"),s=Oe("horizontalDirection"),i=b.useMemo(()=>gu(n,l=>lr(l,s?"width":"height")),[n,s]),a=Tr(i,!0,Oe("skipAnimationFrameInResizeObserver"));return b.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:Is(o),children:e})},Iv=({children:e})=>{const t=b.useContext(Yu),n=Sn("windowViewportRect"),r=Sn("fixedItemHeight"),o=Oe("customScrollParent"),s=bu(n,o,Oe("skipAnimationFrameInResizeObserver")),i=Oe("alignToBottom");return b.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:Is(i),children:e})},Nv=({children:e})=>{const t=Oe("TopItemListComponent")||"div",n=Oe("headerHeight"),r={...Sv,marginTop:`${n}px`},o=Oe("context");return u.jsx(t,{style:r,...tn(t,o),children:e})},Av=b.memo(function(e){const t=Oe("useWindowScroll"),n=Oe("topItemsIndexes").length>0,r=Oe("customScrollParent"),o=Oe("context");return u.jsxs(r||t?Pv:jv,{...e,context:o,children:[n&&u.jsx(Nv,{children:u.jsx(td,{showTopList:!0})}),u.jsxs(r||t?Iv:Ev,{children:[u.jsx(kv,{}),u.jsx(td,{}),u.jsx(Tv,{})]})]})}),{Component:_v,useEmitter:Pa,useEmitterValue:Oe,usePublisher:Sn}=Gu(gv,{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"}},Av),jv=nd({useEmitter:Pa,useEmitterValue:Oe,usePublisher:Sn}),Pv=rd({useEmitter:Pa,useEmitterValue:Oe,usePublisher:Sn}),Rv=_v;Tt(qu,at(()=>{const e=ee(c=>u.jsxs("td",{children:["Item $",c]})),t=ee(null),n=ee(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=ee(null),o=ee(null),s=ee({}),i=ee(ja),a=ee(Kr),l=(c,d=null)=>en(X(s,pe(f=>f[c]),Et()),d);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:a,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")}})),_a();const od={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},Ov={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:sd,floor:Ns,max:Io,min:Ra,round:id}=Math;function ad(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Mv(e){return{...Ov,items:e}}function As(e,t){return e&&e.width===t.width&&e.height===t.height}function Dv(e,t){return e&&e.column===t.column&&e.row===t.row}const Lv=at(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:m,propsReady:g},{customScrollParent:y,useWindowScroll:x,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:T},k])=>{const S=ee(0),E=ee(0),j=ee(od),_=ee({height:0,width:0}),P=ee({height:0,width:0}),D=Ze(),z=Ze(),B=ee(0),O=ee(null),H=ee({column:0,row:0}),R=Ze(),V=Ze(),$=ee(!1),F=ee(0),ne=ee(!0),Q=ee(!1),ye=ee(!1);dt(X(m,Ue(F),_e(([L,q])=>!!q)),()=>{ze(ne,!1)}),dt(X(Ft(m,ne,P,_,F,Q),_e(([L,q,ie,ce,,U])=>L&&!q&&ie.height!==0&&ce.height!==0&&!U)),([,,,,L])=>{ze(Q,!0),Ca(1,()=>{ze(D,L)}),jn(X(c),()=>{ze(t,[0,0]),ze(ne,!0)})}),we(X(V,_e(L=>L!=null&&L.scrollTop>0),Bn(0)),E),dt(X(m,Ue(V),_e(([,L])=>L!=null)),([,L])=>{L&&(ze(_,L.viewport),ze(P,L.item),ze(H,L.gap),L.scrollTop>0&&(ze($,!0),jn(X(c,kr(1)),q=>{ze($,!1)}),ze(l,{top:L.scrollTop})))}),we(X(_,pe(({height:L})=>L)),f),we(X(Ft(Ne(_,As),Ne(P,As),Ne(H,(L,q)=>L&&L.column===q.column&&L.row===q.row),Ne(c)),pe(([L,q,ie,ce])=>({gap:ie,item:q,scrollTop:ce,viewport:L}))),R),we(X(Ft(Ne(S),r,Ne(H,Dv),Ne(P,As),Ne(_,As),Ne(O),Ne(E),Ne($),Ne(ne),Ne(F)),_e(([,,,,,,,L])=>!L),pe(([L,[q,ie],ce,U,We,re,xe,,Pe,$e])=>{const{column:rt,row:Se}=ce,{height:Ye,width:ot}=U,{width:et}=We;if(xe===0&&(L===0||et===0))return od;if(ot===0){const st=ka($e,L),Gt=st+Math.max(xe-1,0);return Mv(ad(st,Gt,re))}const Xe=ld(et,ot,rt);let Ke,tt;Pe?q===0&&ie===0&&xe>0?(Ke=0,tt=xe-1):(Ke=Xe*Ns((q+Se)/(Ye+Se)),tt=Xe*sd((ie+Se)/(Ye+Se))-1,tt=Ra(L-1,Io(tt,Xe-1)),Ke=Ra(tt,Io(0,Ke))):(Ke=0,tt=-1);const Ot=ad(Ke,tt,re),{bottom:St,top:nt}=cd(We,ce,U,Ot),yt=sd(L/Xe),Nt=yt*Ye+(yt-1)*Se-St;return{bottom:St,itemHeight:Ye,items:Ot,itemWidth:ot,offsetBottom:Nt,offsetTop:nt,top:nt}})),j),we(X(O,_e(L=>L!==null),pe(L=>L.length)),S),we(X(Ft(_,P,j,H),_e(([L,q,{items:ie}])=>ie.length>0&&q.height!==0&&L.height!==0),pe(([L,q,{items:ie},ce])=>{const{bottom:U,top:We}=cd(L,ce,q,ie);return[We,U]}),Et(wo)),t);const je=ee(!1);we(X(c,Ue(je),pe(([L,q])=>q||L!==0)),je);const J=mn(X(Ft(j,S),_e(([{items:L}])=>L.length>0),Ue(je),_e(([[L,q],ie])=>{const ce=L.items[L.items.length-1].index===q-1;return(ie||L.bottom>0&&L.itemHeight>0&&L.offsetBottom===0&&L.items.length===q)&&ce}),pe(([[,L]])=>L-1),Et())),ue=mn(X(Ne(j),_e(({items:L})=>L.length>0&&L[0].index===0),Bn(0),Et())),ke=mn(X(Ne(j),Ue($),_e(([{items:L},q])=>L.length>0&&!q),pe(([{items:L}])=>({endIndex:L[L.length-1].index,startIndex:L[0].index})),Et(Nu),Qn(0)));we(ke,p.scrollSeekRangeChanged),we(X(D,Ue(_,P,S,H),pe(([L,q,ie,ce,U])=>{const We=Ou(L),{align:re,behavior:xe,offset:Pe}=We;let $e=We.index;$e==="LAST"&&($e=ce-1),$e=Io(0,$e,Ra(ce-1,$e));let rt=Oa(q,U,ie,$e);return re==="end"?rt=id(rt-q.height+ie.height):re==="center"&&(rt=id(rt-q.height/2+ie.height/2)),Pe&&(rt+=Pe),{behavior:xe,top:rt}})),l);const te=en(X(j,pe(L=>L.offsetBottom+L.bottom)),0);return we(X(T,pe(L=>({height:L.visibleHeight,width:L.visibleWidth}))),_),{customScrollParent:y,data:O,deviation:B,footerHeight:o,gap:H,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:P,overscan:n,restoreStateFrom:V,scrollBy:i,scrollContainerState:a,scrollHeight:z,scrollTo:l,scrollToIndex:D,scrollTop:c,smoothScrollTargetReached:d,totalCount:S,useWindowScroll:x,viewportDimensions:_,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:T,...p,gridState:j,horizontalDirection:ye,initialTopMostItemIndex:F,totalListHeight:te,...h,endReached:J,propsReady:g,rangeChanged:ke,startReached:ue,stateChanged:R,stateRestoreInProgress:$,...k}},Tt(Ta,rn,Eo,Vu,cr,Ia,ar));function ld(e,t,n){return Io(1,Ns((e+n)/(Ns(t)+n)))}function cd(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=Oa(e,t,n,r[0].index);return{bottom:Oa(e,t,n,r[r.length-1].index)+o,top:s}}function Oa(e,t,n,r){const o=ld(e.width,n.width,t.column),s=Ns(r/o),i=s*n.height+Io(0,s-1)*t.row;return i>0?i+t.row:i}const Fv=at(()=>{const e=ee(f=>`Item ${f}`),t=ee({}),n=ee(null),r=ee("virtuoso-grid-item"),o=ee("virtuoso-grid-list"),s=ee(ja),i=ee("div"),a=ee(Kr),l=(f,h=null)=>en(X(t,pe(p=>p[f]),Et()),h),c=ee(!1),d=ee(!1);return we(Ne(d),c),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),$v=at(([e,t])=>({...e,...t}),Tt(Lv,Fv)),zv=b.memo(function(){const e=It("gridState"),t=It("listClassName"),n=It("itemClassName"),r=It("itemContent"),o=It("computeItemKey"),s=It("isSeeking"),i=Cn("scrollHeight"),a=It("ItemComponent"),l=It("ListComponent"),c=It("ScrollSeekPlaceholder"),d=It("context"),f=Cn("itemDimensions"),h=Cn("gap"),p=It("log"),m=It("stateRestoreInProgress"),g=Cn("reportReadyState"),y=Tr(b.useMemo(()=>x=>{const w=x.parentElement.parentElement.scrollHeight;i(w);const C=x.firstChild;if(C){const{height:T,width:k}=C.getBoundingClientRect();f({height:T,width:k})}h({column:dd("column-gap",getComputedStyle(x).columnGap,p),row:dd("row-gap",getComputedStyle(x).rowGap,p)})},[i,f,h,p]),!0,!1);return Ju(()=>{e.itemHeight>0&&e.itemWidth>0&&g(!0)},[e]),m?null:u.jsx(l,{className:t,ref:y,...tn(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(x=>{const w=o(x.index,x.data,d);return s?u.jsx(c,{...tn(c,d),height:e.itemHeight,index:x.index,width:e.itemWidth},w):b.createElement(a,{...tn(a,d),className:n,"data-index":x.index,key:w},r(x.index,x.data,d))})})}),Bv=b.memo(function(){const e=It("HeaderComponent"),t=Cn("headerHeight"),n=It("headerFooterTag"),r=Tr(b.useMemo(()=>s=>{t(lr(s,"height"))},[t]),!0,!1),o=It("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),Hv=b.memo(function(){const e=It("FooterComponent"),t=Cn("footerHeight"),n=It("headerFooterTag"),r=Tr(b.useMemo(()=>s=>{t(lr(s,"height"))},[t]),!0,!1),o=It("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),Uv=({children:e})=>{const t=b.useContext(Xu),n=Cn("itemDimensions"),r=Cn("viewportDimensions"),o=Tr(b.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return b.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:Is(!1),children:e})},Wv=({children:e})=>{const t=b.useContext(Xu),n=Cn("windowViewportRect"),r=Cn("itemDimensions"),o=It("customScrollParent"),s=bu(n,o,!1);return b.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:Is(!1),children:e})},Vv=b.memo(function({...e}){const t=It("useWindowScroll"),n=It("customScrollParent"),r=n||t?qv:Kv,o=n||t?Wv:Uv,s=It("context");return u.jsx(r,{...e,...tn(r,s),children:u.jsxs(o,{children:[u.jsx(Bv,{}),u.jsx(zv,{}),u.jsx(Hv,{})]})})}),{useEmitter:ud,useEmitterValue:It,usePublisher:Cn}=Gu($v,{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"}},Vv),Kv=nd({useEmitter:ud,useEmitterValue:It,usePublisher:Cn}),qv=rd({useEmitter:ud,useEmitterValue:It,usePublisher:Cn});function dd(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,dn.WARN),t==="normal"?0:parseInt(t??"0",10)}const Gv=Go.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 fd({className:e,variant:t,...n}){return u.jsx("div",{className:oe(Gv({variant:t}),e),...n})}const No=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));No.displayName="Card";const Ao=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("flex flex-col space-y-1.5 p-6",e),...t}));Ao.displayName="CardHeader";const _o=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:oe("text-2xl font-semibold leading-none tracking-tight",e),...t}));_o.displayName="CardTitle";const hd=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:oe("text-sm text-muted-foreground",e),...t}));hd.displayName="CardDescription";const jo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("p-6 pt-0",e),...t}));jo.displayName="CardContent";const pd=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("flex items-center p-6 pt-0",e),...t}));pd.displayName="CardFooter";const Yv=1,Xv=1e6;let Ma=0;function Jv(){return Ma=(Ma+1)%Number.MAX_SAFE_INTEGER,Ma.toString()}const Da=new Map,md=e=>{if(Da.has(e))return;const t=setTimeout(()=>{Da.delete(e),Po({type:"REMOVE_TOAST",toastId:e})},Xv);Da.set(e,t)},Zv=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,Yv)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?md(n):e.toasts.forEach(r=>{md(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},_s=[];let js={toasts:[]};function Po(e){js=Zv(js,e),_s.forEach(t=>{t(js)})}function Qv({...e}){const t=Jv(),n=o=>Po({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Po({type:"DISMISS_TOAST",toastId:t});return Po({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function La(){const[e,t]=v.useState(js);return v.useEffect(()=>(_s.push(t),()=>{const n=_s.indexOf(t);n>-1&&_s.splice(n,1)}),[e]),{...e,toast:Qv,dismiss:n=>Po({type:"DISMISS_TOAST",toastId:n})}}async function gd(e,t){return await wn(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function yd(e,t){return await(await gd(`/files/${e}/view`,t)).text()}async function ew(e,t){const n=await gd(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await wn(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function tw(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await wn("/files",{params:r})}function Fa(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function xd(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function Ro(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(Ro).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(xd(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=Ro(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function Oo(e){if(typeof e=="string")return e;if(xd(e))return"";try{const t=Ro(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function nw(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function rw(e){const t=Oo(e);return typeof e=="string"&&nw(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Ps(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=Fa(t);if(n!==null)return Ps(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Ps(e.content):e}function ge(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function vd(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function $a(...e){return t=>{let n=!1;const r=e.map(o=>{const s=vd(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():vd(e[o],null)}}}}function Qe(...e){return v.useCallback($a(...e),e)}function ow(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function er(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:h,children:p,...m}=f,g=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,y=v.useMemo(()=>m,Object.values(m));return u.jsx(g.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,m=v.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,sw(o,...t)]}function sw(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},iw=v[" useId ".trim().toString()]||(()=>{}),aw=0;function tr(e){const[t,n]=v.useState(iw());return Kt(()=>{n(r=>r??String(aw++))},[e]),e||(t?`radix-${t}`:"")}var lw=v[" useInsertionEffect ".trim().toString()]||Kt;function Gr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=cw({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"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=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const h=uw(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function cw({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return lw(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function uw(e){return typeof e=="function"}var dw=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],De=dw.reduce((e,t)=>{const n=vr.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function wd(e,t){e&&Yo.flushSync(()=>e.dispatchEvent(t))}function qt(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function fw(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var hw="DismissableLayer",za="dismissableLayer.update",pw="dismissableLayer.pointerDownOutside",mw="dismissableLayer.focusOutside",bd,Sd=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Rs=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(Sd),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),m=Qe(t,E=>f(E)),g=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=g.indexOf(y),w=d?g.indexOf(d):-1,C=c.layersWithOutsidePointerEventsDisabled.size>0,T=w>=x,k=xw(E=>{const j=E.target,_=[...c.branches].some(P=>P.contains(j));!T||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),S=vw(E=>{const j=E.target;[...c.branches].some(P=>P.contains(j))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return fw(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(bd=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),Cd(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=bd)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),Cd())},[d,c]),v.useEffect(()=>{const E=()=>p({});return document.addEventListener(za,E),()=>document.removeEventListener(za,E)},[]),u.jsx(De.div,{...l,ref:m,style:{pointerEvents:C?T?"auto":"none":void 0,...e.style},onFocusCapture:ge(e.onFocusCapture,S.onFocusCapture),onBlurCapture:ge(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:ge(e.onPointerDownCapture,k.onPointerDownCapture)})});Rs.displayName=hw;var gw="DismissableLayerBranch",yw=v.forwardRef((e,t)=>{const n=v.useContext(Sd),r=v.useRef(null),o=Qe(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(De.div,{...e,ref:o})});yw.displayName=gw;function xw(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){kd(pw,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function vw(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&kd(mw,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Cd(){const e=new CustomEvent(za);document.dispatchEvent(e)}function kd(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?wd(o,s):o.dispatchEvent(s)}var Ba="focusScope.autoFocusOnMount",Ha="focusScope.autoFocusOnUnmount",Td={bubbles:!1,cancelable:!0},ww="FocusScope",Os=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=qt(o),d=qt(s),f=v.useRef(null),h=Qe(t,g=>l(g)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let g=function(C){if(p.paused||!a)return;const T=C.target;a.contains(T)?f.current=T:ur(f.current,{select:!0})},y=function(C){if(p.paused||!a)return;const T=C.relatedTarget;T!==null&&(a.contains(T)||ur(f.current,{select:!0}))},x=function(C){if(document.activeElement===document.body)for(const k of C)k.removedNodes.length>0&&ur(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){Nd.add(p);const g=document.activeElement;if(!a.contains(g)){const x=new CustomEvent(Ba,Td);a.addEventListener(Ba,c),a.dispatchEvent(x),x.defaultPrevented||(bw(Ew(Ed(a)),{select:!0}),document.activeElement===g&&ur(a))}return()=>{a.removeEventListener(Ba,c),setTimeout(()=>{const x=new CustomEvent(Ha,Td);a.addEventListener(Ha,d),a.dispatchEvent(x),x.defaultPrevented||ur(g??document.body,{select:!0}),a.removeEventListener(Ha,d),Nd.remove(p)},0)}}},[a,c,d,p]);const m=v.useCallback(g=>{if(!n&&!r||p.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,x=document.activeElement;if(y&&x){const w=g.currentTarget,[C,T]=Sw(w);C&&T?!g.shiftKey&&x===T?(g.preventDefault(),n&&ur(C,{select:!0})):g.shiftKey&&x===C&&(g.preventDefault(),n&&ur(T,{select:!0})):x===w&&g.preventDefault()}},[n,r,p.paused]);return u.jsx(De.div,{tabIndex:-1,...i,ref:h,onKeyDown:m})});Os.displayName=ww;function bw(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(ur(r,{select:t}),document.activeElement!==n)return}function Sw(e){const t=Ed(e),n=Id(t,e),r=Id(t.reverse(),e);return[n,r]}function Ed(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Id(e,t){for(const n of e)if(!Cw(n,{upTo:t}))return n}function Cw(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function kw(e){return e instanceof HTMLInputElement&&"select"in e}function ur(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&kw(e)&&t&&e.select()}}var Nd=Tw();function Tw(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Ad(e,t),e.unshift(t)},remove(t){var n;e=Ad(e,t),(n=e[0])==null||n.resume()}}}function Ad(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Ew(e){return e.filter(t=>t.tagName!=="A")}var Iw="Portal",Ms=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Pi.createPortal(u.jsx(De.div,{...r,ref:t}),i):null});Ms.displayName=Iw;function Nw(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var kn=e=>{const{present:t,children:n}=e,r=Aw(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=Qe(r.ref,_w(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};kn.displayName="Presence";function Aw(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Nw(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Ds(r.current);s.current=a==="mounted"?c:"none"},[a]),Kt(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=Ds(c);e?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const g=Ds(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&g&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},h=p=>{p.target===t&&(s.current=Ds(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Ds(e){return(e==null?void 0:e.animationName)||"none"}function _w(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Ua=0;function Wa(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??_d()),document.body.insertAdjacentElement("beforeend",e[1]??_d()),Ua++,()=>{Ua===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ua--}},[])}function _d(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Wn=function(){return Wn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Wn.apply(this,arguments)};function jd(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function jw(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Ls="right-scroll-bar-position",Fs="width-before-scroll-bar",Pw="with-scroll-bars-hidden",Rw="--removed-body-scroll-bar-size";function Va(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Ow(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Mw=typeof window<"u"?v.useLayoutEffect:v.useEffect,Pd=new WeakMap;function Dw(e,t){var n=Ow(null,function(r){return e.forEach(function(o){return Va(o,r)})});return Mw(function(){var r=Pd.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Va(a,null)}),s.forEach(function(a){o.has(a)||Va(a,i)})}Pd.set(n,e)},[e]),n}function Lw(e){return e}function Fw(e,t){t===void 0&&(t=Lw);var n=[],r=!1,o={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]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function $w(e){e===void 0&&(e={});var t=Fw(null);return t.options=Wn({async:!0,ssr:!1},e),t}var Rd=function(e){var t=e.sideCar,n=jd(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,Wn({},n))};Rd.isSideCarExport=!0;function zw(e,t){return e.useMedium(t),Rd}var Od=$w(),Ka=function(){},$s=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:Ka,onWheelCapture:Ka,onTouchMoveCapture:Ka}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,m=e.noIsolation,g=e.inert,y=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,C=e.gapMode,T=jd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,S=Dw([n,t]),E=Wn(Wn({},T),o);return v.createElement(v.Fragment,null,d&&v.createElement(k,{sideCar:Od,removeScrollBar:c,shards:f,noRelative:p,noIsolation:m,inert:g,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:C}),i?v.cloneElement(v.Children.only(a),Wn(Wn({},E),{ref:S})):v.createElement(w,Wn({},E,{className:l,ref:S}),a))});$s.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},$s.classNames={fullWidth:Fs,zeroRight:Ls};var Bw=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Hw(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Bw();return t&&e.setAttribute("nonce",t),e}function Uw(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Ww(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Vw=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Hw())&&(Uw(t,n),Ww(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Kw=function(){var e=Vw();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Md=function(){var e=Kw(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},qw={left:0,top:0,right:0,gap:0},qa=function(e){return parseInt(e||"",10)||0},Gw=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[qa(n),qa(r),qa(o)]},Yw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return qw;var t=Gw(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Xw=Md(),Yr="data-scroll-locked",Jw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
|
38
|
+
`)}const tu=200;function Zy({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o,onStreamClosed:s,onConnectionError:i,onAuthError:a,onHeartbeat:l}){const c=b.useRef(null),d=b.useRef(null),f=b.useRef(new Map),h=b.useRef(null),p=b.useCallback(_=>{try{const P=globalThis.structuredClone;if(typeof P=="function")return P(_)}catch{}try{return JSON.parse(JSON.stringify(_))}catch{return _}},[]),m=b.useCallback((_,P)=>{if(!_)return;const D=f.current.get(_)??[],z=p(P),B=D.length>=tu?[...D.slice(D.length-tu+1),z]:[...D,z];f.current.set(_,B)},[p]),g=b.useCallback(_=>{_&&f.current.set(_,[])},[]),y=b.useCallback(_=>{const P=_??d.current;if(!P)return;const D=f.current.get(P);D!=null&&D.length&&D.forEach(z=>{try{n(z)}catch(B){console.error("[useChatStreamingService] Failed to replay buffered event",B)}})},[n]),x=b.useCallback(_=>{var z,B,O,H,R;const P=_.seq??null;if(P!==null){const V=c.current;if(V!==null){if(P<=V)return;P>V+1&&(o==null||o({from:V,to:P}))}c.current=P}if(_.type==="thread_info"){d.current=_.threadId,h.current&&(h.current.threadIdGuess=_.threadId),g(_.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",_);try{t(_)}catch(V){console.error("[useChatStreamingService] Error in onThreadInfo handler:",V)}return}if(_.type==="heartbeat"){try{l==null||l(_)}catch(V){console.error("[useChatStreamingService] Error in onHeartbeat handler:",V)}return}if(_.type==="error"){const V=_;if(V.error_type==="auth_error"||V.code==="TOKEN_EXPIRED"||((z=V.message)==null?void 0:z.includes("token"))||((B=V.message)==null?void 0:B.includes("401"))||((O=V.message)==null?void 0:O.includes("unauthorized"))||((H=V.message)==null?void 0:H.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",V.message);try{a==null||a(V.message)}catch(F){console.warn("[useChatStreamingService] onAuthError handler failed",F)}}}const D=_.threadId??(_.type==="state_history"?_.threadId:void 0)??d.current??((R=h.current)==null?void 0:R.threadIdGuess)??null;if(_.type==="state_history"&&(d.current=D??d.current),Uy(_)){_.type==="checkpoint"||_.type==="state_history"?g(D??null):m(D??null,_);try{n(_)}catch(V){console.error("[useChatStreamingService] Error in onMessageEvent handler:",V)}return}try{r==null||r(_)}catch(V){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",V)}},[m,g,n,o,t,r]),{stream:w,stop:C,isStreaming:T,error:k,setToken:S}=eu({baseUrl:e,token:void 0}),E=b.useCallback((_,P)=>{c.current=null,d.current=_.threadId??null,h.current={request:_,callbacks:P,manualStop:!1,threadIdGuess:_.threadId??null},w(_,x,{onOpen:P==null?void 0:P.onOpen,onError:D=>{var z;(z=P==null?void 0:P.onError)==null||z.call(P,D)},onGap:(P==null?void 0:P.onGap)??o,onConnectionError:D=>{var z;i==null||i(D),(z=P==null?void 0:P.onConnectionError)==null||z.call(P,D)},onAuthError:D=>{var z;a==null||a(D),(z=P==null?void 0:P.onAuthError)==null||z.call(P,D)},onHeartbeat:D=>{var z;try{l==null||l(D)}catch(B){console.warn("[useChatStreamingService] onHeartbeat handler failed",B)}try{(z=P==null?void 0:P.onHeartbeat)==null||z.call(P,D)}catch(B){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",B)}},onClosed:D=>{var H,R,V,$;const z=((H=h.current)==null?void 0:H.manualStop)??!1,B=d.current??((R=h.current)==null?void 0:R.threadIdGuess)??((V=D.lastStateHistory)==null?void 0:V.threadId)??null;(D.reason==="complete"||D.reason==="aborted"&&z)&&g(B);const O={...D,threadId:B,manualStop:z};try{s==null||s(O)}catch(F){console.warn("[useChatStreamingService] onStreamClosed handler failed",F)}try{($=P==null?void 0:P.onClosed)==null||$.call(P,O)}catch(F){console.warn("[useChatStreamingService] downstream onClosed handler failed",F)}h.current&&(h.current=null)}})},[g,x,a,i,l,o,s,w]),j=b.useCallback(()=>{h.current&&(h.current.manualStop=!0),C()},[C]);return b.useMemo(()=>({startStream:E,stop:j,isStreaming:T,error:k,setAuthToken:S,replayBufferedEvents:y}),[E,j,T,k,S,y])}const nu=50,Qy=750,ta="chat-history@1",ex=5,tx=1e3,nx=15e3,ds=300;function ru(e,t=ds){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:t});return}catch{}window.setTimeout(e,t)}function Cr(){return typeof window<"u"&&typeof window.localStorage<"u"}function na(e){if(!Cr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function ra(e,t){if(!Cr())return!1;try{return window.localStorage.setItem(e,t),!0}catch{return!1}}function oa(e){if(Cr())try{window.localStorage.removeItem(e)}catch{}}function sa(e){return e==null?e:{...e}}function rx(e){return e==null?e:{...e}}function ox(e){if(Array.isArray(e))return e.slice();if(e==null)return e}function sx(e){if(Array.isArray(e))return e.map(t=>({...t}));if(e==null)return e}function un(e,t={}){const n=t.cloneMessages??!1,r=Array.isArray(e==null?void 0:e.messages)?e.messages:[],o=sa(e==null?void 0:e.metadata),s=sa(e==null?void 0:e.config),i=sa(e==null?void 0:e.parentConfig),a=ox(e==null?void 0:e.next),l=sx(e==null?void 0:e.tasks),c=rx(e==null?void 0:e.values),d={checkpointId:(e==null?void 0:e.checkpointId)??null,checkpointNs:(e==null?void 0:e.checkpointNs)??null,createdAt:(e==null?void 0:e.createdAt)??null,parentId:(e==null?void 0:e.parentId)??null,branchLabel:(e==null?void 0:e.branchLabel)??null,lastMessageId:(e==null?void 0:e.lastMessageId)??null,messagesLen:typeof(e==null?void 0:e.messagesLen)=="number"?e.messagesLen:r.length,hasMessages:typeof(e==null?void 0:e.hasMessages)=="boolean"?e.hasMessages:r.length>0,messages:n?r.slice():r,nextCursor:(e==null?void 0:e.nextCursor)??null,nextCursorNs:(e==null?void 0:e.nextCursorNs)??null,interrupt:(e==null?void 0:e.interrupt)??null};return o!==void 0&&(d.metadata=o),s!==void 0&&(d.config=s),i!==void 0&&(d.parentConfig=i),a!==void 0&&(d.next=a),l!==void 0&&(d.tasks=l),c!==void 0&&(d.values=c),d}function ix(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function ou(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}function ia(e,t){return`${e}${t}`}function ax(e,t){const n=na(ia(e,t));if(!n)return null;try{const r=JSON.parse(n);return typeof(r==null?void 0:r.threadId)!="string"?null:{threadId:r.threadId,snapshot:un(r.snapshot,{cloneMessages:!0}),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0}}catch{return null}}function lx(e,t,n=100){if(!Cr())return;const r=un(t.snapshot,{cloneMessages:!0}),o={threadId:t.threadId,snapshot:{...r,messages:r.messages.slice(-n)},updatedAt:Date.now()},s=ia(e,t.threadId),i=JSON.stringify(o);if(!ra(s,i))try{const a=[];for(let l=0;l<window.localStorage.length;l++){const c=window.localStorage.key(l);if(!c||c===s||!c.startsWith(e))continue;const d=window.localStorage.getItem(c);if(!d){a.push({key:c,updatedAt:0});continue}try{const f=JSON.parse(d),h=typeof(f==null?void 0:f.updatedAt)=="number"&&Number.isFinite(f.updatedAt)?f.updatedAt:0;a.push({key:c,updatedAt:h})}catch{a.push({key:c,updatedAt:0})}}a.sort((l,c)=>l.updatedAt-c.updatedAt);for(const l of a)if(window.localStorage.removeItem(l.key),ra(s,i))break}catch{}}function cx(e,t){oa(ia(e,t))}function ux(e){if(Cr())try{for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n&&n.startsWith(e)&&window.localStorage.removeItem(n)}}catch{}}function su(e,t,n){return`${e}__${t??""}__${n??""}`}function fs(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?{...e}:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function dx(e,t){return fs(e,t)}function fx(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function hx(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function iu(e,t){const n=fs(e.metadata,t.metadata),r=fs(e.config,t.config),o=fs(e.parentConfig,t.parentConfig),s=fx(e.next,t.next),i=hx(e.tasks,t.tasks),a=dx(e.values,t.values),l={};return n!==void 0&&(l.metadata=n??null),r!==void 0&&(l.config=r??null),o!==void 0&&(l.parentConfig=o??null),s!==void 0&&(l.next=s??null),i!==void 0&&(l.tasks=i??null),a!==void 0&&(l.values=a??null),l}function au(e){return Array.isArray(e)?e.filter(t=>!!(t&&(t.checkpointId||t.checkpointNs))).map(t=>{const n=un(t,{cloneMessages:!0});return{...n,messages:Array.isArray(n.messages)?n.messages:[],values:n.values??null}}):[]}const px="cachedThreads",mx="v1",aa=200;function gx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function la(e,t){return`cachedThreads:v1:${e}:${gx(t||"anon")}`}function yx(){const e=na(px);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function xx(e){const t=na(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function ca(e,t){ra(e,JSON.stringify(t))}function ua(e){const t=xx(e);if(t.length>0)return t;const n=yx();if(n.length>0)try{ca(e,n.slice(0,aa))}catch{}return n}function hs(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function da(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function vx({currentThreadId:e,currentThreadIdRef:t}){const[n,r]=b.useState([]),o=b.useRef(new Map),s=b.useRef(new Map),i=b.useCallback(m=>{if(!m){r([]);return}const g=o.current.get(m);if(!g||!g.length){r([]);return}r(g.map(y=>un(y,{cloneMessages:!0})))},[]);b.useEffect(()=>{i(e)},[e,i]);const a=b.useCallback((m,g,y)=>{if(!m)return;const x=y==="replace"?[]:o.current.get(m)??[],w=y==="replace"?g:[...g,...x];if(!w.length){y==="replace"&&o.current.set(m,[]),m===t.current&&r([]);return}const C=new Map;for(const k of w){if(!(k!=null&&k.checkpointId))continue;const S=`${k.checkpointId}::${k.checkpointNs??""}`,E=un(k,{cloneMessages:!0}),j=C.get(S);if(!j){C.set(S,E);continue}const _=iu(j,E);C.set(S,{...j,..._})}const T=Array.from(C.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});o.current.set(m,T),m===t.current&&i(m)},[t,i]),l=b.useCallback((m,g,y)=>{if(!m)return;const x=s.current.get(m),w=y==="replace"||!x?new Map:new Map(x);if(g&&typeof g=="object")for(const[C,T]of Object.entries(g)){if(!(T!=null&&T.checkpointId))continue;const k=C||Wr(T.checkpointId,T.checkpointNs??null);w.set(k,un(T,{cloneMessages:!0}))}s.current.set(m,w)},[]),c=b.useCallback((m,g)=>{if(!m)return!1;const y=au(g);if(!y.length)return!1;const x=o.current.get(m)??[],w=new Map,C=(k,{preferExisting:S})=>{for(const E of k){if(!(E!=null&&E.checkpointId)&&!(E!=null&&E.checkpointNs))continue;const j=Wr(E.checkpointId??null,E.checkpointNs??null);j&&(S&&w.has(j)?w.set(j,E):w.has(j)&&S||w.set(j,E))}};C(y,{preferExisting:!1}),C(x,{preferExisting:!0});const T=Array.from(w.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});return o.current.set(m,T),m===t.current&&r(T.map(k=>un(k,{cloneMessages:!0}))),!0},[t]),d=b.useCallback(m=>{m&&(o.current.delete(m),s.current.delete(m),m===t.current&&r([]))},[t]),f=b.useCallback(()=>{r([])},[]),h=b.useCallback(m=>m?s.current.get(m)??null:null,[]),p=b.useCallback((m,g)=>{var y;if(m)return(y=s.current.get(m))==null?void 0:y.get(g)},[]);return{threadCheckpoints:n,syncActiveThreadCheckpoints:i,updateCheckpointCache:a,updateCheckpointSnapshots:l,applyCheckpointSummaries:c,clearThreadCaches:d,resetThreadCheckpoints:f,getSnapshotCache:h,getSnapshotFromCache:p}}const lu=b.createContext(null),cu=b.createContext(null),uu=b.createContext(null),wx=b.createContext(!1);function bx({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onAuthError:a,onThreadChange:l}){const{api:c,baseUrl:d}=Yi(),f=b.useMemo(()=>Zn(d),[d]),h=b.useMemo(()=>{try{return new URL(d).host}catch{return"unknown"}},[d]),p=b.useMemo(()=>`threadPayload:${mx}:${h}:`,[h]),m=b.useCallback(I=>ax(p,I),[p]),g=b.useCallback((I,A=100)=>{lx(p,I,A)},[p]),y=b.useCallback(I=>{cx(p,I)},[p]),x=b.useCallback(()=>{ux(p)},[p]),[w,C]=b.useState(()=>{var I;return la(h,(I=c.getAuthToken)==null?void 0:I.call(c))}),[T,k]=b.useState(()=>{var A;const I=ua(la(h,(A=c.getAuthToken)==null?void 0:A.call(c)));return hs(I)}),S=b.useMemo(()=>da(T),[T]),[E,j]=b.useState(t),[_,P]=b.useState(!1),[D,z]=b.useState(!1),[B,O]=b.useState(null),[H,R]=b.useState(null),[V,$]=b.useState(null),F=b.useCallback(()=>{const I=ua(w);b.startTransition(()=>{k(hs(I))})},[w]),[ne,Q]=b.useState(!1),[ye,je]=b.useState(!1),[J,ue]=b.useState(null),[ke,te]=b.useState(void 0),[L,q]=b.useState(void 0),[ie,ce]=b.useState(void 0),{state:U,dispatch:We,seed:re,prepend:xe,pushUser:Pe,onEvent:$e,reset:rt}=Kc(),Se=b.useRef(E);b.useEffect(()=>{Se.current=E},[E]);const Ye=b.useRef(!1),ot=b.useRef([]),et=b.useRef(null),Xe=b.useRef(null),Ke=b.useRef(new Map),tt=b.useRef(E),Ot=b.useRef(!1),St=b.useRef(null),nt=b.useRef(new Map),yt=b.useRef(new Map),{threadCheckpoints:Nt,syncActiveThreadCheckpoints:st,updateCheckpointCache:Gt,updateCheckpointSnapshots:Yt,applyCheckpointSummaries:Xt,clearThreadCaches:Jt,resetThreadCheckpoints:ft,getSnapshotCache:Ve,getSnapshotFromCache:Mt}=vx({currentThreadId:E,currentThreadIdRef:Se}),_t=b.useCallback(()=>{var K;const I=yt.current;if(I.size<=nu)return;const A=Array.from(I.entries()).sort((fe,le)=>fe[1].timestamp-le[1].timestamp),W=I.size-nu;for(let fe=0;fe<W;fe++){const le=(K=A[fe])==null?void 0:K[0];le&&I.delete(le)}},[]),G=b.useCallback((I,A)=>{if(!I)return null;const W=Array.isArray(I.checkpoints)?I.checkpoints:[];return W.length===0?null:{version:I.version===ta?I.version:ta,threadId:I.threadId??A,checkpoints:W}},[]),Te=b.useCallback((I,A)=>{const{threadId:W,checkpointId:K=null,checkpointNs:fe=null}=I,le=su(W,K,fe);if(A!=null&&A.force)nt.current.delete(le),yt.current.delete(le);else{if(A!=null&&A.preferCache){const kt=yt.current.get(le);if(kt)return Promise.resolve(kt.result)}const Be=nt.current.get(le);if(Be)return Be}const bt=(async()=>{try{const Be=await c.getStateHistory({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0}),kt=G(Be,W);if(kt)return{payload:kt,usedHistoryApi:!0};throw new Error("History response missing checkpoints")}catch(Be){console.warn("[ChatSessionProvider] getStateHistory failed, falling back to getState:",Be);const kt=await c.getState({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0});return{payload:{version:ta,threadId:W,checkpoints:[kt]},usedHistoryApi:!1}}})().then(Be=>(yt.current.set(le,{result:Be,timestamp:Date.now()}),_t(),Be)).finally(()=>{nt.current.get(le)===bt&&nt.current.delete(le)});return nt.current.set(le,bt),bt},[c,G,_t]),ve=b.useCallback((I,A)=>new Promise((W,K)=>{const fe=async()=>{Ye.current=!0;try{await I(),W()}catch(le){K(le)}finally{Ye.current=!1;const le=ot.current.shift();le&&le().catch(()=>{})}};Ye.current?ot.current.push(fe):fe().catch(le=>{K(le)})}),[]),pt=b.useRef(S.length),mt=b.useRef(!1);b.useEffect(()=>{pt.current=S.length},[S.length]),b.useEffect(()=>{const I=U.pendingInterrupt??ix(U.messages);ou(V,I)||$(I??null)},[V,U.messages,U.pendingInterrupt]);const ct=b.useCallback(async()=>{const I=pt.current>0;I||P(!0);try{const A=await c.listThreads();b.startTransition(()=>{k(W=>{const K=ht=>ht.map(bt=>`${bt.threadId}:${bt.updatedAt??""}:${bt.messageCount??""}`).join("|"),fe=da(W);return K(fe)===K(A)||A.length===0&&fe.length>0&&!mt.current?W:hs(A)}),I||P(!1)}),O(null),mt.current||(mt.current=!0)}catch(A){i==null||i(String(A)),console.error("[ChatSessionProvider] Failed to refresh threads:",A),O(String(A)),I||P(!1)}},[c,i]),Me=b.useRef(!1),Ut=b.useRef(null),Le=b.useRef(null),xt=b.useRef(""),[Ln,Dt]=b.useState("idle"),fn=b.useRef({attempts:0,timer:null,reason:null}),io=b.useRef(null),ao=b.useRef(0),Lr=b.useRef(()=>{}),Fr=b.useRef(()=>{}),N=b.useRef(()=>{}),Y=I=>{if(!I||typeof I!="object")return!1;const A=I;return A.code==="ECONNABORTED"?!0:(typeof A.message=="string"?A.message.toLowerCase():"").includes("timeout")},ae=b.useCallback(async I=>{const A=await c.listCheckpointSummaries(I);return au(A??[])},[c]),Ce=b.useCallback((I,A)=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const W=I.map(fe=>`${fe.threadId}:${fe.updatedAt??""}:${fe.messageCount??""}`).join("|");if(I.length===0){try{oa(w)}catch{}xt.current="";return}if(W===xt.current)return;const K=()=>{try{const fe=I.slice(0,aa);ca(w,fe),xt.current=W}catch{}finally{Le.current=null}};if(A!=null&&A.immediate){K();return}Le.current=window.setTimeout(()=>{ru(K)},ds)},[w]),Ge=b.useCallback(()=>{Ce(S,{immediate:!0})},[Ce,S]),qe=b.useCallback((I,A,W,K)=>{var Ul;const fe=W??Se.current;if(!fe)return;const le=un(I),ht=fe===Se.current,bt=(K==null?void 0:K.persist)!==!1;if(A==="replace"){if(bt){const Vt={threadId:fe,snapshot:un(I,{cloneMessages:!0})};Ke.current.set(fe,Vt),tt.current=fe}if(!ht)return;re(le.messages,{checkpointId:le.checkpointId??null,checkpointNs:le.checkpointNs??null,pendingInterrupt:le.interrupt??null}),$(le.interrupt??null),ue(le.nextCursor??null),Q(!!le.nextCursor),te(le.checkpointId??void 0),q(le.checkpointNs??void 0),ce(le.nextCursorNs??void 0);return}const Be=Ke.current.get(fe),kt=(Be==null?void 0:Be.snapshot)??null,Ht=Array.isArray(kt==null?void 0:kt.messages)?kt.messages:[],pn=un(kt),Jn=Array.isArray(I==null?void 0:I.messages)?I.messages:[],Wt=new Set,jt=[...Jn,...Ht].filter(Vt=>{const Wl=Vt==null?void 0:Vt.id;return Wl?Wt.has(Wl)?!1:(Wt.add(Wl),!0):!0}),or=iu(pn,le),$r={checkpointId:pn.checkpointId??le.checkpointId??null,checkpointNs:pn.checkpointNs??le.checkpointNs??null,createdAt:le.createdAt??pn.createdAt??null,parentId:le.parentId??pn.parentId??null,branchLabel:le.branchLabel??pn.branchLabel??null,lastMessageId:((Ul=jt[jt.length-1])==null?void 0:Ul.id)??null,messagesLen:jt.length,hasMessages:jt.length>0,messages:jt,nextCursor:le.nextCursor??pn.nextCursor??null,nextCursorNs:le.nextCursorNs??pn.nextCursorNs??null,interrupt:pn.interrupt??le.interrupt??null,...or};if(Ke.current.set(fe,{threadId:fe,snapshot:un($r,{cloneMessages:!0})}),!ht)return;Jn.length&&xe(Jn);const lo=I&&Object.prototype.hasOwnProperty.call(I,"checkpointId")?I.checkpointId:void 0,An=I&&Object.prototype.hasOwnProperty.call(I,"checkpointNs")?I.checkpointNs:void 0,zr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursor")?I.nextCursor:void 0,xr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursorNs")?I.nextCursorNs:void 0;ue(Vt=>zr!==void 0?zr??Vt??null:Vt??null),Q(Vt=>zr!==void 0?!!zr:Vt),te(Vt=>lo!==void 0?lo??Vt??void 0:Vt??void 0),q(Vt=>An!==void 0?An??Vt??void 0:Vt??void 0),ce(Vt=>xr!==void 0?xr??void 0:Vt)},[xe,re,$]),He=b.useCallback(I=>{if(I.threadId!=null&&I.threadId!==Se.current)return;const A=un(I.snapshot,{cloneMessages:!0});re(A.messages,{checkpointId:A.checkpointId??null,checkpointNs:A.checkpointNs??null,pendingInterrupt:A.interrupt??null}),$(A.interrupt??null),ue(A.nextCursor??null),Q(!!A.nextCursor),te(A.checkpointId??void 0),q(A.checkpointNs??void 0),ce(A.nextCursorNs??void 0),tt.current=I.threadId,st(I.threadId??Se.current??null)},[re,$,st]),Re=b.useCallback(I=>{if(!I)return;Ke.current.delete(I),y(I),Jt(I);const A=`${I}__`;for(const W of nt.current.keys())W.startsWith(A)&&nt.current.delete(W);for(const W of yt.current.keys())W.startsWith(A)&&yt.current.delete(W);tt.current===I&&(tt.current=null)},[Jt,y]),At=b.useCallback(()=>{const I=Se.current;I&&Re(I),rt([]),Q(!1),je(!1),ue(null),te(void 0),q(void 0),ce(void 0)},[Re,rt]),gt=b.useCallback(({from:I,to:A})=>{const W=Se.current;W&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${I} -> ${A}) for thread ${W}`)},[]),Ct=b.useCallback(I=>{const A=I.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:A,title:I.title,created:I.created,currentThreads:S.length});const W={threadId:A,title:I.title||`Thread ${A.slice(0,8)}`,createdAt:I.createdAt||new Date().toISOString(),updatedAt:I.updatedAt||new Date().toISOString(),messageCount:I.messageCount||0};Se.current!==A&&(!Se.current&&U.messages.length<=1&&(Xe.current=A),j(A)),b.startTransition(()=>{k(K=>{const fe=K.byId[A];return fe?fe.title===W.title&&fe.updatedAt===W.updatedAt&&fe.messageCount===W.messageCount?K:{byId:{...K.byId,[A]:W},order:K.order}:{byId:{...K.byId,[A]:W},order:[A,...K.order]}})})},[U.messages.length]),{startStream:Zt,stop:Fn,isStreaming:hn,error:zt,setAuthToken:$n,replayBufferedEvents:Z}=Zy({baseUrl:f,onThreadInfo:Ct,onMessageEvent:$e,onUnhandledEvent:I=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${I.type}`,I)},onSequenceGap:gt,onStreamClosed:I=>{Lr.current(I)},onConnectionError:I=>{Fr.current(I)},onAuthError:a,onHeartbeat:I=>{N.current(I)}}),se=b.useCallback(()=>{const I=fn.current;I.timer!==null&&(window.clearTimeout(I.timer),I.timer=null),I.reason=null},[]),de=b.useCallback((I,A)=>{Dt("connecting"),Zt(I,{onOpen:W=>{var K;se(),fn.current.attempts=0,Dt("connected"),(K=A==null?void 0:A.onOpen)==null||K.call(A,W)},onError:W=>{var K;(K=A==null?void 0:A.onError)==null||K.call(A,W)},onGap:(A==null?void 0:A.onGap)??gt,onConnectionError:W=>{var K;Fr.current(W),(K=A==null?void 0:A.onConnectionError)==null||K.call(A,W)},onHeartbeat:W=>{var K;N.current(W),(K=A==null?void 0:A.onHeartbeat)==null||K.call(A,W)},onClosed:W=>{var K;Lr.current(W),(K=A==null?void 0:A.onClosed)==null||K.call(A,W)}})},[se,gt,Dt,Zt]),Ie=b.useCallback(()=>{const I=Se.current;if(!I)return null;const A=io.current,W=U.lastCheckpointId??(A==null?void 0:A.lastCheckpointId)??null,K=U.lastCheckpointNs??(A==null?void 0:A.lastCheckpointNs)??null,fe={};return W&&(fe.checkpointId=W),K&&(fe.checkpointNs=K),{threadId:I,checkpointId:W,checkpointNs:K,command:{kind:"resume",value:fe}}},[U.lastCheckpointId,U.lastCheckpointNs]),lt=b.useCallback(I=>{const A=fn.current;if(A.timer!==null)return;if(A.attempts>=ex){Dt("error");return}A.attempts+=1,A.reason=I;const W=Math.min(tx*Math.pow(2,A.attempts-1),nx);Dt("reconnecting"),A.timer=window.setTimeout(()=>{A.timer=null,A.reason=null;const K=Ie();if(!K){Dt("error");return}Z(K.threadId??void 0),de(K)},W)},[Ie,Z,Dt,de]),Je=b.useCallback(I=>{var A;if(io.current=I,I.manualStop||I.reason==="complete"){se(),fn.current.attempts=0,Dt("idle");return}if(I.error&&(I.error.includes("token")||I.error.includes("401")||I.error.includes("unauthorized")||I.error.includes("Unauthorized")||I.error.includes("TOKEN_EXPIRED")||I.error.includes("auth_error"))){console.error("[ChatSessionProvider] Auth error detected:",I.error);try{a==null||a(I.error)}catch(K){console.error("[ChatSessionProvider] Error in onAuthError handler:",K)}return}if(I.reason==="error"||I.reason==="aborted"){if((A=I.error)!=null&&A.includes("Stream idle timeout")){console.warn("[ChatSessionProvider] Idle timeout - not scheduling resume (watchdog is generous)");return}lt(`closed:${I.reason}`)}},[se,lt,Dt,a]),it=b.useCallback(I=>{console.warn("[ChatSessionProvider] Stream connection error:",I),lt("connection-error")},[lt]),Bt=b.useCallback(I=>{ao.current=Date.now(),Dt(A=>A==="reconnecting"?"connected":A)},[Dt]);Lr.current=Je,Fr.current=it,N.current=Bt,b.useEffect(()=>()=>{se()},[se]);const sn=b.useCallback(()=>{se(),fn.current.attempts=0,Dt("idle"),Fn()},[se,Dt,Fn]);b.useEffect(()=>{Me.current=hn},[hn]),b.useEffect(()=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const I=S.map(W=>`${W.threadId}:${W.updatedAt??""}:${W.messageCount??""}`).join("|");if(S.length===0){try{oa(w)}catch{}xt.current="";return}if(I===xt.current)return;const A=()=>{try{const W=S.slice(0,aa);ca(w,W),xt.current=I}catch{}finally{Le.current=null}};return Le.current=window.setTimeout(()=>{ru(A),Le.current=null},ds),()=>{Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)}},[S,Ce]),b.useEffect(()=>{var K;const I=c.getAuthToken();$n(I);const A=fe=>{const le=la(h,fe);St.current!==le&&(St.current=le,Ot.current=!1),C(le);const ht=ua(le);b.startTransition(()=>{k(hs(ht))}),fe&&!Ot.current&&(Ot.current=!0)};A(I);const W=(K=c.onTokenChange)==null?void 0:K.call(c,fe=>{fe!==I&&($n(fe),x(),nt.current.clear(),yt.current.clear(),A(fe))});return()=>{W==null||W()}},[c,h,$n,x]);const Xn=b.useCallback(async I=>{var K;const A=`Thread ${(K=crypto.randomUUID)==null?void 0:K.call(crypto)}`,W={threadId:A,title:I||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};k(fe=>({byId:{...fe.byId,[A]:W},order:[A,...fe.order]})),j(A);try{const fe=await c.createThread(I),le=typeof fe=="string"?fe:fe.threadId;return k(ht=>{const bt=ht.byId[A];if(!bt)return ht;const Be={...ht.byId};delete Be[A],Be[le]={...bt,threadId:le};const kt=ht.order.map(Ht=>Ht===A?le:Ht);return{byId:Be,order:kt}}),j(le),setTimeout(()=>ct(),10),O(null),le}catch(fe){throw k(le=>{if(!le.byId[A])return le;const ht={...le.byId};delete ht[A];const bt=le.order.filter(Be=>Be!==A);return{byId:ht,order:bt}}),j(null),O(String(fe)),fe}},[c,ct]),Ko=b.useCallback(async I=>{try{await c.deleteThread(I);let A=null;k(W=>{if(!W.byId[I])return W;const K={...W.byId};delete K[I];const fe=W.order.filter(ht=>ht!==I),le={byId:K,order:fe};return A=da(le),le}),A&&Ce(A,{immediate:!0}),Re(I),Se.current===I&&(Xe.current=I,j(null),Se.current=null,tt.current=null,At()),await ct(),O(null)}catch(A){throw O(String(A)),A}},[c,At,Re,ct,Ce]),_i=b.useCallback(async(I,A)=>{try{await c.updateThread(I,A),k(W=>{const K=W.byId[I];return K?{byId:{...W.byId,[I]:{...K,title:A}},order:W.order}:W}),O(null)}catch(W){throw await ct(),O(String(W)),W}},[c,ct]),Nn=b.useCallback(async(I,A,W,K=!1)=>{await ve(async()=>{if(Xe.current===I&&!K){Xe.current=null;return}if(et.current===I&&!K)return;j(Wt=>Wt===I?Wt:I),Se.current=I;const ht=su(I,A??null,W??null),bt=yt.current.get(ht),Be=!K&&!A&&!W&&bt&&Date.now()-bt.timestamp<Qy,kt=!K&&!A&&!W;let Ht=!1;if(kt){const Wt=Ke.current.get(I);if(Wt)He(Wt),Ht=!0;else{const jt=m(I);jt&&(Ke.current.set(I,jt),He(jt),Ht=!0)}}const pn=K||!Ht||!!A||!!W,Jn=async Wt=>{Wt&&z(!0),et.current=I;try{const jt=await Te({threadId:I,checkpointId:A,checkpointNs:W},{force:K}),{latest:or,checkpoints:$r,snapshots:lo}=as(jt.payload);qe(or,"replace",I),Gt(I,$r,"replace"),Yt(I,lo,"replace"),R(null),jt.usedHistoryApi||ae(I).then(An=>{Xt(I,An)}).catch(An=>{console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries:",An)})}catch(jt){if(Y(jt))try{const or=await ae(I),$r=Xt(I,or);if(Q(!1),ue(null),ce(void 0),te(void 0),q(void 0),$r){R("History request timed out. Select a checkpoint to load manually.");return}}catch(or){console.warn("[ChatSessionProvider] Failed to fetch checkpoint summaries after timeout:",or)}throw(!Ht||K||Wt)&&(i==null||i(String(jt))),R(String(jt)),jt}finally{et.current=null,Wt&&z(!1)}};pn?await Jn(!0):kt&&Ht&&!Be&&Jn(!1).catch(Wt=>{console.warn("[ChatSessionProvider] Background refresh failed:",Wt)})},`loadThread-${I}`)},[He,Xt,qe,ve,ae,Te,Y,i,Gt,Yt]),ji=b.useCallback(async()=>{await ve(async()=>{const I=Se.current;I&&Re(I),Xe.current=null,j(null),Se.current=null,tt.current=null,At(),te(void 0),q(void 0),ce(void 0),ft();try{localStorage.removeItem("lastThreadId")}catch(A){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",A)}},"clearCurrentThread")},[At,Re,ve,ft]),Um=b.useCallback(async(I,A)=>{const W=Se.current;if(!W)throw new Error("No active thread");const K=Wr(I,A??null),fe=Mt(W,K);if(fe){await ve(async()=>{qe(fe,"replace",W,{persist:!1})},`navigateToCheckpoint-${W}-${K}`);return}await Nn(W,I,A??void 0,!0)},[qe,ve,Mt,Nn]),Wm=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");await Nn(Se.current,void 0,void 0,!0)},[Nn]),Vm=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");if(ye||!ne)return;const I=J;if(I){je(!0);try{const A=Se.current,W=await Te({threadId:A,checkpointId:I??ke??null,checkpointNs:ie??L??null}),{latest:K,checkpoints:fe,snapshots:le}=as(W.payload),ht=Ve(A);let bt=fe.length>0;if(bt&&ht&&ht.size>0&&(bt=fe.some(Be=>{if(!(Be!=null&&Be.checkpointId))return!1;const kt=Wr(Be.checkpointId,Be.checkpointNs??null);return!ht.has(kt)})),!bt){ue(null),ce(void 0),Q(!1),R(null);return}if(qe(K,"prepend",A??void 0),A&&(Gt(A,fe,"prepend"),Yt(A,le,"prepend"),!W.usedHistoryApi))try{const Be=await ae(A);Xt(A,Be)}catch(Be){console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries during prepend:",Be)}R(null)}catch(A){throw R(String(A)),A}finally{je(!1)}}},[qe,Te,Ve,ne,ke,L,ie,J,ae,Xt,ye,Gt,Yt]),Km=b.useCallback(I=>{if(I!=null&&I.threadId){if(I.checkpointId){const A=Wr(I.checkpointId,I.checkpointNs??null),W=un({...I,interrupt:I.interrupt??null},{cloneMessages:!0});Yt(I.threadId,{[A]:W},"prepend")}qe(I,"replace",I.threadId)}},[qe,Yt]),qo=b.useCallback(async(I,A)=>{var zr;const W=Se.current,K=(I==null?void 0:I.text)??"",fe=(I==null?void 0:I.attachments)??[],le=fe.length?fe:(A==null?void 0:A.attachments)??[],ht=I==null?void 0:I.messageAdditionalKwargs,bt={...(A==null?void 0:A.payloadExtras)??{},...(I==null?void 0:I.payload)??{}};if(!W&&!Object.keys(bt).length&&le.length===0&&!K.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!W&&!bt.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:Be,filesInfo:kt}=await Iy(c,le),Ht=[...Be];K&&K.trim()&&Ht.push({type:"text",text:K.trim()});const pn=!!W,Jn=pn?(A==null?void 0:A.checkpointId)??U.lastCheckpointId??void 0:void 0,Wt=pn?(A==null?void 0:A.checkpointNs)??U.lastCheckpointNs??void 0:void 0,jt={id:((zr=crypto.randomUUID)==null?void 0:zr.call(crypto))||`user-${Date.now()}`,role:"user",content:Ht,createdAt:new Date().toISOString(),...Jn!=null?{checkpointId:Jn}:{},...Wt!=null?{checkpointNs:Wt}:{}};ht&&Object.keys(ht).length&&(jt.additionalKwargs={...jt.additionalKwargs??{},...ht}),Ht.length>0&&Pe(jt);const or={...jt,content:Ht},$r=le.length>0,lo={messages:Ht.length>0?[or]:[],files_info:kt,...o&&$r&&s?{active_agent:s}:{},...bt},An={threadId:W??null,payload:lo,checkpointId:Jn??null,checkpointNs:Wt??null,nodeFilter:(A==null?void 0:A.nodeFilter)??null,config:A==null?void 0:A.config,command:(A==null?void 0:A.command)??null};An.threadId||delete An.threadId,An.command||delete An.command,de(An,{onError:xr=>{console.warn("[ChatSessionProvider] Stream error:",xr)},onOpen:({threadId:xr})=>{!Se.current&&xr&&(U.messages.length<=1&&(Xe.current=xr),j(xr))},onGap:gt})},[c,o,s,gt,U.lastCheckpointId,U.lastCheckpointNs,U.messages.length,Pe,de]),qm=b.useCallback(async(I,A,W)=>{if(!Se.current)throw new Error("No active thread to handle interrupt");const fe=A?W??!0:!1;try{try{We({type:"interrupt_response",payload:{interruptId:I}})}catch(le){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",le)}await qo({payload:{}},{checkpointId:U.lastCheckpointId??void 0,checkpointNs:U.lastCheckpointNs??void 0,command:{kind:"resume",value:fe}}),$(null)}catch(le){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${I}:`,le),le}},[We,U.lastCheckpointId,U.lastCheckpointNs,qo]);b.useEffect(()=>{if(l==null||l(E),E)try{localStorage.setItem("lastThreadId",E)}catch(I){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",I)}},[E,l]),b.useEffect(()=>((async()=>{try{if(ct().catch(A=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",A),i==null||i(String(A))}),!r&&!t)try{const A=localStorage.getItem("lastThreadId");A&&(j(A),n&&await Nn(A))}catch(A){console.warn("[ChatSessionProvider] Failed to restore last thread:",A)}else t&&n&&await Nn(t)}catch(A){console.error("[ChatSessionProvider] Initialization failed:",A),i==null||i(String(A))}})(),()=>{}),[]),b.useEffect(()=>{const I=Se.current;if(!I||tt.current!==I)return;U.messages.length&&U.messages[U.messages.length-1];const A=un({checkpointId:U.lastCheckpointId??null,checkpointNs:U.lastCheckpointNs??null,messages:U.messages.slice(),nextCursor:J??null,nextCursorNs:ie??null,interrupt:U.pendingInterrupt??V??null}),W=Ke.current.get(I),K=W==null?void 0:W.snapshot,fe=!K||K.messages.length!==A.messages.length||K.messages.some((Be,kt)=>{var Ht;return(Be==null?void 0:Be.id)!==((Ht=A.messages[kt])==null?void 0:Ht.id)}),le=((K==null?void 0:K.checkpointId)??null)!==A.checkpointId||((K==null?void 0:K.checkpointNs)??null)!==A.checkpointNs,ht=((K==null?void 0:K.nextCursor)??null)!==A.nextCursor||((K==null?void 0:K.nextCursorNs)??null)!==A.nextCursorNs,bt=!ou((K==null?void 0:K.interrupt)??null,A.interrupt??null);if(fe||le||ht||bt){const Be={threadId:I,snapshot:A};Ke.current.set(I,Be),Ut.current&&window.clearTimeout(Ut.current),Ut.current=window.setTimeout(()=>{try{g(Be,100)}catch(kt){console.warn("[ChatSessionProvider] Failed to persist thread payload:",kt)}},ds)}},[J,ie,U.lastCheckpointId,U.lastCheckpointNs,U.messages,U.pendingInterrupt,V,g]);const hT=b.useMemo(()=>({threads:S,currentThreadId:E,setCurrentThreadId:j,isLoading:_,error:B,actions:{createThread:Xn,deleteThread:Ko,renameThread:_i,refreshThreads:()=>ct()},persistThreadsCache:Ge,hydrateFromCache:F}),[S,E,_,B,Xn,Ko,_i,ct,Ge,F,j]),pT=b.useMemo(()=>{const I=U.lastBranch??null,A=U.assemblingId??null,W=I||A?{branchLabel:(I==null?void 0:I.branchLabel)??null,lastBranch:I,assemblingMessageId:A}:null;return{threadId:E,messages:U.messages,interrupt:V,checkpoint:{id:U.lastCheckpointId??null,namespace:U.lastCheckpointNs??null},checkpoints:Nt,metadata:W,isLoading:D,isHistoryLoading:ye,error:H,hasMore:ne,loadOlder:Vm,seedFromSnapshot:Km,clearState:At,navigateToCheckpoint:Um,returnToLatest:Wm,loadThread:Nn,clearThread:ji,respondToInterrupt:qm}},[ji,At,E,V,ne,ye,D,Vm,Nn,U.assemblingId,U.lastBranch,U.lastCheckpointId,U.lastCheckpointNs,U.messages,Um,qm,Wm,Km,H,Nt]),mT=b.useMemo(()=>({isStreaming:hn,error:zt,connectionState:Ln,submit:qo,send:qo,stop:sn,setAuthToken:$n}),[Ln,hn,zt,sn,qo,$n]);return u.jsx(wx.Provider,{value:!0,children:u.jsx(uu.Provider,{value:mT,children:u.jsx(lu.Provider,{value:hT,children:u.jsx(cu.Provider,{value:pT,children:e})})})})}function ps(){const e=b.useContext(lu);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function ms(){const e=b.useContext(cu);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function du(){const e=b.useContext(uu);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function gs({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(Ty,{apiConfig:t,children:u.jsx(bx,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onAuthError:l,onThreadChange:c,children:e})})}function oe(...e){return Jm.twMerge(Xm.clsx(e))}const Sx=Go.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"}}),ut=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?vr.Slot:"button";return u.jsx(i,{className:oe(Sx({variant:t,size:n,className:e})),ref:s,...o})});ut.displayName="Button";const fu=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:oe("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",e),ref:n,...t}));fu.displayName="Textarea";function hu({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const m=i!==void 0,[g,y]=b.useState(e),x=(m?i:g)??"",[w,C]=b.useTransition(),T=b.useRef(null),k=b.useRef(0),S=b.useRef(null);b.useEffect(()=>{m||(y(e??""),S.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,m]);const E=b.useCallback(()=>{const H=T.current;H&&(H.style.height="auto",H.style.height=`${H.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,x]);const j=b.useCallback((H,{fromUser:R})=>{m||y(H),R&&(a==null||a(H))},[m,a]),_=b.useCallback(async H=>{H&&H.preventDefault();const R=(x??"").trim();if(!R&&!p)return;const V=++k.current;S.current={id:V,shouldClear:!0},C(()=>{var $,F,ne;try{const Q=l(R);Q&&typeof Q.then=="function"?Q.then(()=>{var ye,je;((ye=S.current)==null?void 0:ye.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((je=S.current)==null?void 0:je.id)===V&&(S.current=null)}).catch(()=>{var ye;((ye=S.current)==null?void 0:ye.id)===V&&(S.current=null)}):((($=S.current)==null?void 0:$.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((F=S.current)==null?void 0:F.id)===V&&(S.current=null))}catch{((ne=S.current)==null?void 0:ne.id)===V&&(S.current=null)}})},[x,l,p,m,a]),P=b.useCallback(H=>{const R=H.target.value;j(R,{fromUser:!0}),S.current&&(S.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[j]),D=b.useCallback(H=>{H.key==="Enter"&&!H.shiftKey?(H.preventDefault(),_()):H.key==="Escape"&&t&&(H.preventDefault(),c==null||c())},[_,t,c]),O=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return u.jsx("form",{onSubmit:H=>void _(H),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(fu,{ref:T,value:x,onChange:P,onKeyDown:D,placeholder:t?"Edit your message...":n,className:O,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(ut,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(he.Square,{size:16})}):u.jsx(ut,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!p||w,children:u.jsx(he.Send,{size:16})})})]})})}const Cx=b.memo(hu),ys=0,ir=1,Vr=2,pu=4;function mu(e){return()=>e}function kx(e){e()}function gu(e,t){return n=>e(t(n))}function yu(e,t){return()=>e(t)}function Tx(e,t){return n=>e(t,n)}function fa(e){return e!==void 0}function Ex(...e){return()=>{e.map(kx)}}function Kr(){}function xs(e,t){return t(e),e}function Ix(e,t){return t(e)}function Tt(...e){return e}function dt(e,t){return e(ir,t)}function ze(e,t){e(ys,t)}function ha(e){e(Vr)}function Rt(e){return e(pu)}function we(e,t){return dt(e,Tx(t,ys))}function jn(e,t){const n=e(ir,r=>{n(),t(r)});return n}function xu(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function vu(e,t){return e===t}function Et(e=vu){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function _e(e){return t=>n=>{e(n)&&t(n)}}function pe(e){return t=>gu(t,e)}function Bn(e){return t=>()=>{t(e)}}function X(e,...t){const n=Nx(...t);return(r,o)=>{switch(r){case Vr:ha(e);return;case ir:return dt(e,n(o))}}}function Hn(e,t){return n=>r=>{n(t=e(t,r))}}function kr(e){return t=>n=>{e>0?e--:t(n)}}function Qn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Ue(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);dt(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function Nx(...e){return t=>e.reduceRight(Ix,t)}function Ax(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case ir:return s?n===s?void 0:(r(),n=s,t=dt(e,s),t):(r(),Kr);case Vr:r(),n=null;return}}}function ee(e){let t=e;const n=Ze();return(r,o)=>{switch(r){case ys:t=o;break;case ir:{o(t);break}case pu:return t}return n(r,o)}}function en(e,t){return xs(ee(t),n=>we(e,n))}function Ze(){const e=[];return(t,n)=>{switch(t){case ys:e.slice().forEach(r=>{r(n)});return;case Vr:e.splice(0,e.length);return;case ir:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function mn(e){return xs(Ze(),t=>we(e,t))}function at(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:_x(),singleton:n}}const _x=()=>Symbol();function jx(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(l=>n(l)));return i&&t.set(s,a),a};return n(e)}function Ft(...e){const t=Ze(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);dt(s,l=>{n[i]=l,r=r|a,r===o&&ze(t,n)})}),function(s,i){switch(s){case Vr:{ha(t);return}case ir:return r===o&&i(n),dt(t,i)}}}function Ne(e,t=vu){return X(e,Et(t))}function pa(...e){return function(t,n){switch(t){case Vr:return;case ir:return Ex(...e.map(r=>dt(r,n)))}}}var dn=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(dn||{});const Px={0:"debug",3:"error",1:"log",2:"warn"},Rx=()=>typeof globalThis>"u"?window:globalThis,ar=at(()=>{const e=ee(3);return{log:ee((t,n,r=1)=>{var o;const s=(o=Rx().VIRTUOSO_LOG_LEVEL)!=null?o:Rt(e);r>=s&&console[Px[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function Tr(e,t,n){return ma(e,t,n).callbackRef}function ma(e,t,n){const r=b.useRef(null);let o=i=>{};const s=b.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const l=i[0].target;l.offsetParent!==null&&e(l)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function Ox(e,t,n,r,o,s,i,a,l){const c=b.useCallback(d=>{const f=Mx(d.children,t,a?"offsetWidth":"offsetHeight",o);let h=d.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const p=h.lastElementChild.dataset.viewportType==="window";let m;p&&(m=h.ownerDocument.defaultView);const g=i?a?i.scrollLeft:i.scrollTop:p?a?m.scrollX||m.document.documentElement.scrollLeft:m.scrollY||m.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,y=i?a?i.scrollWidth:i.scrollHeight:p?a?m.document.documentElement.scrollWidth:m.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,x=i?a?i.offsetWidth:i.offsetHeight:p?a?m.innerWidth:m.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:y,scrollTop:Math.max(g,0),viewportHeight:x}),s==null||s(a?wu("column-gap",getComputedStyle(d).columnGap,o):wu("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return ma(c,n,l)}function Mx(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},dn.ERROR),d===c)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function wu(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,dn.WARN),t==="normal"?0:parseInt(t??"0",10)}function bu(e,t,n){const r=b.useRef(null),o=b.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,h;if(t){const p=t.getBoundingClientRect(),m=c.top-p.top;h=p.height-Math.max(0,m),f=m+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,c.top),f=c.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=ma(o,!0,n),a=b.useCallback(()=>{o(i.current)},[o,i]);return b.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const rn=at(()=>{const e=Ze(),t=Ze(),n=ee(0),r=Ze(),o=ee(0),s=Ze(),i=Ze(),a=ee(0),l=ee(0),c=ee(0),d=ee(0),f=Ze(),h=Ze(),p=ee(!1),m=ee(!1),g=ee(!1);return we(X(e,pe(({scrollTop:y})=>y)),t),we(X(e,pe(({scrollHeight:y})=>y)),i),we(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:m,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:g,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),xo={lvl:0};function Su(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:l}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=l}return s.push({end:1/0,start:r,value:o}),s}function vt(e){return e===xo}function vo(e,t){if(!vt(e))return t===e.k?e.v:t<e.k?vo(e.l,t):vo(e.r,t)}function Pn(e,t,n="k"){if(vt(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=Pn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return Pn(e.l,t,n)}function gn(e,t,n){return vt(e)?Tu(t,n,1):t===e.k?$t(e,{k:t,v:n}):t<e.k?Eu($t(e,{l:gn(e.l,t,n)})):Eu($t(e,{r:gn(e.r,t,n)}))}function qr(){return xo}function vs(e,t,n){if(vt(e))return[];const r=Pn(e,t)[0];return Dx(ya(e,r,n))}function ga(e,t){if(vt(e))return xo;const{k:n,l:r,r:o}=e;if(t===n){if(vt(r))return o;if(vt(o))return r;{const[s,i]=ku(r);return ws($t(e,{k:s,l:Cu(r),v:i}))}}else return t<n?ws($t(e,{l:ga(r,t)})):ws($t(e,{r:ga(o,t)}))}function Er(e){return vt(e)?[]:[...Er(e.l),{k:e.k,v:e.v},...Er(e.r)]}function ya(e,t,n){if(vt(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(ya(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(ya(s,t,n))),a}function ws(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(xa(t))return Iu($t(e,{lvl:n-1}));if(!vt(t)&&!vt(t.r))return $t(t.r,{l:$t(t,{r:t.r.l}),lvl:n,r:$t(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(xa(e))return va($t(e,{lvl:n-1}));if(!vt(r)&&!vt(r.l)){const o=r.l,s=xa(o)?r.lvl-1:r.lvl;return $t(o,{l:$t(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:va($t(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function $t(e,t){return Tu(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function Cu(e){return vt(e.r)?e.l:ws($t(e,{r:Cu(e.r)}))}function xa(e){return vt(e)||e.lvl>e.r.lvl}function ku(e){return vt(e.r)?[e.k,e.v]:ku(e.r)}function Tu(e,t,n,r=xo,o=xo){return{k:e,l:r,lvl:n,r:o,v:t}}function Eu(e){return va(Iu(e))}function Iu(e){const{l:t}=e;return!vt(t)&&t.lvl===e.lvl?$t(t,{r:$t(e,{l:t.r})}):e}function va(e){const{lvl:t,r:n}=e;return!vt(n)&&!vt(n.r)&&n.lvl===t&&n.r.lvl===t?$t(n,{l:$t(e,{r:n.l}),lvl:t+1}):e}function Dx(e){return Su(e,({k:t,v:n})=>({index:t,value:n}))}function Nu(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function wo(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const wa=at(()=>({recalcInProgress:ee(!1)}),[],{singleton:!0});function Au(e,t,n){return e[bs(e,t,n)]}function bs(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function Lx(e,t,n,r){const o=bs(e,t,r),s=bs(e,n,r,o);return e.slice(o,s+1)}function lr(e,t){return Math.round(e.getBoundingClientRect()[t])}function Ss(e){return!vt(e.groupOffsetTree)}function ba({index:e},t){return t===e?0:t<e?-1:1}function Fx(){return{groupIndices:[],groupOffsetTree:qr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:qr()}}function $x(e,t){let n=vt(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),vt(e)){e=gn(e,0,s);continue}const a=vs(e,i-1,o+1);if(a.some(Kx(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=ga(e,f)):(c=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=gn(e,o+1,h));c&&(e=gn(e,i,s))}return[e,n]}function zx(e){return typeof e.groupIndex<"u"}function Bx({offset:e},t){return t===e?0:t<e?-1:1}function bo(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Au(t,e,ba),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function _u(e,t){if(!Ss(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function ju(e,t,n){if(zx(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=_u(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function Hx(e,t,n,r=0){return r>0&&(t=Math.max(t,Au(e,r,ba).offset)),Su(Lx(e,t,n,Bx),Vx)}function Ux(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,dn.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&vt(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((m,g)=>gn(gn(m,g,h),g+1,p),i)}else[i,a]=$x(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=Sa(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>gn(h,p,bo(p,f,o)),qr()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function Wx(e){return Er(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function Pu(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function Sa(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=bs(o,t-1,ba),a=o[l].offset;const c=Pn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===Pn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of vs(n,t,1/0)){const f=c-s,h=f*i+a+f*r;o.push({index:c,offset:h,size:d}),s=c,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function Vx(e){return{index:e.index,value:e}}function Kx(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const qx={offsetHeight:"height",offsetWidth:"width"},Un=at(([{log:e},{recalcInProgress:t}])=>{const n=Ze(),r=Ze(),o=en(r,0),s=Ze(),i=Ze(),a=ee(0),l=ee([]),c=ee(void 0),d=ee(void 0),f=ee((k,S)=>lr(k,qx[S])),h=ee(void 0),p=ee(0),m=Fx(),g=en(X(n,Ue(l,e,p),Hn(Ux,m),Et()),m),y=en(X(l,Et(),Hn((k,S)=>({current:S,prev:k.current}),{current:[],prev:[]}),pe(({prev:k})=>k)),[]);we(X(l,_e(k=>k.length>0),Ue(g,p),pe(([k,S,E])=>{const j=k.reduce((_,P,D)=>gn(_,P,bo(P,S.offsetTree,E)||D),qr());return{...S,groupIndices:k,groupOffsetTree:j}})),g),we(X(r,Ue(g),_e(([k,{lastIndex:S}])=>k<S),pe(([k,{lastIndex:S,lastSize:E}])=>[{endIndex:S,size:E,startIndex:k}])),n),we(c,d);const x=en(X(c,pe(k=>k===void 0)),!0);we(X(d,_e(k=>k!==void 0&&vt(Rt(g).sizeTree)),pe(k=>[{endIndex:0,size:k,startIndex:0}])),n);const w=mn(X(n,Ue(g),Hn(({sizes:k},[S,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:m}),pe(k=>k.changed)));dt(X(a,Hn((k,S)=>({diff:k.prev-S,prev:S}),{diff:0,prev:0}),pe(k=>k.diff)),k=>{const{groupIndices:S}=Rt(g);if(k>0)ze(t,!0),ze(s,k+Pu(k,S));else if(k<0){const E=Rt(y);E.length>0&&(k-=Pu(-k,E)),ze(i,k)}}),dt(X(a,Ue(e)),([k,S])=>{k<0&&S("`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:a},dn.ERROR)});const C=mn(s);we(X(s,Ue(g),pe(([k,S])=>{const E=S.groupIndices.length>0,j=[],_=S.lastSize;if(E){const P=vo(S.sizeTree,0);let D=0,z=0;for(;D<k;){const O=S.groupIndices[z],H=S.groupIndices.length===z+1?1/0:S.groupIndices[z+1]-O-1;j.push({endIndex:O,size:P,startIndex:O}),j.push({endIndex:O+1+H-1,size:_,startIndex:O+1}),z++,D+=H+1}const B=Er(S.sizeTree);return D!==k&&B.shift(),B.reduce((O,{k:H,v:R})=>{let V=O.ranges;return O.prevSize!==0&&(V=[...O.ranges,{endIndex:H+k-1,size:O.prevSize,startIndex:O.prevIndex}]),{prevIndex:H+k,prevSize:R,ranges:V}},{prevIndex:k,prevSize:0,ranges:j}).ranges}return Er(S.sizeTree).reduce((P,{k:D,v:z})=>({prevIndex:D+k,prevSize:z,ranges:[...P.ranges,{endIndex:D+k-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const T=mn(X(i,Ue(g,p),pe(([k,{offsetTree:S},E])=>{const j=-k;return bo(j,S,E)})));return we(X(i,Ue(g,p),pe(([k,S,E])=>{if(S.groupIndices.length>0){if(vt(S.sizeTree))return S;let j=qr();const _=Rt(y);let P=0,D=0,z=0;for(;P<-k;){z=_[D];const B=_[D+1]-z-1;D++,P+=B+1}if(j=Er(S.sizeTree).reduce((B,{k:O,v:H})=>gn(B,Math.max(0,O+k),H),j),P!==-k){const B=vo(S.sizeTree,z);j=gn(j,0,B);const O=Pn(S.sizeTree,-k+1)[1];j=gn(j,1,O)}return{...S,sizeTree:j,...Sa(S.offsetTree,0,j,E)}}else{const j=Er(S.sizeTree).reduce((_,{k:P,v:D})=>gn(_,Math.max(0,P+k),D),qr());return{...S,sizeTree:j,...Sa(S.offsetTree,0,j,E)}}})),g),{beforeUnshiftWith:C,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:p,groupIndices:l,itemSize:f,listRefresh:w,shiftWith:i,shiftWithOffset:T,sizeRanges:n,sizes:g,statefulTotalCount:o,totalCount:r,trackItemSizes:x,unshiftWith:s}},Tt(ar,wa),{singleton:!0});function Gx(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Ru=at(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Ze(),i=Ze(),a=mn(X(s,pe(Gx)));return we(X(a,pe(l=>l.totalCount)),n),we(X(a,pe(l=>l.groupIndices)),e),we(X(Ft(o,t,r),_e(([l,c])=>Ss(c)),pe(([l,c,d])=>Pn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),Et(),pe(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},Tt(Un,rn)),cr=at(([{log:e}])=>{const t=ee(!1),n=mn(X(t,_e(r=>r),Et()));return dt(t,r=>{r&&Rt(e)("props updated",{},dn.DEBUG)}),{didMount:n,propsReady:t}},Tt(ar),{singleton:!0}),Yx=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Ou(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Yx)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const So=at(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=Ze(),m=Ze(),g=ee(0);let y=null,x=null,w=null;function C(){y&&(y(),y=null),w&&(w(),w=null),x&&(clearTimeout(x),x=null),ze(l,!1)}return we(X(p,Ue(n,f,r,g,a,i,h),Ue(e,s,o),pe(([[T,k,S,E,j,_,P,D],z,B,O])=>{const H=Ou(T),{align:R,behavior:V,offset:$}=H,F=E-1,ne=ju(H,k,F);let Q=bo(ne,k.offsetTree,z)+_;R==="end"?(Q+=B+Pn(k.sizeTree,ne)[1]-S+O,ne===F&&(Q+=P)):R==="center"?Q+=(B+Pn(k.sizeTree,ne)[1]-S+O)/2:Q-=j,$&&(Q+=$);const ye=je=>{C(),je?(D("retrying to scroll to",{location:T},dn.DEBUG),ze(p,T)):(ze(m,!0),D("list did not change, scroll successful",{},dn.DEBUG))};if(C(),V==="smooth"){let je=!1;w=dt(t,J=>{je=je||J}),y=jn(d,()=>{ye(je)})}else y=jn(X(t,Xx(150)),ye);return x=setTimeout(()=>{C()},1200),ze(l,!0),D("scrolling from index to",{behavior:V,index:ne,top:Q},dn.DEBUG),{behavior:V,top:Q}})),c),{scrollTargetReached:m,scrollToIndex:p,topListHeight:g}},Tt(Un,rn,ar),{singleton:!0});function Xx(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function Ca(e,t){e==0?t():requestAnimationFrame(()=>{Ca(e-1,t)})}function ka(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const Co=at(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=ee(!0),l=ee(0),c=ee(!0);return we(X(i,Ue(l),_e(([d,f])=>!!f),Bn(!1)),a),we(X(i,Ue(l),_e(([d,f])=>!!f),Bn(!1)),c),dt(X(Ft(t,i),Ue(a,n,e,c),_e(([[,d],f,{sizeTree:h},p,m])=>d&&(!vt(h)||fa(p))&&!f&&!m),Ue(l)),([,d])=>{jn(o,()=>{ze(c,!0)}),Ca(4,()=>{jn(r,()=>{ze(a,!0)}),ze(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},Tt(Un,rn,So,cr),{singleton:!0});function Mu(e,t){return Math.abs(e-t)<1.01}const ko="up",To="down",Jx="none",Zx={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Qx=0,Eo=at(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=ee(!1),a=ee(!0),l=Ze(),c=Ze(),d=ee(4),f=ee(Qx),h=en(X(pa(X(Ne(o),kr(1),Bn(!0)),X(Ne(o),kr(1),Bn(!1),xu(100))),Et()),!1),p=en(X(pa(X(n,Bn(!0)),X(n,Bn(!1),xu(200))),Et()),!1);we(X(Ft(Ne(o),Ne(f)),pe(([w,C])=>w<=C),Et()),a),we(X(a,Qn(50)),c);const m=mn(X(Ft(r,Ne(s),Ne(t),Ne(e),Ne(d)),Hn((w,[{scrollHeight:C,scrollTop:T},k,S,E,j])=>{const _=T+k-C>-j,P={scrollHeight:C,scrollTop:T,viewportHeight:k};if(_){let z,B;return T>w.state.scrollTop?(z="SCROLLED_DOWN",B=w.state.scrollTop-T):(z="SIZE_DECREASED",B=w.state.scrollTop-T||w.scrollTopDelta),{atBottom:!0,atBottomBecause:z,scrollTopDelta:B,state:P}}let D;return P.scrollHeight>w.state.scrollHeight?D="SIZE_INCREASED":k<w.state.viewportHeight?D="VIEWPORT_HEIGHT_DECREASING":T<w.state.scrollTop?D="SCROLLING_UPWARDS":D="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:D,state:P}},Zx),Et((w,C)=>w&&w.atBottom===C.atBottom))),g=en(X(r,Hn((w,{scrollHeight:C,scrollTop:T,viewportHeight:k})=>{if(Mu(w.scrollHeight,C))return{changed:!1,jump:0,scrollHeight:C,scrollTop:T};{const S=C-(T+k)<1;return w.scrollTop!==T&&S?{changed:!0,jump:w.scrollTop-T,scrollHeight:C,scrollTop:T}:{changed:!0,jump:0,scrollHeight:C,scrollTop:T}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),_e(w=>w.changed),pe(w=>w.jump)),0);we(X(m,pe(w=>w.atBottom)),i),we(X(i,Qn(50)),l);const y=ee(To);we(X(r,pe(({scrollTop:w})=>w),Et(),Hn((w,C)=>Rt(p)?{direction:w.direction,prevScrollTop:C}:{direction:C<w.prevScrollTop?ko:To,prevScrollTop:C},{direction:To,prevScrollTop:0}),pe(w=>w.direction)),y),we(X(r,Qn(50),Bn(Jx)),y);const x=ee(0);return we(X(h,_e(w=>!w),Bn(0)),x),we(X(o,Qn(100),Ue(h),_e(([w,C])=>!!C),Hn(([w,C],[T])=>[C,T],[0,0]),pe(([w,C])=>C-w)),x),{atBottomState:m,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:g,scrollDirection:y,scrollVelocity:x}},Tt(rn)),Cs="top",ks="bottom",Du="none";function Lu(e,t,n){return typeof e=="number"?n===ko&&t===Cs||n===To&&t===ks?e:0:n===ko?t===Cs?e.main:e.reverse:t===ks?e.main:e.reverse}function Fu(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const Ta=at(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Ze(),i=ee(0),a=ee(0),l=ee(0),c=en(X(Ft(Ne(r),Ne(o),Ne(n),Ne(s,wo),Ne(l),Ne(i),Ne(t),Ne(e),Ne(a)),pe(([d,f,h,[p,m],g,y,x,w,C])=>{const T=d-w,k=y+x,S=Math.max(h-T,0);let E=Du;const j=Fu(C,Cs),_=Fu(C,ks);return p-=w,p+=h+x,m+=h+x,m-=w,p>d+k-j&&(E=ko),m<d-S+f+_&&(E=To),E!==Du?[Math.max(T-h-Lu(g,Cs,E)-j,0),T-S-x+f+Lu(g,ks,E)+_]:null}),_e(d=>d!=null),Et(wo)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},Tt(rn),{singleton:!0});function ev(e,t,n){if(Ss(t)){const r=_u(e,t);return[{index:Pn(t.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:e,offset:0,size:0}]}const Ea={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Ts(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const g=e[e.length-1];d=g.offset+g.size}const f=n-i,h=a+f*l+(f-1)*r,p=c,m=h-d;return{bottom:d,firstItemIndex:s,items:zu(e,o,s),offsetBottom:m,offsetTop:c,top:p,topItems:zu(t,o,s),topListHeight:t.reduce((g,y)=>y.size+g,0),totalCount:n}}function $u(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-i>=e)break;i++}const a=e+i,l=ka(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return Ts(c,[],a,o,n,r)}function zu(e,t,n){if(e.length===0)return[];if(!Ss(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=vs(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const Ir=at(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:m}])=>{const g=ee([]),y=ee(0),x=Ze();we(s.topItemsIndexes,g);const w=en(X(Ft(p,m,Ne(l,wo),Ne(o),Ne(r),Ne(c),d,Ne(g),Ne(t),Ne(n),e),_e(([S,E,,j,,,,,,,_])=>{const P=_&&_.length!==j;return S&&!E&&!P}),pe(([,,[S,E],j,_,P,D,z,B,O,H])=>{const R=_,{offsetTree:V,sizeTree:$}=R,F=Rt(y);if(j===0)return{...Ea,totalCount:j};if(S===0&&E===0)return F===0?{...Ea,totalCount:j}:$u(F,P,_,B,O,H||[]);if(vt($))return F>0?null:Ts(ev(ka(P,j),R,H),[],j,O,R,B);const ne=[];if(z.length>0){const ue=z[0],ke=z[z.length-1];let te=0;for(const L of vs($,ue,ke)){const q=L.value,ie=Math.max(L.start,ue),ce=Math.min(L.end,ke);for(let U=ie;U<=ce;U++)ne.push({data:H==null?void 0:H[U],index:U,offset:te,size:q}),te+=q}}if(!D)return Ts([],ne,j,O,R,B);const Q=z.length>0?z[z.length-1]+1:0,ye=Hx(V,S,E,Q);if(ye.length===0)return null;const je=j-1,J=xs([],ue=>{for(const ke of ye){const te=ke.value;let L=te.offset,q=ke.start;const ie=te.size;if(te.offset<S){q+=Math.floor((S-te.offset+O)/(ie+O));const U=q-ke.start;L+=U*ie+U*O}q<Q&&(L+=(Q-q)*ie,q=Q);const ce=Math.min(ke.end,je);for(let U=q;U<=ce&&!(L>=E);U++)ue.push({data:H==null?void 0:H[U],index:U,offset:L,size:ie}),L+=ie+O}});return Ts(J,ne,j,O,R,B)}),_e(S=>S!==null),Et()),Ea);we(X(e,_e(fa),pe(S=>S==null?void 0:S.length)),o),we(X(w,pe(S=>S.topListHeight)),f),we(f,a),we(X(w,pe(S=>[S.top,S.bottom])),i),we(X(w,pe(S=>S.items)),x);const C=mn(X(w,_e(({items:S})=>S.length>0),Ue(o,e),_e(([{items:S},E])=>S[S.length-1].originalIndex===E-1),pe(([,S,E])=>[S-1,E]),Et(wo),pe(([S])=>S))),T=mn(X(w,Qn(200),_e(({items:S,topItems:E})=>S.length>0&&S[0].originalIndex===E.length),pe(({items:S})=>S[0].index),Et())),k=mn(X(w,_e(({items:S})=>S.length>0),pe(({items:S})=>{let E=0,j=S.length-1;for(;S[E].type==="group"&&E<j;)E++;for(;S[j].type==="group"&&j>E;)j--;return{endIndex:S[j].index,startIndex:S[E].index}}),Et(Nu)));return{endReached:C,initialItemCount:y,itemsRendered:x,listState:w,rangeChanged:k,startReached:T,topItemsIndexes:g,...h}},Tt(Un,Ru,Ta,Co,So,Eo,cr,wa),{singleton:!0}),Bu=at(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Ze(),i=en(X(Ft(n,e,r,t,o),pe(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return we(Ne(i),s),{totalListHeight:i,totalListHeightChanged:s}},Tt(rn,Ir),{singleton:!0}),tv=at(([{viewportHeight:e},{totalListHeight:t}])=>{const n=ee(!1),r=en(X(Ft(n,e,t),_e(([o])=>o),pe(([,o,s])=>Math.max(0,o-s)),Qn(0),Et()),0);return{alignToBottom:n,paddingTopAddition:r}},Tt(rn,Bu),{singleton:!0}),Hu=at(()=>({context:ee(null)})),nv=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,Uu=at(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Ze();return we(X(d,Ue(t,l,n,s,o,r,a),Ue(e),pe(([[f,h,p,m,g,y,x,w],C])=>{const{align:T,behavior:k,calculateViewLocation:S=nv,done:E,...j}=f,_=ju(f,h,m-1),P=bo(_,h.offsetTree,C)+g+y,D=P+Pn(h.sizeTree,_)[1],z=w+y,B=w+p-x,O=S({itemBottom:D,itemTop:P,locationParams:{align:T,behavior:k,...j},viewportBottom:B,viewportTop:z});return O?E&&jn(X(i,_e(H=>!H),kr(Rt(i)?1:2)),E):E&&E(),O}),_e(f=>f!==null)),c),{scrollIntoView:d}},Tt(Un,rn,So,Ir,ar),{singleton:!0});function Wu(e){return e?e==="smooth"?"smooth":"auto":!1}const rv=(e,t)=>typeof e=="function"?Wu(e(t)):t&&Wu(e),ov=at(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const m=ee(!1),g=Ze();let y=null;function x(k){ze(i,{align:"end",behavior:k,index:"LAST"})}dt(X(Ft(X(Ne(t),kr(1)),l),Ue(Ne(m),s,a,f),pe(([[k,S],E,j,_,P])=>{let D=S&&_,z="auto";return D&&(z=rv(E,j||P),D=D&&!!z),{followOutputBehavior:z,shouldFollow:D,totalCount:k}}),_e(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:S})=>{y&&(y(),y=null),Rt(n)?requestAnimationFrame(()=>{Rt(d)("following output to ",{totalCount:S},dn.DEBUG),x(k)}):y=jn(e,()=>{Rt(d)("following output to ",{totalCount:S},dn.DEBUG),x(k),y=null})});function w(k){const S=jn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!y&&(Rt(d)("scrolling to bottom due to increased size",{},dn.DEBUG),x("auto"))});setTimeout(S,100)}dt(X(Ft(Ne(m),t,c),_e(([k,,S])=>k&&S),Hn(({value:k},[,S])=>({refreshed:k===S,value:S}),{refreshed:!1,value:0}),_e(({refreshed:k})=>k),Ue(m,t)),([,k])=>{Rt(a)&&w(k!==!1)}),dt(g,()=>{w(Rt(m)!==!1)}),dt(Ft(Ne(m),o),([k,S])=>{k&&!S.atBottom&&S.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&x("auto")});const C=ee(null),T=Ze();return we(pa(X(Ne(r),pe(k=>{var S;return(S=k==null?void 0:k.length)!=null?S:0})),X(Ne(t))),T),dt(X(Ft(X(T,kr(1)),l),Ue(Ne(C),a,f,h),pe(([[k,S],E,j,_,P])=>S&&j&&(E==null?void 0:E({context:P,totalCount:k,scrollingInProgress:_}))),_e(k=>!!k),Qn(0)),k=>{y&&(y(),y=null),Rt(n)?requestAnimationFrame(()=>{Rt(d)("scrolling into view",{}),ze(p,k)}):y=jn(e,()=>{Rt(d)("scrolling into view",{}),ze(p,k),y=null})}),{autoscrollToBottom:g,followOutput:m,scrollIntoViewOnChange:C}},Tt(Un,Eo,So,Co,cr,ar,rn,Hu,Uu)),sv=at(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(we(X(a,Ue(s),_e(([,l])=>l!==0),Ue(o,r,t,n,e),pe(([[,l],c,d,f,h,p=[]])=>$u(l,c,d,f,h,p))),i),{}),Tt(Un,Co,Ir,cr),{singleton:!0}),iv=at(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=ee(0);return dt(X(e,Ue(r),_e(([,o])=>o!==0),pe(([,o])=>({top:o}))),o=>{jn(X(n,kr(1),_e(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{ze(t,o)})})}),{initialScrollTop:r}},Tt(cr,rn,Ir),{singleton:!0}),Vu=at(([{scrollVelocity:e}])=>{const t=ee(!1),n=Ze(),r=ee(!1);return we(X(e,Ue(r,t,n),_e(([o,s])=>!!s),pe(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),Et()),t),dt(X(Ft(t,e,n),Ue(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},Tt(Eo),{singleton:!0}),Ia=at(([{scrollContainerState:e,scrollTo:t}])=>{const n=Ze(),r=Ze(),o=Ze(),s=ee(!1),i=ee(void 0);return we(X(Ft(n,r),pe(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),we(X(t,Ue(r),pe(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},Tt(rn)),av=at(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Ze(),d=ee(void 0),f=ee(null),h=ee(null);return we(a,f),we(l,h),dt(X(c,Ue(t,r,i,f,h,n)),([p,m,g,y,x,w,C])=>{const T=Wx(m.sizeTree);y&&x!==null&&w!==null&&(g=x.scrollTop-w.offsetTop),g-=C,p({ranges:T,scrollTop:g})}),we(X(d,_e(fa),pe(lv)),o),we(X(s,Ue(d),_e(([,p])=>p!==void 0),Et(),pe(([,p])=>p.ranges)),e),{getState:c,restoreStateFrom:d}},Tt(Un,rn,Co,cr,Ia));function lv(e){return{align:"start",index:0,offset:e.scrollTop}}const cv=at(([{topItemsIndexes:e}])=>{const t=ee(0);return we(X(t,_e(n=>n>=0),pe(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},Tt(Ir));function Ku(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const uv=Ku(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),dv=at(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:m}])=>{const g=mn(X(l,Ue(i),Hn(([,x,w,C],[{bottom:T,items:k,offsetBottom:S,totalCount:E},j])=>{const _=T+S;let P=0;return w===E&&x.length>0&&k.length>0&&(k[0].originalIndex===0&&x[0].originalIndex===0||(P=_-C,P!==0&&(P+=j))),[P,k,E,_]},[0,[],0,0]),_e(([x])=>x!==0),Ue(r,a,n,o,p,m),_e(([,x,w,C,,,T])=>!T&&!C&&x!==0&&w===ko),pe(([[x],,,,,w])=>(w("Upward scrolling compensation",{amount:x},dn.DEBUG),x))));function y(x){x>0?(ze(t,{behavior:"auto",top:-x}),ze(e,0)):(ze(e,0),ze(t,{behavior:"auto",top:-x}))}return dt(X(g,Ue(e,s)),([x,w,C])=>{C&&uv()?ze(e,w-x):y(-x)}),dt(X(Ft(en(s,!1),e,m),_e(([x,w,C])=>!x&&!C&&w!==0),pe(([x,w])=>w),Qn(1)),y),we(X(f,pe(x=>({top:-x}))),t),dt(X(c,Ue(h,d),pe(([x,{groupIndices:w,lastSize:C,sizeTree:T},k])=>{function S(E){return E*(C+k)}if(w.length===0)return S(x);{let E=0;const j=vo(T,0);let _=0,P=0;for(;_<x;){_++,E+=j;let D=w.length===P+1?1/0:w[P+1]-w[P]-1;_+D>x&&(E-=j,D=x-_+1),_+=D,E+=S(D),P++}return E}})),x=>{ze(e,x),requestAnimationFrame(()=>{ze(t,{top:x}),requestAnimationFrame(()=>{ze(e,0),ze(m,!1)})})}),{deviation:e}},Tt(rn,Eo,Ir,Un,ar,wa)),fv=at(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),Tt(Ta,sv,cr,Vu,Bu,iv,tv,Ia,Uu,ar,Hu)),qu=at(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m},g,y,x,{listState:w,topItemsIndexes:C,...T},{scrollToIndex:k},S,{topItemCount:E},{groupCounts:j},_])=>(we(T.rangeChanged,_.scrollSeekRangeChanged),we(X(_.windowViewportRect,pe(P=>P.visibleHeight)),g.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:j,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m,sizeRanges:a,topItemCount:E,topItemsIndexes:C,totalCount:d,...x,groupIndices:s,itemSize:i,listState:w,scrollToIndex:k,statefulTotalCount:c,trackItemSizes:f,...T,..._,...g,sizes:l,...y}),Tt(Un,Co,rn,av,ov,Ir,So,dv,cv,Ru,fv));function hv(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const Es=typeof document<"u"?b.useLayoutEffect:b.useEffect;function Gu(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=b.createContext({});function l(y,x){y.propsReady&&ze(y.propsReady,!1);for(const w of r){const C=y[t.required[w]];ze(C,x[w])}for(const w of o)if(w in x){const C=y[t.optional[w]];ze(C,x[w])}y.propsReady&&ze(y.propsReady,!0)}function c(y){return s.reduce((x,w)=>(x[w]=C=>{const T=y[t.methods[w]];ze(T,C)},x),{})}function d(y){return i.reduce((x,w)=>(x[w]=Ax(y[t.events[w]]),x),{})}const f=b.forwardRef((y,x)=>{const{children:w,...C}=y,[T]=b.useState(()=>xs(jx(e),E=>{l(E,C)})),[k]=b.useState(yu(d,T));Es(()=>{for(const E of i)E in C&&dt(k[E],C[E]);return()=>{Object.values(k).map(ha)}},[C,k,T]),Es(()=>{l(T,C)}),b.useImperativeHandle(x,mu(c(T)));const S=n;return u.jsx(a.Provider,{value:T,children:n?u.jsx(S,{...hv([...r,...o,...i],C),children:w}):w})}),h=y=>{const x=b.useContext(a);return b.useCallback(w=>{ze(x[y],w)},[x,y])},p=y=>{const x=b.useContext(a)[y],w=b.useCallback(C=>dt(x,C),[x]);return b.useSyncExternalStore(w,()=>Rt(x),()=>Rt(x))},m=y=>{const x=b.useContext(a)[y],[w,C]=b.useState(yu(Rt,x));return Es(()=>dt(x,T=>{T!==w&&C(mu(T))}),[x,w]),w},g=b.version.startsWith("18")?p:m;return{Component:f,useEmitter:(y,x)=>{const w=b.useContext(a)[y];Es(()=>dt(w,x),[x,w])},useEmitterValue:g,usePublisher:h}}const Yu=b.createContext(void 0),Xu=b.createContext(void 0),Ju=typeof document<"u"?b.useLayoutEffect:b.useEffect;function Na(e){return"self"in e}function pv(e){return"body"in e}function Zu(e,t,n,r=Kr,o,s){const i=b.useRef(null),a=b.useRef(null),l=b.useRef(null),c=b.useCallback(h=>{let p,m,g;const y=h.target;if(pv(y)||Na(y)){const w=Na(y)?y:y.defaultView;g=s?w.scrollX:w.scrollY,p=s?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,m=s?w.innerWidth:w.innerHeight}else g=s?y.scrollLeft:y.scrollTop,p=s?y.scrollWidth:y.scrollHeight,m=s?y.offsetWidth:y.offsetHeight;const x=()=>{e({scrollHeight:p,scrollTop:Math.max(g,0),viewportHeight:m})};h.suppressFlushSync?x():Pi.flushSync(x),a.current!==null&&(g===a.current||g<=0||g===p-m)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);b.useEffect(()=>{const h=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",c,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const m=h.behavior==="smooth";let g,y,x;Na(p)?(y=Math.max(lr(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),g=s?p.innerWidth:p.innerHeight,x=s?window.scrollX:window.scrollY):(y=p[s?"scrollWidth":"scrollHeight"],g=lr(p,s?"width":"height"),x=p[s?"scrollLeft":"scrollTop"]);const w=y-g;if(h.top=Math.ceil(Math.max(Math.min(w,h.top),0)),Mu(g,y)||h.top===x){e({scrollHeight:y,scrollTop:x,viewportHeight:g}),m&&t(!0);return}m?(a.current=h.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),p.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const Aa="-webkit-sticky",Qu="sticky",_a=Ku(()=>{if(typeof document>"u")return Qu;const e=document.createElement("div");return e.style.position=Aa,e.style.position===Aa?Aa:Qu});function ja(e){return e}const mv=at(()=>{const e=ee(a=>`Item ${a}`),t=ee(a=>`Group ${a}`),n=ee({}),r=ee(ja),o=ee("div"),s=ee(Kr),i=(a,l=null)=>en(X(n,pe(c=>c[a]),Et()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),gv=at(([e,t])=>({...e,...t}),Tt(qu,mv)),yv=({height:e})=>u.jsx("div",{style:{height:e}}),xv={overflowAnchor:"none",position:_a(),zIndex:1},ed={overflowAnchor:"none"},vv={...ed,display:"inline-block",height:"100%"},td=b.memo(function({showTopList:e=!1}){const t=Oe("listState"),n=Sn("sizeRanges"),r=Oe("useWindowScroll"),o=Oe("customScrollParent"),s=Sn("windowScrollContainerState"),i=Sn("scrollContainerState"),a=o||r?s:i,l=Oe("itemContent"),c=Oe("context"),d=Oe("groupContent"),f=Oe("trackItemSizes"),h=Oe("itemSize"),p=Oe("log"),m=Sn("gap"),g=Oe("horizontalDirection"),{callbackRef:y}=Ox(n,h,f,e?Kr:a,p,m,o,g,Oe("skipAnimationFrameInResizeObserver")),[x,w]=b.useState(0);Pa("deviation",O=>{x!==O&&w(O)});const C=Oe("EmptyPlaceholder"),T=Oe("ScrollSeekPlaceholder")||yv,k=Oe("ListComponent"),S=Oe("ItemComponent"),E=Oe("GroupComponent"),j=Oe("computeItemKey"),_=Oe("isSeeking"),P=Oe("groupIndices").length>0,D=Oe("alignToBottom"),z=Oe("initialItemFinalLocationReached"),B=e?{}:{boxSizing:"border-box",...g?{display:"inline-block",height:"100%",marginLeft:x!==0?x:D?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:x!==0?x:D?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...z?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&C?u.jsx(C,{...tn(C,c)}):u.jsx(k,{...tn(k,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:y,style:B,children:(e?t.topItems:t.items).map(O=>{const H=O.originalIndex,R=j(H+t.firstItemIndex,O.data,c);return _?b.createElement(T,{...tn(T,c),height:O.size,index:O.index,key:R,type:O.type||"item",...O.type==="group"?{}:{groupIndex:O.groupIndex}}):O.type==="group"?b.createElement(E,{...tn(E,c),"data-index":H,"data-item-index":O.index,"data-known-size":O.size,key:R,style:xv},d(O.index,c)):b.createElement(S,{...tn(S,c),...Cv(S,O.data),"data-index":H,"data-item-group-index":O.groupIndex,"data-item-index":O.index,"data-known-size":O.size,key:R,style:g?vv:ed},P?l(O.index,O.groupIndex,O.data,c):l(O.index,O.data,c))})})}),wv={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},bv={outline:"none",overflowX:"auto",position:"relative"},Is=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),Sv={position:_a(),top:0,width:"100%",zIndex:1};function tn(e,t){if(typeof e!="string")return{context:t}}function Cv(e,t){return{item:typeof e=="string"?void 0:t}}const kv=b.memo(function(){const e=Oe("HeaderComponent"),t=Sn("headerHeight"),n=Oe("HeaderFooterTag"),r=Tr(b.useMemo(()=>s=>{t(lr(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),Tv=b.memo(function(){const e=Oe("FooterComponent"),t=Sn("footerHeight"),n=Oe("HeaderFooterTag"),r=Tr(b.useMemo(()=>s=>{t(lr(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null});function nd({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:m}=Zu(a,c,l,d,void 0,f);return e("scrollTo",m),e("scrollBy",h),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?bv:wv,...o},tabIndex:0,...i,...tn(l,s),children:r})})}function rd({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=b.useRef(null),m=t("scrollerRef"),{scrollByCallback:g,scrollerRef:y,scrollToCallback:x}=Zu(a,c,l,m,h);return Ju(()=>{var w;return y.current=h||((w=p.current)==null?void 0:w.ownerDocument.defaultView),()=>{y.current=null}},[y,h]),e("windowScrollTo",x),e("scrollBy",g),u.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...tn(l,s),children:r})})}const Ev=({children:e})=>{const t=b.useContext(Yu),n=Sn("viewportHeight"),r=Sn("fixedItemHeight"),o=Oe("alignToBottom"),s=Oe("horizontalDirection"),i=b.useMemo(()=>gu(n,l=>lr(l,s?"width":"height")),[n,s]),a=Tr(i,!0,Oe("skipAnimationFrameInResizeObserver"));return b.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:Is(o),children:e})},Iv=({children:e})=>{const t=b.useContext(Yu),n=Sn("windowViewportRect"),r=Sn("fixedItemHeight"),o=Oe("customScrollParent"),s=bu(n,o,Oe("skipAnimationFrameInResizeObserver")),i=Oe("alignToBottom");return b.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:Is(i),children:e})},Nv=({children:e})=>{const t=Oe("TopItemListComponent")||"div",n=Oe("headerHeight"),r={...Sv,marginTop:`${n}px`},o=Oe("context");return u.jsx(t,{style:r,...tn(t,o),children:e})},Av=b.memo(function(e){const t=Oe("useWindowScroll"),n=Oe("topItemsIndexes").length>0,r=Oe("customScrollParent"),o=Oe("context");return u.jsxs(r||t?Pv:jv,{...e,context:o,children:[n&&u.jsx(Nv,{children:u.jsx(td,{showTopList:!0})}),u.jsxs(r||t?Iv:Ev,{children:[u.jsx(kv,{}),u.jsx(td,{}),u.jsx(Tv,{})]})]})}),{Component:_v,useEmitter:Pa,useEmitterValue:Oe,usePublisher:Sn}=Gu(gv,{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"}},Av),jv=nd({useEmitter:Pa,useEmitterValue:Oe,usePublisher:Sn}),Pv=rd({useEmitter:Pa,useEmitterValue:Oe,usePublisher:Sn}),Rv=_v;Tt(qu,at(()=>{const e=ee(c=>u.jsxs("td",{children:["Item $",c]})),t=ee(null),n=ee(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=ee(null),o=ee(null),s=ee({}),i=ee(ja),a=ee(Kr),l=(c,d=null)=>en(X(s,pe(f=>f[c]),Et()),d);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:a,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")}})),_a();const od={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},Ov={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:sd,floor:Ns,max:Io,min:Ra,round:id}=Math;function ad(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Mv(e){return{...Ov,items:e}}function As(e,t){return e&&e.width===t.width&&e.height===t.height}function Dv(e,t){return e&&e.column===t.column&&e.row===t.row}const Lv=at(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:m,propsReady:g},{customScrollParent:y,useWindowScroll:x,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:T},k])=>{const S=ee(0),E=ee(0),j=ee(od),_=ee({height:0,width:0}),P=ee({height:0,width:0}),D=Ze(),z=Ze(),B=ee(0),O=ee(null),H=ee({column:0,row:0}),R=Ze(),V=Ze(),$=ee(!1),F=ee(0),ne=ee(!0),Q=ee(!1),ye=ee(!1);dt(X(m,Ue(F),_e(([L,q])=>!!q)),()=>{ze(ne,!1)}),dt(X(Ft(m,ne,P,_,F,Q),_e(([L,q,ie,ce,,U])=>L&&!q&&ie.height!==0&&ce.height!==0&&!U)),([,,,,L])=>{ze(Q,!0),Ca(1,()=>{ze(D,L)}),jn(X(c),()=>{ze(t,[0,0]),ze(ne,!0)})}),we(X(V,_e(L=>L!=null&&L.scrollTop>0),Bn(0)),E),dt(X(m,Ue(V),_e(([,L])=>L!=null)),([,L])=>{L&&(ze(_,L.viewport),ze(P,L.item),ze(H,L.gap),L.scrollTop>0&&(ze($,!0),jn(X(c,kr(1)),q=>{ze($,!1)}),ze(l,{top:L.scrollTop})))}),we(X(_,pe(({height:L})=>L)),f),we(X(Ft(Ne(_,As),Ne(P,As),Ne(H,(L,q)=>L&&L.column===q.column&&L.row===q.row),Ne(c)),pe(([L,q,ie,ce])=>({gap:ie,item:q,scrollTop:ce,viewport:L}))),R),we(X(Ft(Ne(S),r,Ne(H,Dv),Ne(P,As),Ne(_,As),Ne(O),Ne(E),Ne($),Ne(ne),Ne(F)),_e(([,,,,,,,L])=>!L),pe(([L,[q,ie],ce,U,We,re,xe,,Pe,$e])=>{const{column:rt,row:Se}=ce,{height:Ye,width:ot}=U,{width:et}=We;if(xe===0&&(L===0||et===0))return od;if(ot===0){const st=ka($e,L),Gt=st+Math.max(xe-1,0);return Mv(ad(st,Gt,re))}const Xe=ld(et,ot,rt);let Ke,tt;Pe?q===0&&ie===0&&xe>0?(Ke=0,tt=xe-1):(Ke=Xe*Ns((q+Se)/(Ye+Se)),tt=Xe*sd((ie+Se)/(Ye+Se))-1,tt=Ra(L-1,Io(tt,Xe-1)),Ke=Ra(tt,Io(0,Ke))):(Ke=0,tt=-1);const Ot=ad(Ke,tt,re),{bottom:St,top:nt}=cd(We,ce,U,Ot),yt=sd(L/Xe),Nt=yt*Ye+(yt-1)*Se-St;return{bottom:St,itemHeight:Ye,items:Ot,itemWidth:ot,offsetBottom:Nt,offsetTop:nt,top:nt}})),j),we(X(O,_e(L=>L!==null),pe(L=>L.length)),S),we(X(Ft(_,P,j,H),_e(([L,q,{items:ie}])=>ie.length>0&&q.height!==0&&L.height!==0),pe(([L,q,{items:ie},ce])=>{const{bottom:U,top:We}=cd(L,ce,q,ie);return[We,U]}),Et(wo)),t);const je=ee(!1);we(X(c,Ue(je),pe(([L,q])=>q||L!==0)),je);const J=mn(X(Ft(j,S),_e(([{items:L}])=>L.length>0),Ue(je),_e(([[L,q],ie])=>{const ce=L.items[L.items.length-1].index===q-1;return(ie||L.bottom>0&&L.itemHeight>0&&L.offsetBottom===0&&L.items.length===q)&&ce}),pe(([[,L]])=>L-1),Et())),ue=mn(X(Ne(j),_e(({items:L})=>L.length>0&&L[0].index===0),Bn(0),Et())),ke=mn(X(Ne(j),Ue($),_e(([{items:L},q])=>L.length>0&&!q),pe(([{items:L}])=>({endIndex:L[L.length-1].index,startIndex:L[0].index})),Et(Nu),Qn(0)));we(ke,p.scrollSeekRangeChanged),we(X(D,Ue(_,P,S,H),pe(([L,q,ie,ce,U])=>{const We=Ou(L),{align:re,behavior:xe,offset:Pe}=We;let $e=We.index;$e==="LAST"&&($e=ce-1),$e=Io(0,$e,Ra(ce-1,$e));let rt=Oa(q,U,ie,$e);return re==="end"?rt=id(rt-q.height+ie.height):re==="center"&&(rt=id(rt-q.height/2+ie.height/2)),Pe&&(rt+=Pe),{behavior:xe,top:rt}})),l);const te=en(X(j,pe(L=>L.offsetBottom+L.bottom)),0);return we(X(T,pe(L=>({height:L.visibleHeight,width:L.visibleWidth}))),_),{customScrollParent:y,data:O,deviation:B,footerHeight:o,gap:H,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:P,overscan:n,restoreStateFrom:V,scrollBy:i,scrollContainerState:a,scrollHeight:z,scrollTo:l,scrollToIndex:D,scrollTop:c,smoothScrollTargetReached:d,totalCount:S,useWindowScroll:x,viewportDimensions:_,windowScrollContainerState:w,windowScrollTo:C,windowViewportRect:T,...p,gridState:j,horizontalDirection:ye,initialTopMostItemIndex:F,totalListHeight:te,...h,endReached:J,propsReady:g,rangeChanged:ke,startReached:ue,stateChanged:R,stateRestoreInProgress:$,...k}},Tt(Ta,rn,Eo,Vu,cr,Ia,ar));function ld(e,t,n){return Io(1,Ns((e+n)/(Ns(t)+n)))}function cd(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=Oa(e,t,n,r[0].index);return{bottom:Oa(e,t,n,r[r.length-1].index)+o,top:s}}function Oa(e,t,n,r){const o=ld(e.width,n.width,t.column),s=Ns(r/o),i=s*n.height+Io(0,s-1)*t.row;return i>0?i+t.row:i}const Fv=at(()=>{const e=ee(f=>`Item ${f}`),t=ee({}),n=ee(null),r=ee("virtuoso-grid-item"),o=ee("virtuoso-grid-list"),s=ee(ja),i=ee("div"),a=ee(Kr),l=(f,h=null)=>en(X(t,pe(p=>p[f]),Et()),h),c=ee(!1),d=ee(!1);return we(Ne(d),c),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),$v=at(([e,t])=>({...e,...t}),Tt(Lv,Fv)),zv=b.memo(function(){const e=It("gridState"),t=It("listClassName"),n=It("itemClassName"),r=It("itemContent"),o=It("computeItemKey"),s=It("isSeeking"),i=Cn("scrollHeight"),a=It("ItemComponent"),l=It("ListComponent"),c=It("ScrollSeekPlaceholder"),d=It("context"),f=Cn("itemDimensions"),h=Cn("gap"),p=It("log"),m=It("stateRestoreInProgress"),g=Cn("reportReadyState"),y=Tr(b.useMemo(()=>x=>{const w=x.parentElement.parentElement.scrollHeight;i(w);const C=x.firstChild;if(C){const{height:T,width:k}=C.getBoundingClientRect();f({height:T,width:k})}h({column:dd("column-gap",getComputedStyle(x).columnGap,p),row:dd("row-gap",getComputedStyle(x).rowGap,p)})},[i,f,h,p]),!0,!1);return Ju(()=>{e.itemHeight>0&&e.itemWidth>0&&g(!0)},[e]),m?null:u.jsx(l,{className:t,ref:y,...tn(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(x=>{const w=o(x.index,x.data,d);return s?u.jsx(c,{...tn(c,d),height:e.itemHeight,index:x.index,width:e.itemWidth},w):b.createElement(a,{...tn(a,d),className:n,"data-index":x.index,key:w},r(x.index,x.data,d))})})}),Bv=b.memo(function(){const e=It("HeaderComponent"),t=Cn("headerHeight"),n=It("headerFooterTag"),r=Tr(b.useMemo(()=>s=>{t(lr(s,"height"))},[t]),!0,!1),o=It("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),Hv=b.memo(function(){const e=It("FooterComponent"),t=Cn("footerHeight"),n=It("headerFooterTag"),r=Tr(b.useMemo(()=>s=>{t(lr(s,"height"))},[t]),!0,!1),o=It("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...tn(e,o)})}):null}),Uv=({children:e})=>{const t=b.useContext(Xu),n=Cn("itemDimensions"),r=Cn("viewportDimensions"),o=Tr(b.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return b.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:Is(!1),children:e})},Wv=({children:e})=>{const t=b.useContext(Xu),n=Cn("windowViewportRect"),r=Cn("itemDimensions"),o=It("customScrollParent"),s=bu(n,o,!1);return b.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:Is(!1),children:e})},Vv=b.memo(function({...e}){const t=It("useWindowScroll"),n=It("customScrollParent"),r=n||t?qv:Kv,o=n||t?Wv:Uv,s=It("context");return u.jsx(r,{...e,...tn(r,s),children:u.jsxs(o,{children:[u.jsx(Bv,{}),u.jsx(zv,{}),u.jsx(Hv,{})]})})}),{useEmitter:ud,useEmitterValue:It,usePublisher:Cn}=Gu($v,{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"}},Vv),Kv=nd({useEmitter:ud,useEmitterValue:It,usePublisher:Cn}),qv=rd({useEmitter:ud,useEmitterValue:It,usePublisher:Cn});function dd(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,dn.WARN),t==="normal"?0:parseInt(t??"0",10)}const Gv=Go.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 fd({className:e,variant:t,...n}){return u.jsx("div",{className:oe(Gv({variant:t}),e),...n})}const No=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));No.displayName="Card";const Ao=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("flex flex-col space-y-1.5 p-6",e),...t}));Ao.displayName="CardHeader";const _o=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:oe("text-2xl font-semibold leading-none tracking-tight",e),...t}));_o.displayName="CardTitle";const hd=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:oe("text-sm text-muted-foreground",e),...t}));hd.displayName="CardDescription";const jo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("p-6 pt-0",e),...t}));jo.displayName="CardContent";const pd=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:oe("flex items-center p-6 pt-0",e),...t}));pd.displayName="CardFooter";const Yv=1,Xv=1e6;let Ma=0;function Jv(){return Ma=(Ma+1)%Number.MAX_SAFE_INTEGER,Ma.toString()}const Da=new Map,md=e=>{if(Da.has(e))return;const t=setTimeout(()=>{Da.delete(e),Po({type:"REMOVE_TOAST",toastId:e})},Xv);Da.set(e,t)},Zv=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,Yv)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?md(n):e.toasts.forEach(r=>{md(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},_s=[];let js={toasts:[]};function Po(e){js=Zv(js,e),_s.forEach(t=>{t(js)})}function Qv({...e}){const t=Jv(),n=o=>Po({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Po({type:"DISMISS_TOAST",toastId:t});return Po({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function La(){const[e,t]=v.useState(js);return v.useEffect(()=>(_s.push(t),()=>{const n=_s.indexOf(t);n>-1&&_s.splice(n,1)}),[e]),{...e,toast:Qv,dismiss:n=>Po({type:"DISMISS_TOAST",toastId:n})}}async function gd(e,t){return await wn(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function yd(e,t){return await(await gd(`/files/${e}/view`,t)).text()}async function ew(e,t){const n=await gd(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await wn(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function tw(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await wn("/files",{params:r})}function Fa(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function xd(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function Ro(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(Ro).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(xd(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=Ro(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function Oo(e){if(typeof e=="string")return e;if(xd(e))return"";try{const t=Ro(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function nw(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function rw(e){const t=Oo(e);return typeof e=="string"&&nw(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Ps(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=Fa(t);if(n!==null)return Ps(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Ps(e.content):e}function ge(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function vd(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function $a(...e){return t=>{let n=!1;const r=e.map(o=>{const s=vd(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():vd(e[o],null)}}}}function Qe(...e){return v.useCallback($a(...e),e)}function ow(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function er(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:h,children:p,...m}=f,g=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,y=v.useMemo(()=>m,Object.values(m));return u.jsx(g.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,m=v.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,sw(o,...t)]}function sw(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},iw=v[" useId ".trim().toString()]||(()=>{}),aw=0;function tr(e){const[t,n]=v.useState(iw());return Kt(()=>{n(r=>r??String(aw++))},[e]),e||(t?`radix-${t}`:"")}var lw=v[" useInsertionEffect ".trim().toString()]||Kt;function Gr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=cw({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"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=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const h=uw(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function cw({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return lw(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function uw(e){return typeof e=="function"}var dw=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],De=dw.reduce((e,t)=>{const n=vr.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function wd(e,t){e&&Yo.flushSync(()=>e.dispatchEvent(t))}function qt(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function fw(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var hw="DismissableLayer",za="dismissableLayer.update",pw="dismissableLayer.pointerDownOutside",mw="dismissableLayer.focusOutside",bd,Sd=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Rs=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(Sd),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),m=Qe(t,E=>f(E)),g=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=g.indexOf(y),w=d?g.indexOf(d):-1,C=c.layersWithOutsidePointerEventsDisabled.size>0,T=w>=x,k=xw(E=>{const j=E.target,_=[...c.branches].some(P=>P.contains(j));!T||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),S=vw(E=>{const j=E.target;[...c.branches].some(P=>P.contains(j))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return fw(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(bd=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),Cd(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=bd)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),Cd())},[d,c]),v.useEffect(()=>{const E=()=>p({});return document.addEventListener(za,E),()=>document.removeEventListener(za,E)},[]),u.jsx(De.div,{...l,ref:m,style:{pointerEvents:C?T?"auto":"none":void 0,...e.style},onFocusCapture:ge(e.onFocusCapture,S.onFocusCapture),onBlurCapture:ge(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:ge(e.onPointerDownCapture,k.onPointerDownCapture)})});Rs.displayName=hw;var gw="DismissableLayerBranch",yw=v.forwardRef((e,t)=>{const n=v.useContext(Sd),r=v.useRef(null),o=Qe(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(De.div,{...e,ref:o})});yw.displayName=gw;function xw(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){kd(pw,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function vw(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&kd(mw,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Cd(){const e=new CustomEvent(za);document.dispatchEvent(e)}function kd(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?wd(o,s):o.dispatchEvent(s)}var Ba="focusScope.autoFocusOnMount",Ha="focusScope.autoFocusOnUnmount",Td={bubbles:!1,cancelable:!0},ww="FocusScope",Os=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=qt(o),d=qt(s),f=v.useRef(null),h=Qe(t,g=>l(g)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let g=function(C){if(p.paused||!a)return;const T=C.target;a.contains(T)?f.current=T:ur(f.current,{select:!0})},y=function(C){if(p.paused||!a)return;const T=C.relatedTarget;T!==null&&(a.contains(T)||ur(f.current,{select:!0}))},x=function(C){if(document.activeElement===document.body)for(const k of C)k.removedNodes.length>0&&ur(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){Nd.add(p);const g=document.activeElement;if(!a.contains(g)){const x=new CustomEvent(Ba,Td);a.addEventListener(Ba,c),a.dispatchEvent(x),x.defaultPrevented||(bw(Ew(Ed(a)),{select:!0}),document.activeElement===g&&ur(a))}return()=>{a.removeEventListener(Ba,c),setTimeout(()=>{const x=new CustomEvent(Ha,Td);a.addEventListener(Ha,d),a.dispatchEvent(x),x.defaultPrevented||ur(g??document.body,{select:!0}),a.removeEventListener(Ha,d),Nd.remove(p)},0)}}},[a,c,d,p]);const m=v.useCallback(g=>{if(!n&&!r||p.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,x=document.activeElement;if(y&&x){const w=g.currentTarget,[C,T]=Sw(w);C&&T?!g.shiftKey&&x===T?(g.preventDefault(),n&&ur(C,{select:!0})):g.shiftKey&&x===C&&(g.preventDefault(),n&&ur(T,{select:!0})):x===w&&g.preventDefault()}},[n,r,p.paused]);return u.jsx(De.div,{tabIndex:-1,...i,ref:h,onKeyDown:m})});Os.displayName=ww;function bw(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(ur(r,{select:t}),document.activeElement!==n)return}function Sw(e){const t=Ed(e),n=Id(t,e),r=Id(t.reverse(),e);return[n,r]}function Ed(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Id(e,t){for(const n of e)if(!Cw(n,{upTo:t}))return n}function Cw(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function kw(e){return e instanceof HTMLInputElement&&"select"in e}function ur(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&kw(e)&&t&&e.select()}}var Nd=Tw();function Tw(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Ad(e,t),e.unshift(t)},remove(t){var n;e=Ad(e,t),(n=e[0])==null||n.resume()}}}function Ad(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Ew(e){return e.filter(t=>t.tagName!=="A")}var Iw="Portal",Ms=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Pi.createPortal(u.jsx(De.div,{...r,ref:t}),i):null});Ms.displayName=Iw;function Nw(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var kn=e=>{const{present:t,children:n}=e,r=Aw(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=Qe(r.ref,_w(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};kn.displayName="Presence";function Aw(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Nw(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Ds(r.current);s.current=a==="mounted"?c:"none"},[a]),Kt(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=Ds(c);e?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const g=Ds(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&g&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},h=p=>{p.target===t&&(s.current=Ds(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Ds(e){return(e==null?void 0:e.animationName)||"none"}function _w(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Ua=0;function Wa(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??_d()),document.body.insertAdjacentElement("beforeend",e[1]??_d()),Ua++,()=>{Ua===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ua--}},[])}function _d(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Wn=function(){return Wn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Wn.apply(this,arguments)};function jd(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function jw(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Ls="right-scroll-bar-position",Fs="width-before-scroll-bar",Pw="with-scroll-bars-hidden",Rw="--removed-body-scroll-bar-size";function Va(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Ow(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Mw=typeof window<"u"?v.useLayoutEffect:v.useEffect,Pd=new WeakMap;function Dw(e,t){var n=Ow(null,function(r){return e.forEach(function(o){return Va(o,r)})});return Mw(function(){var r=Pd.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Va(a,null)}),s.forEach(function(a){o.has(a)||Va(a,i)})}Pd.set(n,e)},[e]),n}function Lw(e){return e}function Fw(e,t){t===void 0&&(t=Lw);var n=[],r=!1,o={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]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function $w(e){e===void 0&&(e={});var t=Fw(null);return t.options=Wn({async:!0,ssr:!1},e),t}var Rd=function(e){var t=e.sideCar,n=jd(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,Wn({},n))};Rd.isSideCarExport=!0;function zw(e,t){return e.useMedium(t),Rd}var Od=$w(),Ka=function(){},$s=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:Ka,onWheelCapture:Ka,onTouchMoveCapture:Ka}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,m=e.noIsolation,g=e.inert,y=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,C=e.gapMode,T=jd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,S=Dw([n,t]),E=Wn(Wn({},T),o);return v.createElement(v.Fragment,null,d&&v.createElement(k,{sideCar:Od,removeScrollBar:c,shards:f,noRelative:p,noIsolation:m,inert:g,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:C}),i?v.cloneElement(v.Children.only(a),Wn(Wn({},E),{ref:S})):v.createElement(w,Wn({},E,{className:l,ref:S}),a))});$s.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},$s.classNames={fullWidth:Fs,zeroRight:Ls};var Bw=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Hw(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Bw();return t&&e.setAttribute("nonce",t),e}function Uw(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Ww(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Vw=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Hw())&&(Uw(t,n),Ww(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Kw=function(){var e=Vw();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Md=function(){var e=Kw(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},qw={left:0,top:0,right:0,gap:0},qa=function(e){return parseInt(e||"",10)||0},Gw=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[qa(n),qa(r),qa(o)]},Yw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return qw;var t=Gw(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Xw=Md(),Yr="data-scroll-locked",Jw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
|
39
39
|
.`.concat(Pw,` {
|
|
40
40
|
overflow: hidden `).concat(r,`;
|
|
41
41
|
padding-right: `).concat(a,"px ").concat(r,`;
|
package/package.json
CHANGED