teodor-new-chat-ui 4.3.279 → 4.3.281
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 +1 -3
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -4116,14 +4116,12 @@ function qx({
|
|
|
4116
4116
|
[gt]
|
|
4117
4117
|
);
|
|
4118
4118
|
Tt(() => {
|
|
4119
|
-
if (!o || !m || T)
|
|
4119
|
+
if (!o || !m || T || $e)
|
|
4120
4120
|
return;
|
|
4121
4121
|
if (re.current === m) {
|
|
4122
4122
|
re.current = null;
|
|
4123
4123
|
return;
|
|
4124
4124
|
}
|
|
4125
|
-
if ($e)
|
|
4126
|
-
return;
|
|
4127
4125
|
if (Pe.current === m) {
|
|
4128
4126
|
Pe.current = null, se.current = m;
|
|
4129
4127
|
return;
|
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=Vn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&So.assertOptions(r,{silentJSONParsing:hn.transitional(hn.boolean),forcedJSONParsing:hn.transitional(hn.boolean),clarifyTimeoutError:hn.transitional(hn.boolean)},!1),o!=null&&(O.isFunction(o)?n.paramsSerializer={serialize:o}:So.assertOptions(o,{encode:hn.function,serialize:hn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),So.assertOptions(n,{baseUrl:hn.spelling("baseURL"),withXsrfToken:hn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&O.merge(s.common,s[n.method]);s&&O.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=Ft.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(l=l&&x.synchronous,a.unshift(x.fulfilled,x.rejected))});const c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let d,f=0,h;if(!l){const m=[_l.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++],x=a[f++];try{p=m(p)}catch(y){x.call(this,y);break}}try{d=_l.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=Vn(this.defaults,t);const n=wl(t.baseURL,t.url,t.allowAbsoluteUrls);return dl(n,t.params,t.paramsSerializer)}};O.forEach(["delete","get","head","options"],function(t){Kn.prototype[t]=function(n,r){return this.request(Vn(r||{},{method:t,url:n,data:(r||{}).data}))}}),O.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Vn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Kn.prototype[t]=n(),Kn.prototype[t+"Form"]=n(!0)});let dg=class Bp{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 lr(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 Bp(function(o){t=o}),cancel:t}}};function fg(e){return function(n){return e.apply(null,n)}}function hg(e){return O.isObject(e)&&e.isAxiosError===!0}const oi={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(oi).forEach(([e,t])=>{oi[t]=e});function Ol(e){const t=new Kn(e),n=Xa(Kn.prototype.request,t);return O.extend(n,Kn.prototype,t,{allOwnKeys:!0}),O.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Ol(Vn(e,o))},n}const bt=Ol(_r);bt.Axios=Kn,bt.CanceledError=lr,bt.CancelToken=dg,bt.isCancel=gl,bt.VERSION=Rl,bt.toFormData=xo,bt.AxiosError=Pe,bt.Cancel=bt.CanceledError,bt.all=function(t){return Promise.all(t)},bt.spread=fg,bt.isAxiosError=hg,bt.mergeConfig=Vn,bt.AxiosHeaders=Ft,bt.formToJSON=e=>pl(O.isHTMLForm(e)?new FormData(e):e),bt.getAdapter=jl.getAdapter,bt.HttpStatusCode=oi,bt.default=bt;const{Axios:ZC,AxiosError:QC,CanceledError:eT,isCancel:tT,CancelToken:nT,VERSION:rT,all:oT,Cancel:sT,isAxiosError:iT,spread:aT,toFormData:lT,AxiosHeaders:cT,HttpStatusCode:uT,formToJSON:dT,getAdapter:fT,mergeConfig:hT}=bt,Ml=typeof window<"u"?window.__API_BASE_URL__:void 0,Dl=Ml?Tn(Ml):void 0;function Tn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Co=null;const si=new Set;function Ll(){return Co}function To(e){Co=e,si.forEach(t=>t(e))}function $l(e){return si.add(e),()=>si.delete(e)}const pg=3e4,mg=9e4,qt=bt.create({...Dl?{baseURL:Dl}:{},timeout:pg,withCredentials:!0});qt.interceptors.request.use(e=>(Co&&(e.headers.Authorization=`Bearer ${Co}`),e)),qt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),To(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Gt(e,t){return qt.defaults.baseURL?(await qt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function ii(e,t,n){return qt.defaults.baseURL?(await qt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fl(e,t,n){return qt.defaults.baseURL?(await qt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function zl(e,t){return qt.defaults.baseURL?(await qt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Yt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Bl{get baseUrl(){const t=qt.defaults.baseURL;return t?Tn(String(t)):""}updateConfig(t){t.baseUrl&&(qt.defaults.baseURL=Tn(String(t.baseUrl))),t.authToken!==void 0&&To(t.authToken)}getAuthToken(){return Ll()}setAuthToken(t){To(t)}onTokenChange(t){return $l(t)}async listThreads(){const t=await Gt("/threads"),n=Yt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await ii("/threads",t?{title:t}:void 0);return Yt(r)}async updateThread(t,n){const r=await Fl(`/threads/${t}`,{title:n});return Yt(r)}async deleteThread(t){const n=await zl(`/threads/${t}`);return Yt(n)}async threadInfo(t){const n=await Gt(`/threads/${t}/info`);return Yt(n)}async listAgents(){const t=await Gt("/agents"),n=Yt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Gt(`/agents/${t}`);return Yt(n)}async getAgentSchema(t){const n=await Gt(`/agents/${t}/schema`);return Yt(n)}async getState(t){const n=await Gt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Yt(n)}async getStateHistory(t){const n=await Gt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:mg});return Yt(n)}async cancelRun(t){const n=await ii("/runs/cancel",{threadId:t});return Yt(n)}async listCheckpointSummaries(t){const n=await Gt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Yt(n);return(r==null?void 0:r.items)??[]}}const jn=new Bl,Hl=b.createContext(null);function gg({children:e,apiConfig:t}){const n=jn;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(Hl.Provider,{value:r,children:e})}function ai(){const e=b.useContext(Hl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function xg(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 yg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await xg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const vg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function li(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 wg(e,t){return`${e??""}::${t??""}`}function cr(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(!li(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Sg(t),i=Ul(r,0),a=Cg(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Ul(e,t){if(!li(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(j=>!!j&&typeof j=="object").map(j=>({...j})):a===null?null:void 0,c=r.map((j,D)=>Rg(j,D)).filter(j=>!!j),d=zt(e.config),f=zt(d==null?void 0:d.configurable),h=ft(f,["checkpoint_id","checkpointId"]),p=ft(f,["checkpoint_ns","checkpointNs"]),m=zt(e==null?void 0:e.parentConfig),x=zt(m==null?void 0:m.configurable),y=ft(x,["checkpoint_id","checkpointId"])??null,g=ft(x,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,S=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString();c[c.length-1];const k=c.slice().reverse().find(j=>j.role==="user")??null,T=zt(e==null?void 0:e.metadata),C=ft(T,["branch_label","branchLabel"]),E=ft(x,["checkpoint_id","checkpointId"]),N=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:g,interrupt:bg(a,c,t),createdAt:S,parentId:E??null,branchLabel:C??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:T??null,config:d??null,parentConfig:m??null,next:N??null,tasks:l??null,values:i??null}}function bg(e,t,n){const r=jg(e,n);return r||Ag(t,n)}function Sg(e){const t=new Map;e.forEach((o,s)=>{if(!li(o))return;const i=Ul(o,s);if(!(i!=null&&i.checkpointId))return;const a=wg(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Eg(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Vl(s.createdAt??"")-Vl(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function Cg(e){var n,r;const t=[];for(const o of e){const s=o.checkpointId??null;if(!s)continue;const i=o.metadata??{},a=ft(i,["label"])??ft(i,["branch_label","branchLabel"])??ft(i,["description"])??"User input",l=kg(i,["step"]),c=ft(i,["source"]),d=o.createdAt??null,f=((r=(n=o.messages)==null?void 0:n[o.messages.length-1])==null?void 0:r.id)??null,h=o.lastUserMessageId??f,p=Tg(o.next);t.push({id:s,label:a,messageId:h,step:l,source:c??null,createdAt:d,next:p??void 0})}return t}function Tg(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function kg(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Eg(e,t){return{...e,metadata:ko(e.metadata,t.metadata)??null,config:ko(e.config,t.config)??null,parentConfig:ko(e.parentConfig,t.parentConfig)??null,next:Ig(e.next,t.next)??null,tasks:Ng(e.tasks,t.tasks)??null,values:ko(e.values,t.values)??null}}function ko(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 Ig(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 Ng(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 Ag(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 jg(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=_g(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=Pr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Pr(r.state,`${o}-state`);if(s)return s}}return null}function _g(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",x=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:m,interrupts:x,state:y!==void 0?y:f}}const n=zt(e);if(!n)return null;const r=ft(n,["id","thread_id","taskId"])??t,o=ft(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 Pr(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=Wl(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Pr(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=Pr(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=Pr(l,t,n+1,r);if(c)return c}}return null}function Wl(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=ft(n,["type","event","kind"]),o=ft(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=Wl(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 Vl(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Rg(e,t){if(!e||typeof e!="object")return null;const n=e,r=zt(e)??{},o=zt(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=vg[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=zt(o.additional_kwargs)??zt(o.additionalKwargs),d=zt(o.response_metadata)??zt(o.responseMetadata),f=ft(c,["createdAt","created_at"])??ft(o,["created_at","createdAt"]),h=ft(c,["checkpointId","checkpoint_id"]),p=ft(c,["checkpointNs","checkpoint_ns"]),m=Pg(o.content),x={id:l,role:i,content:m};f&&(x.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(x.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(x.model=String(d.model_name)),!x.model&&typeof o.model=="string"&&(x.model=o.model),h&&(x.checkpointId=h),p&&(x.checkpointNs=p);const y=Lg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),g=d?{...d}:void 0;y&&Object.keys(y).length&&(x.additionalKwargs=y),g&&Object.keys(g).length&&(x.responseMetadata=g);const w=Og((c==null?void 0:c.tool_calls)??o.tool_calls);if(w.length&&(x.content=[...x.content,...w]),i==="tool"){const S=Mg(o,x.content);S&&(x.content=S)}return x}function Pg(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Kl(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Kl(e);return t?[t]:[]}return[]}function Kl(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=ft(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=ft(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 ql(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=ft(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 ql(e,t){var s;const n=ft(e,["id","call_id"])??t,r=ft(e,["name"])??ft(zt(e.function),["name"]);if(!n||!r)return null;const o=Dg(e.args??e.arguments??((s=zt(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Og(e){return Array.isArray(e)?e.map((t,n)=>ql(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Mg(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 Dg(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 zt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function ft(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function Lg(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}const ur=120;function $g(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>ur?`${n.slice(0,ur-3)}…`:n:""}function Fg(e){var r,o;const t=[(r=e.additionalKwargs)==null?void 0:r.summary,(o=e.responseMetadata)==null?void 0:o.summary];for(const s of t)if(typeof s=="string"&&s.trim()){const i=s.trim();return i.length>ur?`${i.slice(0,ur-3)}…`:i}const n=(e.name||e.id||"").toString().trim();return n?n.length>ur?`${n.slice(0,ur-3)}…`:n:""}function Gl(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const o=$g(n.content)||Fg(n);o&&t.set(n.id,o)}return t}function Yl(e={}){const t=b.useMemo(()=>Tn(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),[x,y]=b.useState(0),[g,w]=b.useState(!1),S=b.useRef(null),k=b.useRef(!0),T=b.useRef(0),C=b.useRef(null),E=b.useRef(null),N=b.useRef(null),j=b.useRef(null),D=b.useCallback(A=>{o(A)},[]),P=b.useCallback(()=>{h(""),m(null),d(null),E.current=null,N.current=null,j.current=null},[]),M=b.useCallback(()=>{var A;console.debug("[use-chat] stop() invoked - aborting stream"),(A=S.current)==null||A.abort(),S.current=null,C.current=null,l(!1),w(!1),T.current=0,y(0)},[]),F=b.useCallback((A,z,_)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),m(null),E.current=null,N.current=null,j.current=null;const J=new AbortController;S.current=J;let $=null,R=null,Z=!1;return C.current={threadId:A.threadId??null,headers:{}},(async()=>{var me,Te,je,G,ne,X,L,U,K,se,re,Oe,qe,Ge,oe,le,De,Be;const Y=Ye=>{var Xe;try{const Le=JSON.parse(JSON.stringify(Ye));return(Xe=Le==null?void 0:Le.payload)!=null&&Xe.files_info&&Array.isArray(Le.payload.files_info)&&(Le.payload.files_info=Le.payload.files_info.map(Fe=>({...Fe,data:Fe!=null&&Fe.data?`<base64 ${String(Fe.data).length} chars>`:Fe==null?void 0:Fe.data}))),Le}catch{return Ye}};try{let Ye={};try{if(r)Ye={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ne=window.__AUTH_TOKEN__,Mt=((me=window.localStorage)==null?void 0:me.getItem("authToken"))||null;let Ht=null;try{const B=(Te=window.localStorage)==null?void 0:Te.getItem("chat-settings");B&&(Ht=((je=JSON.parse(B))==null?void 0:je.apiKey)||null)}catch{}const W=Ne||Mt||Ht||null;W&&(Ye={Authorization:`Bearer ${W}`})}}catch{}console.debug("[use-chat] POST",t+n,Y(A));let Xe={};if(typeof window<"u")try{const Ke=(G=window.localStorage)==null?void 0:G.getItem("authSessionId");Ke&&(Xe={"X-Session-Id":Ke})}catch{}const Le={...Ye,...Xe,...s.current},Fe={"Content-Type":"application/json",Accept:"text/event-stream",...Le},Je=await fetch(t+n,{method:"POST",headers:Fe,body:JSON.stringify(A),signal:J.signal,credentials:i});if(C.current&&(C.current.headers=Le),!Je.ok||!Je.body){const Ke=await Je.text().catch(()=>"");console.debug("[use-chat] non-OK response",Je.status,Ke==null?void 0:Ke.slice(0,500));const Ne=`stream ${Je.status}${Ke?": "+Ke:""}`;throw(ne=_==null?void 0:_.onConnectionError)==null||ne.call(_,Ne),Z=!0,$="error",R=Ne,new Error(Ne)}w(!0);const nt=Je.body.getReader(),kt=new TextDecoder;let pt="",mt=[];T.current=0,y(0);let gt=0,Ze=null;const He=()=>{if(mt.length){const Ke=mt.join("");mt=[],k.current&&h(Ne=>Ne+Ke)}Ze=null},Nt=()=>{typeof window<"u"&&Ze==null&&(Ze=requestAnimationFrame(He))};let At=Date.now();const nn=setInterval(()=>{var Ke;if(Date.now()-At>18e5){const Ne="Stream idle timeout";d(Ne),$="error",R=Ne,J.abort(),(Ke=_==null?void 0:_.onError)==null||Ke.call(_,Ne)}},5e3),rn=1024*1024;try{const Ke=Je.headers.get("X-Thread-Id")||Je.headers.get("x-thread-id"),Ne=Je.headers.get("X-Thread-Created")||Je.headers.get("x-thread-created"),Mt=Ke??null,Ht=String(Ne??"").toLowerCase()==="true";for(C.current&&!C.current.threadId&&(C.current={...C.current,threadId:Mt}),(X=_==null?void 0:_.onOpen)==null||X.call(_,{threadId:Mt,created:Ht});;){const{value:W,done:B}=await nt.read();if(B)break;pt+=kt.decode(W,{stream:!0}),pt.length>rn&&(pt="",console.warn("Stream buffer reset: exceeded 1MB"));let H;for(;(H=pt.indexOf(`
|
|
36
36
|
|
|
37
37
|
`))>=0;){const de=pt.slice(0,H);pt=pt.slice(H+2);const we=Bg(de);if(!we)continue;let Se;try{Se=JSON.parse(we)}catch{console.debug("[use-chat] malformed SSE:",we.slice(0,200));continue}const ye=zg(Se)?Se.data:Se;At=Date.now();const st=ye.seq;if(st!==void 0){if(st<=gt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:st,lastProcessedSeq:gt,type:ye.type});continue}gt>0&&st>gt+1&&((L=_==null?void 0:_.onGap)==null||L.call(_,{from:gt,to:st})),gt=st,T.current=st,y(st)}if(console.debug("[use-chat] received event",{seq:ye.seq,type:ye.type,preview:(()=>{var Ae;try{return ye.type==="message_delta"?{deltaTypes:(Ae=ye.delta)==null?void 0:Ae.map(et=>et.type),textLen:(ye.delta||[]).filter(et=>et.type==="text").map(et=>String(et.text||"").length)}:ye.content||ye.delta?{hasContent:!0}:{}}catch(et){return{err:String(et)}}})()}),ye.type==="checkpoint")E.current=ye.checkpointId??null,N.current=ye.checkpointNs??null,m(ye.checkpointId??null);else if(ye.type==="state_history"){j.current=ye;try{const et=cr(ye).latest;et&&(E.current=et.checkpointId??null,N.current=et.checkpointNs??null,m(et.checkpointId??null))}catch(Ae){console.warn("[use-chat] Failed to hydrate state_history payload",Ae)}}try{z==null||z(ye)}catch(Ae){console.error("[use-chat] Error in onEvent callback:",Ae,"for event:",ye.type)}if(ye.type==="token"&&e.autoAppendAssistant!==!1)mt.push(ye.content),Nt();else if(ye.type==="message_delta"){const Ae=ye.delta.filter(et=>et.type==="text").map(et=>et.text).join("");Ae&&e.autoAppendAssistant!==!1&&(mt.push(Ae),Nt())}else if(ye.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(U=_==null?void 0:_.onHeartbeat)==null||U.call(_,ye)}catch(Ae){console.warn("[use-chat] heartbeat callback failed",Ae)}}else if(Ze!==null&&cancelAnimationFrame(Ze),He(),ye.type==="checkpoint")m(ye.checkpointId);else if(ye.type==="error"){const Ae=ye;if(d(Ae.message),$="error",R=Ae.message,Ae.error_type==="auth_error"||Ae.code==="TOKEN_EXPIRED"||((K=Ae.message)==null?void 0:K.includes("token"))||((se=Ae.message)==null?void 0:se.includes("401"))||((re=Ae.message)==null?void 0:re.includes("unauthorized"))||((Oe=Ae.message)==null?void 0:Oe.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Ae.message);try{(qe=_==null?void 0:_.onAuthError)==null||qe.call(_,Ae.message)}catch(yt){console.warn("[use-chat] onAuthError handler failed",yt)}J.abort()}}}}He(),$===null&&!J.signal.aborted&&($="complete")}catch(Ke){if(Ke.name==="AbortError")$=$??"aborted";else{const Ne=Ke.message||String(Ke);$="error",R=Ne,d(Ne),(Ge=_==null?void 0:_.onError)==null||Ge.call(_,Ne)}}finally{try{await nt.cancel()}catch{}finally{(oe=nt.releaseLock)==null||oe.call(nt)}Ze!==null&&typeof window<"u"&&window.cancelAnimationFrame(Ze),clearInterval(nn)}}catch(Ye){if(Ye.name==="AbortError")$=$??"aborted";else{const Xe=Ye.message||String(Ye);$="error",R=Xe,d(Xe),(le=_==null?void 0:_.onError)==null||le.call(_,Xe),Z||((De=_==null?void 0:_.onConnectionError)==null||De.call(_,Xe),Z=!0)}}finally{const Ye=T.current,Xe=E.current,Le=N.current,Fe=j.current,Je=$??(J.signal.aborted?"aborted":R?"error":"complete");try{(Be=_==null?void 0:_.onClosed)==null||Be.call(_,{reason:Je,lastSeq:Ye,lastCheckpointId:Xe,lastCheckpointNs:Le,lastStateHistory:Fe,error:R})}catch(nt){console.warn("[use-chat] onClosed callback failed",nt)}l(!1),w(!1),S.current=null,T.current=0,y(0),C.current=null}})(),{close:()=>J.abort()}},[t,n,r,e.autoAppendAssistant]);return b.useEffect(()=>()=>{var A;k.current=!1,(A=S.current)==null||A.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:p,lastSeq:x,connected:g,stream:F,stop:M,clear:P,setToken:D}}function zg(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Bg(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
|
-
`)}function Hg(e){return e.type!=="token"}const Ug={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function Wg(e,t){var n;switch(t.type){case"reset":return{messages:ci(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=ci(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=ci(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 Jl(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>Jl(o,s),e):e}case"interrupt_response":return{...e,messages:Zl(e.messages),pendingInterrupt:null};default:return e}}function Xl(e=[]){const[t,n]=b.useReducer(Wg,{...Ug,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 Jl(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=Gg(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??Ql(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(k=>k.id===a&&k.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},h=f[a]??{lastSeq:null,lastText:nc(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:x,changed:y}=Vg(d.content,t.delta,h,p);if(!y)return e;const g={...d,content:m},w=Eo(l,c,g),S={...f,[a]:x};return{...e,messages:w,messagesStreamMeta:S}}if(t.type==="message_end"){const a=e.assemblingId??Ql(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=ec(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=tc(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}`,x=d[0]??p,y={type:"tool_call",id:x,name:c,args:t.args};if(h){const S=di(h,d,c,t.args),k={...h,name:h.name??c,additionalKwargs:S},T=f,C=T>=0?Eo(e.messages,T,k):e.messages,E=Io(k,d),N=fi(e.toolIndex,m,E);return{...e,messages:C,toolIndex:N}}const g={id:m,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:di(void 0,d.length?d:[x],c,t.args)},w=Io(g,d.length?d:[x]);return{...e,messages:[...e.messages,g],toolIndex:fi(e.toolIndex,m,w)}}if(t.type==="tool_end"){const a=ec(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=tc(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=Io(d,a);let x=t.output;if(typeof t.output=="string")try{const C=t.output.trim();(C.startsWith("{")||C.startsWith("["))&&(x=JSON.parse(C))}catch{x=t.output}const y={type:"text",text:typeof x=="string"?x:JSON.stringify(x)},g=(d==null?void 0:d.createdAt)??new Date().toISOString(),w=di(d??void 0,m.length?m:a,f),S={id:p,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[y],createdAt:g,additionalKwargs:w},k=c>=0?Eo(e.messages,c,S):[...e.messages,S],T=Io(S,a.length?a:m);return{...e,messages:k,toolIndex:fi(e.toolIndex,p,T)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=qg(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=cr(t),l=a.interrupt,c=a.latest,d=l===null?Zl(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 t.type==="thread_info",e}function ci(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 Eo(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Zl(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 Ql(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function ec(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 ui(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 di(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=ui(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 Io(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=ui(e);for(const o of r)n.add(o);return Array.from(n)}function fi(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 tc(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(ui(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 nc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Vg(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??nc(e);let l="",c=e.slice();if(s){const f=Kg(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 rc(e){return e.replace(/\s+/g," ").trim()}function Kg(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=rc(e),o=rc(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 qg(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 Eo(e,r,s)}return e}function Gg(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const oc=200;function Yg({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=b.useRef(null),f=b.useRef(null),h=b.useRef(new Map),p=b.useRef(null),m=b.useRef(null),x=b.useCallback(P=>{try{const M=globalThis.structuredClone;if(typeof M=="function")return M(P)}catch{}try{return JSON.parse(JSON.stringify(P))}catch{return P}},[]),y=b.useCallback((P,M)=>{if(!P)return;const F=h.current.get(P)??[],A=x(M),z=F.length>=oc?[...F.slice(F.length-oc+1),A]:[...F,A];h.current.set(P,z)},[x]),g=b.useCallback(P=>{P&&h.current.set(P,[])},[]),w=b.useCallback(P=>{const M=P??f.current;if(!M)return;const F=h.current.get(M);F!=null&&F.length&&F.forEach(A=>{try{n(A)}catch(z){console.error("[useChatStreamingService] Failed to replay buffered event",z)}})},[n]),S=b.useCallback(P=>{var A,z,_,J,$;const M=P.seq??null;if(M!==null){const R=d.current;if(R!==null){if(M<=R)return;M>R+1&&(s==null||s({from:R,to:M}))}d.current=M}if(P.type==="thread_info"){f.current=P.threadId,p.current&&(p.current.threadIdGuess=P.threadId),m.current=P,g(P.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",P);try{t(P)}catch(R){console.error("[useChatStreamingService] Error in onThreadInfo handler:",R)}return}if(P.type==="heartbeat"){try{c==null||c(P)}catch(R){console.error("[useChatStreamingService] Error in onHeartbeat handler:",R)}return}if(P.type==="error"){const R=P;if(R.error_type==="auth_error"||R.code==="TOKEN_EXPIRED"||((A=R.message)==null?void 0:A.includes("token"))||((z=R.message)==null?void 0:z.includes("401"))||((_=R.message)==null?void 0:_.includes("unauthorized"))||((J=R.message)==null?void 0:J.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",R.message);try{l==null||l(R.message)}catch(Y){console.warn("[useChatStreamingService] onAuthError handler failed",Y)}}}const F=P.threadId??(P.type==="state_history"?P.threadId:void 0)??f.current??(($=p.current)==null?void 0:$.threadIdGuess)??null;if(P.type==="state_history"){f.current=F??f.current;try{r==null||r(P)}catch(R){console.error("[useChatStreamingService] onStateHistory handler failed",R)}}if(Hg(P)){P.type==="checkpoint"||P.type==="state_history"?g(F??null):y(F??null,P);try{n(P)}catch(R){console.error("[useChatStreamingService] Error in onMessageEvent handler:",R)}return}try{o==null||o(P)}catch(R){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",R)}},[y,g,n,s,t,r,o]),{stream:k,stop:T,isStreaming:C,error:E,setToken:N}=Yl({baseUrl:e,token:void 0}),j=b.useCallback((P,M)=>{d.current=null,m.current=null,f.current=P.threadId??null,p.current={request:P,callbacks:M,manualStop:!1,threadIdGuess:P.threadId??null},k(P,S,{onOpen:M==null?void 0:M.onOpen,onError:F=>{var A;(A=M==null?void 0:M.onError)==null||A.call(M,F)},onGap:(M==null?void 0:M.onGap)??s,onConnectionError:F=>{var A;a==null||a(F),(A=M==null?void 0:M.onConnectionError)==null||A.call(M,F)},onAuthError:F=>{var A;l==null||l(F),(A=M==null?void 0:M.onAuthError)==null||A.call(M,F)},onHeartbeat:F=>{var A;try{c==null||c(F)}catch(z){console.warn("[useChatStreamingService] onHeartbeat handler failed",z)}try{(A=M==null?void 0:M.onHeartbeat)==null||A.call(M,F)}catch(z){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",z)}},onClosed:F=>{var J,$,R,Z;const A=((J=p.current)==null?void 0:J.manualStop)??!1,z=f.current??(($=p.current)==null?void 0:$.threadIdGuess)??((R=F.lastStateHistory)==null?void 0:R.threadId)??null;(F.reason==="complete"||F.reason==="aborted"&&A)&&g(z);const _={...F,threadId:z,threadInfo:m.current,manualStop:A};try{i==null||i(_)}catch(Y){console.warn("[useChatStreamingService] onStreamClosed handler failed",Y)}try{(Z=M==null?void 0:M.onClosed)==null||Z.call(M,_)}catch(Y){console.warn("[useChatStreamingService] downstream onClosed handler failed",Y)}p.current&&(p.current=null)}})},[g,S,l,a,c,s,i,k]),D=b.useCallback(()=>{p.current&&(p.current.manualStop=!0),T()},[T]);return b.useMemo(()=>({startStream:j,stop:D,isStreaming:C,error:E,setAuthToken:N,replayBufferedEvents:w}),[j,D,C,E,N,w])}function Xg(){const e=b.useRef(new Map),t=b.useCallback((a,l)=>{const c=e.current.get(a),d=new Map;c&&c.forEach(f=>{d.set(`${f.checkpointId}::${f.checkpointNs}`,f)}),l.forEach(f=>{d.set(`${f.checkpointId}::${f.checkpointNs}`,f)}),e.current.set(a,Array.from(d.values()))},[]),n=b.useCallback((a,l)=>{const c=e.current.get(a);return c==null?void 0:c.find(d=>d.checkpointId===l)},[]),r=b.useCallback((a,l)=>{const c=e.current.get(a);return(c==null?void 0:c.some(d=>d.checkpointId===l))??!1},[]),o=b.useCallback(a=>e.current.get(a),[]),s=b.useCallback(a=>{e.current.delete(a)},[]),i=b.useCallback(()=>{e.current.clear()},[]);return{cache:e.current,setCacheForThread:t,getCachedMetadata:n,checkpointExists:r,getThreadMetadata:o,clearThreadCache:s,clearAllCache:i}}const sc=b.createContext(null),ic=b.createContext(null),ac=b.createContext(null);b.createContext(!1);function Jg({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,checkpointMetadataCache:l}){const{api:c,baseUrl:d}=ai(),f=b.useMemo(()=>Tn(d),[d]),[h,p]=b.useState([]),[m,x]=b.useState(t),[y,g]=b.useState(!1),[w,S]=b.useState(null),[k,T]=b.useState(!1),[C,E]=b.useState(null),{state:N,seed:j,prepend:D,pushUser:P,onEvent:M}=Xl(),[F,A]=b.useState(!1),[z,_]=b.useState(!1),[J,$]=b.useState(null),[R,Z]=b.useState([]),[Y,me]=b.useState([]),[Te,je]=b.useState(!1),G=b.useMemo(()=>R.flatMap(B=>B.messages??[]),[R]),ne=b.useMemo(()=>Gl(G),[G]),X=l??Xg(),{setCacheForThread:L}=X,U=b.useCallback((B,H,de)=>{const we=H.filter(Se=>Se.checkpointId).map(Se=>({checkpointId:Se.checkpointId,checkpointNs:Se.checkpointNs??void 0,createdAt:Se.createdAt??""}));console.log(`[ChatSessionProvider] Cached metadata for ${we.length} checkpoints from ${de}`),L(B,we)},[L]),K=b.useRef(m),se=b.useRef(null),re=b.useRef(null),Oe=b.useRef(null),qe=b.useRef(!1),Ge=b.useRef(null),oe=b.useRef(new Map);b.useEffect(()=>{K.current=m},[m]);const le=b.useCallback(async()=>{g(!0),S(null);try{const B=await c.listThreads();p(B??[])}catch(B){const H=String(B);S(H),s==null||s(H)}finally{g(!1)}},[c,s]),De=b.useCallback(B=>{if(!(B!=null&&B.threadId))return;const H={threadId:B.threadId,title:B.title||`Thread ${B.threadId.slice(0,8)}`,createdAt:B.createdAt||new Date().toISOString(),updatedAt:B.updatedAt||new Date().toISOString(),messageCount:B.messageCount??1};p(de=>de.some(Se=>Se.threadId===H.threadId)?(console.debug("[ChatSessionProvider] thread_info: thread already in list",H.threadId),de):(console.debug("[ChatSessionProvider] thread_info: adding thread to list",H.threadId),[H,...de]))},[]),Be=b.useCallback(B=>{const H=B.threadId??K.current;if(!H||K.current&&K.current!==H)return;const{checkpoints:de,timeline:we}=cr(B);if(!de.length)return;U(H,de,"stream state_history");const Se=de.find(st=>st.messages&&st.messages.length>0)??de.find(st=>!!st.checkpointId)??de[0];j((Se==null?void 0:Se.messages)??[],{checkpointId:(Se==null?void 0:Se.checkpointId)??null,checkpointNs:(Se==null?void 0:Se.checkpointNs)??null}),me(we),Z(de),A(!!(Se!=null&&Se.nextCursor)),$((Se==null?void 0:Se.nextCursor)??null);const ye=`${H}:${(Se==null?void 0:Se.checkpointId)??"latest"}`;Ge.current=ye},[U,j]),Ye=b.useCallback(B=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",B.threadId),De(B),K.current!==B.threadId&&(re.current=B.threadId,console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),x(B.threadId))},[De]),{startStream:Xe,stop:Le,isStreaming:Fe,error:Je,setAuthToken:nt}=Yg({baseUrl:f,onThreadInfo:Ye,onMessageEvent:M,onStateHistory:Be,onUnhandledEvent:B=>{console.warn("[ChatSessionProvider] Unhandled event:",B.type)},onAuthError:i}),kt=b.useCallback(async B=>{try{const H=await c.createThread(B);return x(H.threadId),await le(),H.threadId}catch(H){return s==null||s(String(H)),null}},[c,le,s]),pt=b.useCallback(async B=>{try{await c.deleteThread(B),K.current===B&&(x(null),j([],{})),await le()}catch(H){s==null||s(String(H))}},[c,le,j,s]),mt=b.useCallback(async(B,H)=>{try{await c.updateThread(B,H),await le()}catch(de){s==null||s(String(de))}},[c,le,s]),gt=b.useCallback(async(B,H)=>{if(!B)return;const de=`${B}:${H??"latest"}`,we=oe.current.get(de);if(we)return we;const Se=(async()=>{const ye=B;T(!0),E(null);try{const st=await c.getStateHistory({threadId:ye,checkpointId:H||void 0});if(K.current!==ye){console.log(`[ChatSessionProvider] Thread changed during load (was ${ye}, now ${K.current}), discarding stale data`);return}const{checkpoints:Ae,timeline:et}=cr(st);U(ye,Ae,`thread load (requested: ${H})`);const yt=Ae.find(Cn=>Cn.messages&&Cn.messages.length>0)??(H?Ae.find(Cn=>Cn.checkpointId===H):null)??Ae[0];j((yt==null?void 0:yt.messages)??[],{checkpointId:(yt==null?void 0:yt.checkpointId)??null,checkpointNs:(yt==null?void 0:yt.checkpointNs)??null}),me(et),Z(Ae),A(!!(yt!=null&&yt.nextCursor)),$((yt==null?void 0:yt.nextCursor)??null)}catch(st){if(K.current===ye){const Ae=String(st);E(Ae),s==null||s(Ae)}}finally{T(!1)}})();oe.current.set(de,Se);try{await Se}finally{oe.current.delete(de)}return K.current===B&&(Ge.current=de),Se},[c,j,s,U]),Ze=b.useCallback(async(B,H)=>{Oe.current=B;try{await gt(B,H)}finally{Oe.current===B&&(Oe.current=null)}},[gt]);b.useEffect(()=>{if(!o||!m||k)return;if(re.current===m){re.current=null;return}if(Fe)return;if(Oe.current===m){Oe.current=null,se.current=m;return}if(se.current===m)return;se.current=m;const B=!qe.current&&!!n&&m===t;let H;B&&n?(H=n,qe.current=!0,console.log("[ChatSessionProvider] Loading thread with checkpoint:",H,r?`(ns: ${r})`:"")):console.log("[ChatSessionProvider] Loading thread with latest checkpoint");const de=`${m}:${H??"latest"}`;Ge.current!==de&&Ze(m,H)},[o,m,n,r,t,k,Fe,Ze]);const He=b.useCallback(async(B,H)=>{const de=K.current;if(!de)return;const we=de;je(!0);try{const Se=await c.getStateHistory({threadId:we,checkpointId:B,checkpointNs:H??void 0});if(K.current!==we){console.log(`[ChatSessionProvider] Thread changed during checkpoint navigation (was ${we}, now ${K.current}), discarding stale data`);return}const{checkpoints:ye,timeline:st}=cr(Se);U(we,ye,"checkpoint navigation");const Ae=ye.find(et=>et.checkpointId===B&&(H?et.checkpointNs===H:!0));if(!Ae){console.warn("[ChatSessionProvider] Requested checkpoint not found:",{checkpointId:B,checkpointNs:H});return}me(st),Z(ye),j(Ae.messages??[],{checkpointId:Ae.checkpointId??null,checkpointNs:Ae.checkpointNs??null})}catch(Se){K.current===we&&(s==null||s(String(Se)))}finally{je(!1)}},[c,j,s,U]),Nt=b.useCallback((B,H)=>{j(N.messages,{checkpointId:B??null,checkpointNs:H??null})},[j,N.messages]),At=b.useCallback(async()=>{K.current&&await Ze(K.current)},[Ze]),nn=b.useCallback(async()=>{if(!K.current||!J)return;const B=K.current;_(!0);try{const H=await c.getStateHistory({threadId:B,checkpointId:J});if(K.current!==B){console.log(`[ChatSessionProvider] Thread changed during history load (was ${B}, now ${K.current}), discarding stale data`);return}const{checkpoints:de}=cr(H);if(de.length>0){const we=de[de.length-1];D((we==null?void 0:we.messages)??[]),A(!!(we!=null&&we.nextCursor)),$((we==null?void 0:we.nextCursor)??null)}}catch(H){K.current===B&&(s==null||s(String(H)))}finally{_(!1)}},[c,J,D,s]),rn=b.useCallback(async()=>{j([],{}),x(null),Le(),Z([]),me([]),A(!1),$(null),T(!1),je(!1),_(!1),E(null);try{await c.getAgent("default")}catch(B){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",B)}},[j,Le,c]),Ke=b.useCallback(async(B,H,de)=>{const we=K.current;if(!we)throw new Error("No active thread to handle interrupt");const Se=H?de??!0:!1;try{const ye={threadId:we,checkpointId:N.lastCheckpointId??void 0,checkpointNs:N.lastCheckpointNs??void 0,command:{kind:"resume",value:Se}};Xe(ye)}catch(ye){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${B}:`,ye),ye}},[N.lastCheckpointId,N.lastCheckpointNs,Xe]);b.useEffect(()=>{le()},[le]),b.useEffect(()=>{a==null||a(m)},[m,a]);const Ne=b.useCallback(async(B,H)=>{let de=K.current;const we=(B==null?void 0:B.text)??"";if(!de&&!we)return;if(!de&&we){const et=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),yt=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);de=`${et}${yt}`,re.current=de,x(de)}const{contentParts:Se}=await yg(c,(B==null?void 0:B.attachments)??[]),ye=[...Se];we!=null&&we.trim()&&ye.push({type:"text",text:we});const st={id:`msg-${Date.now()}`,role:"user",content:ye,createdAt:new Date().toISOString()};P(st);const Ae={threadId:de,payload:{messages:[st]},checkpointId:(H==null?void 0:H.checkpointId)??N.lastCheckpointId??void 0,checkpointNs:(H==null?void 0:H.checkpointNs)??N.lastCheckpointNs??void 0};Xe(Ae)},[c,kt,P,N,Xe]),Mt=b.useMemo(()=>({threads:h,currentThreadId:m,setCurrentThreadId:x,isLoading:y,error:w,actions:{createThread:kt,deleteThread:pt,renameThread:mt,refreshThreads:le}}),[h,m,y,w,kt,pt,mt,le]),Ht=b.useMemo(()=>({threadId:m,messages:N.messages,interrupt:null,checkpoint:{id:N.lastCheckpointId??null,namespace:N.lastCheckpointNs??null},checkpoints:R,timelineCheckpoints:Y,metadata:null,isLoading:k,isHistoryLoading:z,isLoadingCheckpoint:Te,error:C,hasMore:F,loadOlder:nn,clearState:rn,navigateToCheckpoint:He,setCurrentCheckpointId:Nt,returnToLatest:At,loadThread:Ze,clearThread:rn,respondToInterrupt:Ke,messagePreviews:ne}),[m,N,R,Y,k,z,Te,C,F,nn,rn,He,Nt,At,Ze,Ke,ne]),W=b.useMemo(()=>({isStreaming:Fe,error:Je,connectionState:Fe?"connected":"idle",submit:Ne,send:Ne,stop:Le,setAuthToken:nt}),[Fe,Je,Ne,Le,nt]);return u.jsx(sc.Provider,{value:Mt,children:u.jsx(ic.Provider,{value:Ht,children:u.jsx(ac.Provider,{value:W,children:e})})})}function No(){const e=b.useContext(sc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Ao(){const e=b.useContext(ic);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function lc(){const e=b.useContext(ac);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function jo({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onError:i,onAuthError:a,onThreadChange:l,checkpointMetadataCache:c}){return u.jsx(gg,{apiConfig:t,children:u.jsx(Jg,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:i,onAuthError:a,onThreadChange:l,checkpointMetadataCache:c,children:e})})}function te(...e){return Up.twMerge(Hp.clsx(e))}const Zg=uo.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"}}),rt=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Un.Slot:"button";return u.jsx(i,{className:te(Zg({variant:t,size:n,className:e})),ref:s,...o})});rt.displayName="Button";const cc=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:te("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}));cc.displayName="Textarea";function uc({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,[x,y]=b.useState(e),g=(m?i:x)??"",[w,S]=b.useTransition(),k=b.useRef(null),T=b.useRef(0),C=b.useRef(null);b.useEffect(()=>{m||(y(e??""),C.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,m]);const E=b.useCallback(()=>{const z=k.current;z&&(z.style.height="auto",z.style.height=`${z.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,g]);const N=b.useCallback((z,{fromUser:_})=>{m||y(z),_&&(a==null||a(z))},[m,a]),j=b.useCallback(async z=>{z&&z.preventDefault();const _=(g??"").trim();if(!_&&!p)return;const J=++T.current;C.current={id:J,shouldClear:!0},S(()=>{var $,R,Z;try{const Y=l(_);Y&&typeof Y.then=="function"?Y.then(()=>{var me,Te;((me=C.current)==null?void 0:me.id)===J&&C.current.shouldClear&&(m||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((Te=C.current)==null?void 0:Te.id)===J&&(C.current=null)}).catch(()=>{var me;((me=C.current)==null?void 0:me.id)===J&&(C.current=null)}):((($=C.current)==null?void 0:$.id)===J&&C.current.shouldClear&&(m||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((R=C.current)==null?void 0:R.id)===J&&(C.current=null))}catch{((Z=C.current)==null?void 0:Z.id)===J&&(C.current=null)}})},[g,l,p,m,a]),D=b.useCallback(z=>{const _=z.target.value;N(_,{fromUser:!0}),C.current&&(C.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[N]),P=b.useCallback(z=>{z.key==="Enter"&&!z.shiftKey?(z.preventDefault(),j()):z.key==="Escape"&&t&&(z.preventDefault(),c==null||c())},[j,t,c]),A=`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:z=>void j(z),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(cc,{ref:k,value:g,onChange:D,onKeyDown:P,placeholder:t?"Edit your message...":n,className:A,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(rt,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(ie.Square,{size:16})}):u.jsx(rt,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!g.trim()&&!p||w,children:u.jsx(ie.Send,{size:16})})})]})})}const Qg=b.memo(uc);function pe(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 dc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function hi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=dc(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():dc(e[o],null)}}}}function We(...e){return v.useCallback(hi(...e),e)}function ex(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 kn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var g;const{scope:h,children:p,...m}=f,x=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,y=v.useMemo(()=>m,Object.values(m));return u.jsx(x.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var x;const p=((x=h==null?void 0:h[e])==null?void 0:x[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,tx(o,...t)]}function tx(...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 Et=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},nx=v[" useInsertionEffect ".trim().toString()]||Et;function dr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=rx({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=ox(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 rx({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return nx(()=>{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 ox(e){return typeof e=="function"}var sx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Re=sx.reduce((e,t)=>{const n=Un.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 fc(e,t){e&&fo.flushSync(()=>e.dispatchEvent(t))}function pi(e){const t=e+"CollectionProvider",[n,r]=kn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=x=>{const{scope:y,children:g}=x,w=b.useRef(null),S=b.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:S,collectionRef:w,children:g})};i.displayName=t;const a=e+"CollectionSlot",l=Un.createSlot(a),c=b.forwardRef((x,y)=>{const{scope:g,children:w}=x,S=s(a,g),k=We(y,S.collectionRef);return u.jsx(l,{ref:k,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=Un.createSlot(d),p=b.forwardRef((x,y)=>{const{scope:g,children:w,...S}=x,k=b.useRef(null),T=We(y,k),C=s(d,g);return b.useEffect(()=>(C.itemMap.set(k,{ref:k,...S}),()=>void C.itemMap.delete(k))),u.jsx(h,{[f]:"",ref:T,children:w})});p.displayName=d;function m(x){const y=s(e+"CollectionConsumer",x);return b.useCallback(()=>{const w=y.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((C,E)=>S.indexOf(C.ref.current)-S.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},m,r]}var ix=v.createContext(void 0);function _o(e){const t=v.useContext(ix);return e||t||"ltr"}function It(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 ax(e,t=globalThis==null?void 0:globalThis.document){const n=It(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 lx="DismissableLayer",mi="dismissableLayer.update",cx="dismissableLayer.pointerDownOutside",ux="dismissableLayer.focusOutside",hc,pc=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ro=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(pc),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),m=We(t,E=>f(E)),x=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),g=x.indexOf(y),w=d?x.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=w>=g,T=hx(E=>{const N=E.target,j=[...c.branches].some(D=>D.contains(N));!k||j||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),C=px(E=>{const N=E.target;[...c.branches].some(D=>D.contains(N))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return ax(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&&(hc=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),mc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=hc)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),mc())},[d,c]),v.useEffect(()=>{const E=()=>p({});return document.addEventListener(mi,E),()=>document.removeEventListener(mi,E)},[]),u.jsx(Re.div,{...l,ref:m,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:pe(e.onFocusCapture,C.onFocusCapture),onBlurCapture:pe(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:pe(e.onPointerDownCapture,T.onPointerDownCapture)})});Ro.displayName=lx;var dx="DismissableLayerBranch",fx=v.forwardRef((e,t)=>{const n=v.useContext(pc),r=v.useRef(null),o=We(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Re.div,{...e,ref:o})});fx.displayName=dx;function hx(e,t=globalThis==null?void 0:globalThis.document){const n=It(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){gc(cx,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 px(e,t=globalThis==null?void 0:globalThis.document){const n=It(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&gc(ux,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 mc(){const e=new CustomEvent(mi);document.dispatchEvent(e)}function gc(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?fc(o,s):o.dispatchEvent(s)}var gi=0;function xi(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??xc()),document.body.insertAdjacentElement("beforeend",e[1]??xc()),gi++,()=>{gi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),gi--}},[])}function xc(){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 yi="focusScope.autoFocusOnMount",vi="focusScope.autoFocusOnUnmount",yc={bubbles:!1,cancelable:!0},mx="FocusScope",Po=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=It(o),d=It(s),f=v.useRef(null),h=We(t,x=>l(x)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let x=function(S){if(p.paused||!a)return;const k=S.target;a.contains(k)?f.current=k:_n(f.current,{select:!0})},y=function(S){if(p.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||_n(f.current,{select:!0}))},g=function(S){if(document.activeElement===document.body)for(const T of S)T.removedNodes.length>0&&_n(a)};document.addEventListener("focusin",x),document.addEventListener("focusout",y);const w=new MutationObserver(g);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){bc.add(p);const x=document.activeElement;if(!a.contains(x)){const g=new CustomEvent(yi,yc);a.addEventListener(yi,c),a.dispatchEvent(g),g.defaultPrevented||(gx(bx(vc(a)),{select:!0}),document.activeElement===x&&_n(a))}return()=>{a.removeEventListener(yi,c),setTimeout(()=>{const g=new CustomEvent(vi,yc);a.addEventListener(vi,d),a.dispatchEvent(g),g.defaultPrevented||_n(x??document.body,{select:!0}),a.removeEventListener(vi,d),bc.remove(p)},0)}}},[a,c,d,p]);const m=v.useCallback(x=>{if(!n&&!r||p.paused)return;const y=x.key==="Tab"&&!x.altKey&&!x.ctrlKey&&!x.metaKey,g=document.activeElement;if(y&&g){const w=x.currentTarget,[S,k]=xx(w);S&&k?!x.shiftKey&&g===k?(x.preventDefault(),n&&_n(S,{select:!0})):x.shiftKey&&g===S&&(x.preventDefault(),n&&_n(k,{select:!0})):g===w&&x.preventDefault()}},[n,r,p.paused]);return u.jsx(Re.div,{tabIndex:-1,...i,ref:h,onKeyDown:m})});Po.displayName=mx;function gx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(_n(r,{select:t}),document.activeElement!==n)return}function xx(e){const t=vc(e),n=wc(t,e),r=wc(t.reverse(),e);return[n,r]}function vc(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 wc(e,t){for(const n of e)if(!yx(n,{upTo:t}))return n}function yx(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 vx(e){return e instanceof HTMLInputElement&&"select"in e}function _n(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&vx(e)&&t&&e.select()}}var bc=wx();function wx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Sc(e,t),e.unshift(t)},remove(t){var n;e=Sc(e,t),(n=e[0])==null||n.resume()}}}function Sc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function bx(e){return e.filter(t=>t.tagName!=="A")}var Sx=v[" useId ".trim().toString()]||(()=>{}),Cx=0;function En(e){const[t,n]=v.useState(Sx());return Et(()=>{n(r=>r??String(Cx++))},[e]),t?`radix-${t}`:""}const Tx=["top","right","bottom","left"],Rn=Math.min,Ut=Math.max,Oo=Math.round,Mo=Math.floor,pn=e=>({x:e,y:e}),kx={left:"right",right:"left",bottom:"top",top:"bottom"},Ex={start:"end",end:"start"};function wi(e,t,n){return Ut(e,Rn(t,n))}function In(e,t){return typeof e=="function"?e(t):e}function Nn(e){return e.split("-")[0]}function fr(e){return e.split("-")[1]}function bi(e){return e==="x"?"y":"x"}function Si(e){return e==="y"?"height":"width"}const Ix=new Set(["top","bottom"]);function mn(e){return Ix.has(Nn(e))?"y":"x"}function Ci(e){return bi(mn(e))}function Nx(e,t,n){n===void 0&&(n=!1);const r=fr(e),o=Ci(e),s=Si(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Do(i)),[i,Do(i)]}function Ax(e){const t=Do(e);return[Ti(e),t,Ti(t)]}function Ti(e){return e.replace(/start|end/g,t=>Ex[t])}const Cc=["left","right"],Tc=["right","left"],jx=["top","bottom"],_x=["bottom","top"];function Rx(e,t,n){switch(e){case"top":case"bottom":return n?t?Tc:Cc:t?Cc:Tc;case"left":case"right":return t?jx:_x;default:return[]}}function Px(e,t,n,r){const o=fr(e);let s=Rx(Nn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ti)))),s}function Do(e){return e.replace(/left|right|bottom|top/g,t=>kx[t])}function Ox(e){return{top:0,right:0,bottom:0,left:0,...e}}function kc(e){return typeof e!="number"?Ox(e):{top:e,right:e,bottom:e,left:e}}function Lo(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Ec(e,t,n){let{reference:r,floating:o}=e;const s=mn(t),i=Ci(t),a=Si(i),l=Nn(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(fr(t)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const Mx=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=Ec(c,r,l),h=r,p={},m=0;for(let x=0;x<a.length;x++){const{name:y,fn:g}=a[x],{x:w,y:S,data:k,reset:T}=await g({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=S??f,p={...p,[y]:{...p[y],...k}},T&&m<=50&&(m++,typeof T=="object"&&(T.placement&&(h=T.placement),T.rects&&(c=T.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):T.rects),{x:d,y:f}=Ec(c,h,l)),x=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function Or(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=In(t,e),m=kc(p),y=a[h?f==="floating"?"reference":"floating":f],g=Lo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),k=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},T=Lo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(g.top-T.top+m.top)/k.y,bottom:(T.bottom-g.bottom+m.bottom)/k.y,left:(g.left-T.left+m.left)/k.x,right:(T.right-g.right+m.right)/k.x}}const Dx=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=In(e,t)||{};if(c==null)return{};const f=kc(d),h={x:n,y:r},p=Ci(o),m=Si(p),x=await i.getDimensions(c),y=p==="y",g=y?"top":"left",w=y?"bottom":"right",S=y?"clientHeight":"clientWidth",k=s.reference[m]+s.reference[p]-h[p]-s.floating[m],T=h[p]-s.reference[p],C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=C?C[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(C)))&&(E=a.floating[S]||s.floating[m]);const N=k/2-T/2,j=E/2-x[m]/2-1,D=Rn(f[g],j),P=Rn(f[w],j),M=D,F=E-x[m]-P,A=E/2-x[m]/2+N,z=wi(M,A,F),_=!l.arrow&&fr(o)!=null&&A!==z&&s.reference[m]/2-(A<M?D:P)-x[m]/2<0,J=_?A<M?A-M:A-F:0;return{[p]:h[p]+J,data:{[p]:z,centerOffset:A-z-J,..._&&{alignmentOffset:J}},reset:_}}}),Lx=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:x=!0,...y}=In(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const g=Nn(o),w=mn(a),S=Nn(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),T=h||(S||!x?[Do(a)]:Ax(a)),C=m!=="none";!h&&C&&T.push(...Px(a,x,m,k));const E=[a,...T],N=await Or(t,y),j=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&j.push(N[g]),f){const A=Nx(o,i,k);j.push(N[A[0]],N[A[1]])}if(D=[...D,{placement:o,overflows:j}],!j.every(A=>A<=0)){var P,M;const A=(((P=s.flip)==null?void 0:P.index)||0)+1,z=E[A];if(z&&(!(f==="alignment"?w!==mn(z):!1)||D.every($=>mn($.placement)===w?$.overflows[0]>0:!0)))return{data:{index:A,overflows:D},reset:{placement:z}};let _=(M=D.filter(J=>J.overflows[0]<=0).sort((J,$)=>J.overflows[1]-$.overflows[1])[0])==null?void 0:M.placement;if(!_)switch(p){case"bestFit":{var F;const J=(F=D.filter($=>{if(C){const R=mn($.placement);return R===w||R==="y"}return!0}).map($=>[$.placement,$.overflows.filter(R=>R>0).reduce((R,Z)=>R+Z,0)]).sort(($,R)=>$[1]-R[1])[0])==null?void 0:F[0];J&&(_=J);break}case"initialPlacement":_=a;break}if(o!==_)return{reset:{placement:_}}}return{}}}};function Ic(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Nc(e){return Tx.some(t=>e[t]>=0)}const $x=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=In(e,t);switch(r){case"referenceHidden":{const s=await Or(t,{...o,elementContext:"reference"}),i=Ic(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Nc(i)}}}case"escaped":{const s=await Or(t,{...o,altBoundary:!0}),i=Ic(s,n.floating);return{data:{escapedOffsets:i,escaped:Nc(i)}}}default:return{}}}}},Ac=new Set(["left","top"]);async function Fx(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Nn(n),a=fr(n),l=mn(n)==="y",c=Ac.has(i)?-1:1,d=s&&l?-1:1,f=In(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}const zx=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await Fx(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},Bx=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x:g,y:w}=y;return{x:g,y:w}}},...l}=In(e,t),c={x:n,y:r},d=await Or(t,l),f=mn(Nn(o)),h=bi(f);let p=c[h],m=c[f];if(s){const y=h==="y"?"top":"left",g=h==="y"?"bottom":"right",w=p+d[y],S=p-d[g];p=wi(w,p,S)}if(i){const y=f==="y"?"top":"left",g=f==="y"?"bottom":"right",w=m+d[y],S=m-d[g];m=wi(w,m,S)}const x=a.fn({...t,[h]:p,[f]:m});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[h]:s,[f]:i}}}}}},Hx=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=In(e,t),d={x:n,y:r},f=mn(o),h=bi(f);let p=d[h],m=d[f];const x=In(a,t),y=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(l){const S=h==="y"?"height":"width",k=s.reference[h]-s.floating[S]+y.mainAxis,T=s.reference[h]+s.reference[S]-y.mainAxis;p<k?p=k:p>T&&(p=T)}if(c){var g,w;const S=h==="y"?"width":"height",k=Ac.has(Nn(o)),T=s.reference[f]-s.floating[S]+(k&&((g=i.offset)==null?void 0:g[f])||0)+(k?0:y.crossAxis),C=s.reference[f]+s.reference[S]+(k?0:((w=i.offset)==null?void 0:w[f])||0)-(k?y.crossAxis:0);m<T?m=T:m>C&&(m=C)}return{[h]:p,[f]:m}}}},Ux=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=In(e,t),d=await Or(t,c),f=Nn(o),h=fr(o),p=mn(o)==="y",{width:m,height:x}=s.floating;let y,g;f==="top"||f==="bottom"?(y=f,g=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(g=f,y=h==="end"?"top":"bottom");const w=x-d.top-d.bottom,S=m-d.left-d.right,k=Rn(x-d[y],w),T=Rn(m-d[g],S),C=!t.middlewareData.shift;let E=k,N=T;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(N=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),C&&!h){const D=Ut(d.left,0),P=Ut(d.right,0),M=Ut(d.top,0),F=Ut(d.bottom,0);p?N=m-2*(D!==0||P!==0?D+P:Ut(d.left,d.right)):E=x-2*(M!==0||F!==0?M+F:Ut(d.top,d.bottom))}await l({...t,availableWidth:N,availableHeight:E});const j=await i.getDimensions(a.floating);return m!==j.width||x!==j.height?{reset:{rects:!0}}:{}}}};function $o(){return typeof window<"u"}function hr(e){return jc(e)?(e.nodeName||"").toLowerCase():"#document"}function Wt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function gn(e){var t;return(t=(jc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function jc(e){return $o()?e instanceof Node||e instanceof Wt(e).Node:!1}function sn(e){return $o()?e instanceof Element||e instanceof Wt(e).Element:!1}function xn(e){return $o()?e instanceof HTMLElement||e instanceof Wt(e).HTMLElement:!1}function _c(e){return!$o()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Wt(e).ShadowRoot}const Wx=new Set(["inline","contents"]);function Mr(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=an(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Wx.has(o)}const Vx=new Set(["table","td","th"]);function Kx(e){return Vx.has(hr(e))}const qx=[":popover-open",":modal"];function Fo(e){return qx.some(t=>{try{return e.matches(t)}catch{return!1}})}const Gx=["transform","translate","scale","rotate","perspective"],Yx=["transform","translate","scale","rotate","perspective","filter"],Xx=["paint","layout","strict","content"];function ki(e){const t=Ei(),n=sn(e)?an(e):e;return Gx.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Yx.some(r=>(n.willChange||"").includes(r))||Xx.some(r=>(n.contain||"").includes(r))}function Jx(e){let t=Pn(e);for(;xn(t)&&!pr(t);){if(ki(t))return t;if(Fo(t))return null;t=Pn(t)}return null}function Ei(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Zx=new Set(["html","body","#document"]);function pr(e){return Zx.has(hr(e))}function an(e){return Wt(e).getComputedStyle(e)}function zo(e){return sn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Pn(e){if(hr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||_c(e)&&e.host||gn(e);return _c(t)?t.host:t}function Rc(e){const t=Pn(e);return pr(t)?e.ownerDocument?e.ownerDocument.body:e.body:xn(t)&&Mr(t)?t:Rc(t)}function Dr(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Rc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Wt(o);if(s){const a=Ii(i);return t.concat(i,i.visualViewport||[],Mr(o)?o:[],a&&n?Dr(a):[])}return t.concat(o,Dr(o,[],n))}function Ii(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Pc(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=xn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Oo(n)!==s||Oo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Ni(e){return sn(e)?e:e.contextElement}function mr(e){const t=Ni(e);if(!xn(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=Pc(t);let i=(s?Oo(n.width):n.width)/r,a=(s?Oo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Qx=pn(0);function Oc(e){const t=Wt(e);return!Ei()||!t.visualViewport?Qx:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function ey(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Wt(e)?!1:t}function qn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Ni(e);let i=pn(1);t&&(r?sn(r)&&(i=mr(r)):i=mr(e));const a=ey(s,n,r)?Oc(s):pn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const h=Wt(s),p=r&&sn(r)?Wt(r):r;let m=h,x=Ii(m);for(;x&&r&&p!==m;){const y=mr(x),g=x.getBoundingClientRect(),w=an(x),S=g.left+(x.clientLeft+parseFloat(w.paddingLeft))*y.x,k=g.top+(x.clientTop+parseFloat(w.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=S,c+=k,m=Wt(x),x=Ii(m)}}return Lo({width:d,height:f,x:l,y:c})}function Bo(e,t){const n=zo(e).scrollLeft;return t?t.left+n:qn(gn(e)).left+n}function Mc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Bo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function ty(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=gn(r),a=t?Fo(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=pn(1);const d=pn(0),f=xn(r);if((f||!f&&!s)&&((hr(r)!=="body"||Mr(i))&&(l=zo(r)),xn(r))){const p=qn(r);c=mr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?Mc(i,l):pn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}}function ny(e){return Array.from(e.getClientRects())}function ry(e){const t=gn(e),n=zo(e),r=e.ownerDocument.body,o=Ut(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ut(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Bo(e);const a=-n.scrollTop;return an(r).direction==="rtl"&&(i+=Ut(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Dc=25;function oy(e,t){const n=Wt(e),r=gn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=Ei();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Bo(r);if(c<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,m=Math.abs(r.clientWidth-f.clientWidth-p);m<=Dc&&(s-=m)}else c<=Dc&&(s+=c);return{width:s,height:i,x:a,y:l}}const sy=new Set(["absolute","fixed"]);function iy(e,t){const n=qn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=xn(e)?mr(e):pn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Lc(e,t,n){let r;if(t==="viewport")r=oy(e,n);else if(t==="document")r=ry(gn(e));else if(sn(t))r=iy(t,n);else{const o=Oc(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Lo(r)}function $c(e,t){const n=Pn(e);return n===t||!sn(n)||pr(n)?!1:an(n).position==="fixed"||$c(n,t)}function ay(e,t){const n=t.get(e);if(n)return n;let r=Dr(e,[],!1).filter(a=>sn(a)&&hr(a)!=="body"),o=null;const s=an(e).position==="fixed";let i=s?Pn(e):e;for(;sn(i)&&!pr(i);){const a=an(i),l=ki(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&sy.has(o.position)||Mr(i)&&!l&&$c(e,i))?r=r.filter(d=>d!==i):o=a,i=Pn(i)}return t.set(e,r),r}function ly(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Fo(t)?[]:ay(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Lc(t,d,o);return c.top=Ut(f.top,c.top),c.right=Rn(f.right,c.right),c.bottom=Rn(f.bottom,c.bottom),c.left=Ut(f.left,c.left),c},Lc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function cy(e){const{width:t,height:n}=Pc(e);return{width:t,height:n}}function uy(e,t,n){const r=xn(t),o=gn(t),s=n==="fixed",i=qn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=pn(0);function c(){l.x=Bo(o)}if(r||!r&&!s)if((hr(t)!=="body"||Mr(o))&&(a=zo(t)),r){const p=qn(t,!0,s,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Mc(o,a):pn(0),f=i.left+a.scrollLeft-l.x-d.x,h=i.top+a.scrollTop-l.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function Ai(e){return an(e).position==="static"}function Fc(e,t){if(!xn(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return gn(e)===n&&(n=n.ownerDocument.body),n}function zc(e,t){const n=Wt(e);if(Fo(e))return n;if(!xn(e)){let o=Pn(e);for(;o&&!pr(o);){if(sn(o)&&!Ai(o))return o;o=Pn(o)}return n}let r=Fc(e,t);for(;r&&Kx(r)&&Ai(r);)r=Fc(r,t);return r&&pr(r)&&Ai(r)&&!ki(r)?n:r||Jx(e)||n}const dy=async function(e){const t=this.getOffsetParent||zc,n=this.getDimensions,r=await n(e.floating);return{reference:uy(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function fy(e){return an(e).direction==="rtl"}const hy={convertOffsetParentRelativeRectToViewportRelativeRect:ty,getDocumentElement:gn,getClippingRect:ly,getOffsetParent:zc,getElementRects:dy,getClientRects:ny,getDimensions:cy,getScale:mr,isElement:sn,isRTL:fy};function Bc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function py(e,t){let n=null,r;const o=gn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=c;if(a||t(),!h||!p)return;const m=Mo(f),x=Mo(o.clientWidth-(d+h)),y=Mo(o.clientHeight-(f+p)),g=Mo(d),S={rootMargin:-m+"px "+-x+"px "+-y+"px "+-g+"px",threshold:Ut(0,Rn(1,l))||1};let k=!0;function T(C){const E=C[0].intersectionRatio;if(E!==l){if(!k)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Bc(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(T,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(T,S)}n.observe(e)}return i(!0),s}function my(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=Ni(e),d=o||s?[...c?Dr(c):[],...Dr(t)]:[];d.forEach(g=>{o&&g.addEventListener("scroll",n,{passive:!0}),s&&g.addEventListener("resize",n)});const f=c&&a?py(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(g=>{let[w]=g;w&&w.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var S;(S=p)==null||S.observe(t)})),n()}),c&&!l&&p.observe(c),p.observe(t));let m,x=l?qn(e):null;l&&y();function y(){const g=qn(e);x&&!Bc(x,g)&&n(),x=g,m=requestAnimationFrame(y)}return n(),()=>{var g;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(g=p)==null||g.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const gy=zx,xy=Bx,yy=Lx,vy=Ux,wy=$x,Hc=Dx,by=Hx,Sy=(e,t,n)=>{const r=new Map,o={platform:hy,...n},s={...o.platform,_c:r};return Mx(e,t,{...o,platform:s})};var Cy=typeof document<"u",Ty=function(){},Ho=Cy?b.useLayoutEffect:Ty;function Uo(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Uo(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!Uo(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Uc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Wc(e,t){const n=Uc(e);return Math.round(t*n)/n}function ji(e){const t=v.useRef(e);return Ho(()=>{t.current=e}),t}function ky(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=v.useState(r);Uo(h,r)||p(r);const[m,x]=v.useState(null),[y,g]=v.useState(null),w=v.useCallback($=>{$!==C.current&&(C.current=$,x($))},[]),S=v.useCallback($=>{$!==E.current&&(E.current=$,g($))},[]),k=s||m,T=i||y,C=v.useRef(null),E=v.useRef(null),N=v.useRef(d),j=l!=null,D=ji(l),P=ji(o),M=ji(c),F=v.useCallback(()=>{if(!C.current||!E.current)return;const $={placement:t,strategy:n,middleware:h};P.current&&($.platform=P.current),Sy(C.current,E.current,$).then(R=>{const Z={...R,isPositioned:M.current!==!1};A.current&&!Uo(N.current,Z)&&(N.current=Z,fo.flushSync(()=>{f(Z)}))})},[h,t,n,P,M]);Ho(()=>{c===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,f($=>({...$,isPositioned:!1})))},[c]);const A=v.useRef(!1);Ho(()=>(A.current=!0,()=>{A.current=!1}),[]),Ho(()=>{if(k&&(C.current=k),T&&(E.current=T),k&&T){if(D.current)return D.current(k,T,F);F()}},[k,T,F,D,j]);const z=v.useMemo(()=>({reference:C,floating:E,setReference:w,setFloating:S}),[w,S]),_=v.useMemo(()=>({reference:k,floating:T}),[k,T]),J=v.useMemo(()=>{const $={position:n,left:0,top:0};if(!_.floating)return $;const R=Wc(_.floating,d.x),Z=Wc(_.floating,d.y);return a?{...$,transform:"translate("+R+"px, "+Z+"px)",...Uc(_.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:R,top:Z}},[n,a,_.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:F,refs:z,elements:_,floatingStyles:J}),[d,F,z,_,J])}const Ey=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Hc({element:r.current,padding:o}).fn(n):{}:r?Hc({element:r,padding:o}).fn(n):{}}}},Iy=(e,t)=>({...gy(e),options:[e,t]}),Ny=(e,t)=>({...xy(e),options:[e,t]}),Ay=(e,t)=>({...by(e),options:[e,t]}),jy=(e,t)=>({...yy(e),options:[e,t]}),_y=(e,t)=>({...vy(e),options:[e,t]}),Ry=(e,t)=>({...wy(e),options:[e,t]}),Py=(e,t)=>({...Ey(e),options:[e,t]});var Oy="Arrow",Vc=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Re.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vc.displayName=Oy;var My=Vc;function Kc(e){const[t,n]=v.useState(void 0);return Et(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var _i="Popper",[qc,Wo]=kn(_i),[Dy,Gc]=qc(_i),Yc=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(Dy,{scope:t,anchor:r,onAnchorChange:o,children:n})};Yc.displayName=_i;var Xc="PopperAnchor",Jc=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Gc(Xc,n),i=v.useRef(null),a=We(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(Re.div,{...o,ref:a})});Jc.displayName=Xc;var Ri="PopperContent",[Ly,$y]=qc(Ri),Zc=v.forwardRef((e,t)=>{var X,L,U,K,se,re;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:m,...x}=e,y=Gc(Ri,n),[g,w]=v.useState(null),S=We(t,Oe=>w(Oe)),[k,T]=v.useState(null),C=Kc(k),E=(C==null?void 0:C.width)??0,N=(C==null?void 0:C.height)??0,j=r+(s!=="center"?"-"+s:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},P=Array.isArray(c)?c:[c],M=P.length>0,F={padding:D,boundary:P.filter(zy),altBoundary:M},{refs:A,floatingStyles:z,placement:_,isPositioned:J,middlewareData:$}=ky({strategy:"fixed",placement:j,whileElementsMounted:(...Oe)=>my(...Oe,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[Iy({mainAxis:o+N,alignmentAxis:i}),l&&Ny({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Ay():void 0,...F}),l&&jy({...F}),_y({...F,apply:({elements:Oe,rects:qe,availableWidth:Ge,availableHeight:oe})=>{const{width:le,height:De}=qe.reference,Be=Oe.floating.style;Be.setProperty("--radix-popper-available-width",`${Ge}px`),Be.setProperty("--radix-popper-available-height",`${oe}px`),Be.setProperty("--radix-popper-anchor-width",`${le}px`),Be.setProperty("--radix-popper-anchor-height",`${De}px`)}}),k&&Py({element:k,padding:a}),By({arrowWidth:E,arrowHeight:N}),h&&Ry({strategy:"referenceHidden",...F})]}),[R,Z]=tu(_),Y=It(m);Et(()=>{J&&(Y==null||Y())},[J,Y]);const me=(X=$.arrow)==null?void 0:X.x,Te=(L=$.arrow)==null?void 0:L.y,je=((U=$.arrow)==null?void 0:U.centerOffset)!==0,[G,ne]=v.useState();return Et(()=>{g&&ne(window.getComputedStyle(g).zIndex)},[g]),u.jsx("div",{ref:A.setFloating,"data-radix-popper-content-wrapper":"",style:{...z,transform:J?z.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:G,"--radix-popper-transform-origin":[(K=$.transformOrigin)==null?void 0:K.x,(se=$.transformOrigin)==null?void 0:se.y].join(" "),...((re=$.hide)==null?void 0:re.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(Ly,{scope:n,placedSide:R,onArrowChange:T,arrowX:me,arrowY:Te,shouldHideArrow:je,children:u.jsx(Re.div,{"data-side":R,"data-align":Z,...x,ref:S,style:{...x.style,animation:J?void 0:"none"}})})})});Zc.displayName=Ri;var Qc="PopperArrow",Fy={top:"bottom",right:"left",bottom:"top",left:"right"},eu=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=$y(Qc,r),i=Fy[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(My,{...o,ref:n,style:{...o.style,display:"block"}})})});eu.displayName=Qc;function zy(e){return e!==null}var By=e=>({name:"transformOrigin",options:e,fn(t){var y,g,w;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=tu(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((g=o.arrow)==null?void 0:g.x)??0)+a/2,p=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let m="",x="";return c==="bottom"?(m=i?f:`${h}px`,x=`${-l}px`):c==="top"?(m=i?f:`${h}px`,x=`${r.floating.height+l}px`):c==="right"?(m=`${-l}px`,x=i?f:`${p}px`):c==="left"&&(m=`${r.floating.width+l}px`,x=i?f:`${p}px`),{data:{x:m,y:x}}}});function tu(e){const[t,n="center"]=e.split("-");return[t,n]}var nu=Yc,ru=Jc,ou=Zc,su=eu,Hy="Portal",Vo=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Et(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ks.createPortal(u.jsx(Re.div,{...r,ref:t}),i):null});Vo.displayName=Hy;function Uy(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Xt=e=>{const{present:t,children:n}=e,r=Wy(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=We(r.ref,Vy(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Xt.displayName="Presence";function Wy(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Uy(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Ko(r.current);s.current=a==="mounted"?c:"none"},[a]),Et(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=Ko(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]),Et(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const x=Ko(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&x&&(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=Ko(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 Ko(e){return(e==null?void 0:e.animationName)||"none"}function Vy(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 Pi="rovingFocusGroup.onEntryFocus",Ky={bubbles:!1,cancelable:!0},Lr="RovingFocusGroup",[Oi,iu,qy]=pi(Lr),[Gy,au]=kn(Lr,[qy]),[Yy,Xy]=Gy(Lr),lu=v.forwardRef((e,t)=>u.jsx(Oi.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Oi.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Jy,{...e,ref:t})})}));lu.displayName=Lr;var Jy=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,h=v.useRef(null),p=We(t,h),m=_o(s),[x,y]=dr({prop:i,defaultProp:a??null,onChange:l,caller:Lr}),[g,w]=v.useState(!1),S=It(c),k=iu(n),T=v.useRef(!1),[C,E]=v.useState(0);return v.useEffect(()=>{const N=h.current;if(N)return N.addEventListener(Pi,S),()=>N.removeEventListener(Pi,S)},[S]),u.jsx(Yy,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:x,onItemFocus:v.useCallback(N=>y(N),[y]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(N=>N+1),[]),onFocusableItemRemove:v.useCallback(()=>E(N=>N-1),[]),children:u.jsx(Re.div,{tabIndex:g||C===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:pe(e.onMouseDown,()=>{T.current=!0}),onFocus:pe(e.onFocus,N=>{const j=!T.current;if(N.target===N.currentTarget&&j&&!g){const D=new CustomEvent(Pi,Ky);if(N.currentTarget.dispatchEvent(D),!D.defaultPrevented){const P=k().filter(_=>_.focusable),M=P.find(_=>_.active),F=P.find(_=>_.id===x),z=[M,F,...P].filter(Boolean).map(_=>_.ref.current);du(z,d)}}T.current=!1}),onBlur:pe(e.onBlur,()=>w(!1))})})}),cu="RovingFocusGroupItem",uu=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=En(),c=s||l,d=Xy(cu,n),f=d.currentTabStopId===c,h=iu(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:x}=d;return v.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),u.jsx(Oi.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Re.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:pe(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:pe(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:pe(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const g=ev(y,d.orientation,d.dir);if(g!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let S=h().filter(k=>k.focusable).map(k=>k.ref.current);if(g==="last")S.reverse();else if(g==="prev"||g==="next"){g==="prev"&&S.reverse();const k=S.indexOf(y.currentTarget);S=d.loop?tv(S,k+1):S.slice(k+1)}setTimeout(()=>du(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:x!=null}):i})})});uu.displayName=cu;var Zy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Qy(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ev(e,t,n){const r=Qy(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Zy[r]}function du(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function tv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var nv=lu,rv=uu,ov=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},gr=new WeakMap,qo=new WeakMap,Go={},Mi=0,fu=function(e){return e&&(e.host||fu(e.parentNode))},sv=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=fu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},iv=function(e,t,n,r){var o=sv(t,Array.isArray(e)?e:[e]);Go[n]||(Go[n]=new WeakMap);var s=Go[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))d(h);else try{var p=h.getAttribute(r),m=p!==null&&p!=="false",x=(gr.get(h)||0)+1,y=(s.get(h)||0)+1;gr.set(h,x),s.set(h,y),i.push(h),x===1&&m&&qo.set(h,!0),y===1&&h.setAttribute(n,"true"),m||h.setAttribute(r,"true")}catch(g){console.error("aria-hidden: cannot operate on ",h,g)}})};return d(t),a.clear(),Mi++,function(){i.forEach(function(f){var h=gr.get(f)-1,p=s.get(f)-1;gr.set(f,h),s.set(f,p),h||(qo.has(f)||f.removeAttribute(r),qo.delete(f)),p||f.removeAttribute(n)}),Mi--,Mi||(gr=new WeakMap,gr=new WeakMap,qo=new WeakMap,Go={})}},Di=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=ov(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),iv(r,o,n,"aria-hidden")):function(){return null}},yn=function(){return yn=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},yn.apply(this,arguments)};function hu(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 av(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 Yo="right-scroll-bar-position",Xo="width-before-scroll-bar",lv="with-scroll-bars-hidden",cv="--removed-body-scroll-bar-size";function Li(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function uv(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 dv=typeof window<"u"?v.useLayoutEffect:v.useEffect,pu=new WeakMap;function fv(e,t){var n=uv(null,function(r){return e.forEach(function(o){return Li(o,r)})});return dv(function(){var r=pu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Li(a,null)}),s.forEach(function(a){o.has(a)||Li(a,i)})}pu.set(n,e)},[e]),n}function hv(e){return e}function pv(e,t){t===void 0&&(t=hv);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 mv(e){e===void 0&&(e={});var t=pv(null);return t.options=yn({async:!0,ssr:!1},e),t}var mu=function(e){var t=e.sideCar,n=hu(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,yn({},n))};mu.isSideCarExport=!0;function gv(e,t){return e.useMedium(t),mu}var gu=mv(),$i=function(){},Jo=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:$i,onWheelCapture:$i,onTouchMoveCapture:$i}),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,x=e.inert,y=e.allowPinchZoom,g=e.as,w=g===void 0?"div":g,S=e.gapMode,k=hu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),T=h,C=fv([n,t]),E=yn(yn({},k),o);return v.createElement(v.Fragment,null,d&&v.createElement(T,{sideCar:gu,removeScrollBar:c,shards:f,noRelative:p,noIsolation:m,inert:x,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),yn(yn({},E),{ref:C})):v.createElement(w,yn({},E,{className:l,ref:C}),a))});Jo.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Jo.classNames={fullWidth:Xo,zeroRight:Yo};var xv=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function yv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=xv();return t&&e.setAttribute("nonce",t),e}function vv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function wv(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var bv=function(){var e=0,t=null;return{add:function(n){e==0&&(t=yv())&&(vv(t,n),wv(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Sv=function(){var e=bv();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},xu=function(){var e=Sv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Cv={left:0,top:0,right:0,gap:0},Fi=function(e){return parseInt(e||"",10)||0},Tv=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[Fi(n),Fi(r),Fi(o)]},kv=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Cv;var t=Tv(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])}},Ev=xu(),xr="data-scroll-locked",Iv=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
|
+
`)}function Hg(e){return e.type!=="token"}const Ug={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function Wg(e,t){var n;switch(t.type){case"reset":return{messages:ci(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=ci(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=ci(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 Jl(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>Jl(o,s),e):e}case"interrupt_response":return{...e,messages:Zl(e.messages),pendingInterrupt:null};default:return e}}function Xl(e=[]){const[t,n]=b.useReducer(Wg,{...Ug,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 Jl(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=Gg(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??Ql(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(k=>k.id===a&&k.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},h=f[a]??{lastSeq:null,lastText:nc(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:x,changed:y}=Vg(d.content,t.delta,h,p);if(!y)return e;const g={...d,content:m},w=Eo(l,c,g),S={...f,[a]:x};return{...e,messages:w,messagesStreamMeta:S}}if(t.type==="message_end"){const a=e.assemblingId??Ql(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=ec(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=tc(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}`,x=d[0]??p,y={type:"tool_call",id:x,name:c,args:t.args};if(h){const S=di(h,d,c,t.args),k={...h,name:h.name??c,additionalKwargs:S},T=f,C=T>=0?Eo(e.messages,T,k):e.messages,E=Io(k,d),N=fi(e.toolIndex,m,E);return{...e,messages:C,toolIndex:N}}const g={id:m,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:di(void 0,d.length?d:[x],c,t.args)},w=Io(g,d.length?d:[x]);return{...e,messages:[...e.messages,g],toolIndex:fi(e.toolIndex,m,w)}}if(t.type==="tool_end"){const a=ec(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=tc(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=Io(d,a);let x=t.output;if(typeof t.output=="string")try{const C=t.output.trim();(C.startsWith("{")||C.startsWith("["))&&(x=JSON.parse(C))}catch{x=t.output}const y={type:"text",text:typeof x=="string"?x:JSON.stringify(x)},g=(d==null?void 0:d.createdAt)??new Date().toISOString(),w=di(d??void 0,m.length?m:a,f),S={id:p,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[y],createdAt:g,additionalKwargs:w},k=c>=0?Eo(e.messages,c,S):[...e.messages,S],T=Io(S,a.length?a:m);return{...e,messages:k,toolIndex:fi(e.toolIndex,p,T)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=qg(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=cr(t),l=a.interrupt,c=a.latest,d=l===null?Zl(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 t.type==="thread_info",e}function ci(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 Eo(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Zl(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 Ql(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function ec(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 ui(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 di(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=ui(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 Io(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=ui(e);for(const o of r)n.add(o);return Array.from(n)}function fi(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 tc(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(ui(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 nc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Vg(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??nc(e);let l="",c=e.slice();if(s){const f=Kg(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 rc(e){return e.replace(/\s+/g," ").trim()}function Kg(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=rc(e),o=rc(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 qg(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 Eo(e,r,s)}return e}function Gg(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const oc=200;function Yg({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=b.useRef(null),f=b.useRef(null),h=b.useRef(new Map),p=b.useRef(null),m=b.useRef(null),x=b.useCallback(P=>{try{const M=globalThis.structuredClone;if(typeof M=="function")return M(P)}catch{}try{return JSON.parse(JSON.stringify(P))}catch{return P}},[]),y=b.useCallback((P,M)=>{if(!P)return;const F=h.current.get(P)??[],A=x(M),z=F.length>=oc?[...F.slice(F.length-oc+1),A]:[...F,A];h.current.set(P,z)},[x]),g=b.useCallback(P=>{P&&h.current.set(P,[])},[]),w=b.useCallback(P=>{const M=P??f.current;if(!M)return;const F=h.current.get(M);F!=null&&F.length&&F.forEach(A=>{try{n(A)}catch(z){console.error("[useChatStreamingService] Failed to replay buffered event",z)}})},[n]),S=b.useCallback(P=>{var A,z,_,J,$;const M=P.seq??null;if(M!==null){const R=d.current;if(R!==null){if(M<=R)return;M>R+1&&(s==null||s({from:R,to:M}))}d.current=M}if(P.type==="thread_info"){f.current=P.threadId,p.current&&(p.current.threadIdGuess=P.threadId),m.current=P,g(P.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",P);try{t(P)}catch(R){console.error("[useChatStreamingService] Error in onThreadInfo handler:",R)}return}if(P.type==="heartbeat"){try{c==null||c(P)}catch(R){console.error("[useChatStreamingService] Error in onHeartbeat handler:",R)}return}if(P.type==="error"){const R=P;if(R.error_type==="auth_error"||R.code==="TOKEN_EXPIRED"||((A=R.message)==null?void 0:A.includes("token"))||((z=R.message)==null?void 0:z.includes("401"))||((_=R.message)==null?void 0:_.includes("unauthorized"))||((J=R.message)==null?void 0:J.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",R.message);try{l==null||l(R.message)}catch(Y){console.warn("[useChatStreamingService] onAuthError handler failed",Y)}}}const F=P.threadId??(P.type==="state_history"?P.threadId:void 0)??f.current??(($=p.current)==null?void 0:$.threadIdGuess)??null;if(P.type==="state_history"){f.current=F??f.current;try{r==null||r(P)}catch(R){console.error("[useChatStreamingService] onStateHistory handler failed",R)}}if(Hg(P)){P.type==="checkpoint"||P.type==="state_history"?g(F??null):y(F??null,P);try{n(P)}catch(R){console.error("[useChatStreamingService] Error in onMessageEvent handler:",R)}return}try{o==null||o(P)}catch(R){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",R)}},[y,g,n,s,t,r,o]),{stream:k,stop:T,isStreaming:C,error:E,setToken:N}=Yl({baseUrl:e,token:void 0}),j=b.useCallback((P,M)=>{d.current=null,m.current=null,f.current=P.threadId??null,p.current={request:P,callbacks:M,manualStop:!1,threadIdGuess:P.threadId??null},k(P,S,{onOpen:M==null?void 0:M.onOpen,onError:F=>{var A;(A=M==null?void 0:M.onError)==null||A.call(M,F)},onGap:(M==null?void 0:M.onGap)??s,onConnectionError:F=>{var A;a==null||a(F),(A=M==null?void 0:M.onConnectionError)==null||A.call(M,F)},onAuthError:F=>{var A;l==null||l(F),(A=M==null?void 0:M.onAuthError)==null||A.call(M,F)},onHeartbeat:F=>{var A;try{c==null||c(F)}catch(z){console.warn("[useChatStreamingService] onHeartbeat handler failed",z)}try{(A=M==null?void 0:M.onHeartbeat)==null||A.call(M,F)}catch(z){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",z)}},onClosed:F=>{var J,$,R,Z;const A=((J=p.current)==null?void 0:J.manualStop)??!1,z=f.current??(($=p.current)==null?void 0:$.threadIdGuess)??((R=F.lastStateHistory)==null?void 0:R.threadId)??null;(F.reason==="complete"||F.reason==="aborted"&&A)&&g(z);const _={...F,threadId:z,threadInfo:m.current,manualStop:A};try{i==null||i(_)}catch(Y){console.warn("[useChatStreamingService] onStreamClosed handler failed",Y)}try{(Z=M==null?void 0:M.onClosed)==null||Z.call(M,_)}catch(Y){console.warn("[useChatStreamingService] downstream onClosed handler failed",Y)}p.current&&(p.current=null)}})},[g,S,l,a,c,s,i,k]),D=b.useCallback(()=>{p.current&&(p.current.manualStop=!0),T()},[T]);return b.useMemo(()=>({startStream:j,stop:D,isStreaming:C,error:E,setAuthToken:N,replayBufferedEvents:w}),[j,D,C,E,N,w])}function Xg(){const e=b.useRef(new Map),t=b.useCallback((a,l)=>{const c=e.current.get(a),d=new Map;c&&c.forEach(f=>{d.set(`${f.checkpointId}::${f.checkpointNs}`,f)}),l.forEach(f=>{d.set(`${f.checkpointId}::${f.checkpointNs}`,f)}),e.current.set(a,Array.from(d.values()))},[]),n=b.useCallback((a,l)=>{const c=e.current.get(a);return c==null?void 0:c.find(d=>d.checkpointId===l)},[]),r=b.useCallback((a,l)=>{const c=e.current.get(a);return(c==null?void 0:c.some(d=>d.checkpointId===l))??!1},[]),o=b.useCallback(a=>e.current.get(a),[]),s=b.useCallback(a=>{e.current.delete(a)},[]),i=b.useCallback(()=>{e.current.clear()},[]);return{cache:e.current,setCacheForThread:t,getCachedMetadata:n,checkpointExists:r,getThreadMetadata:o,clearThreadCache:s,clearAllCache:i}}const sc=b.createContext(null),ic=b.createContext(null),ac=b.createContext(null);b.createContext(!1);function Jg({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,checkpointMetadataCache:l}){const{api:c,baseUrl:d}=ai(),f=b.useMemo(()=>Tn(d),[d]),[h,p]=b.useState([]),[m,x]=b.useState(t),[y,g]=b.useState(!1),[w,S]=b.useState(null),[k,T]=b.useState(!1),[C,E]=b.useState(null),{state:N,seed:j,prepend:D,pushUser:P,onEvent:M}=Xl(),[F,A]=b.useState(!1),[z,_]=b.useState(!1),[J,$]=b.useState(null),[R,Z]=b.useState([]),[Y,me]=b.useState([]),[Te,je]=b.useState(!1),G=b.useMemo(()=>R.flatMap(B=>B.messages??[]),[R]),ne=b.useMemo(()=>Gl(G),[G]),X=l??Xg(),{setCacheForThread:L}=X,U=b.useCallback((B,H,de)=>{const we=H.filter(Se=>Se.checkpointId).map(Se=>({checkpointId:Se.checkpointId,checkpointNs:Se.checkpointNs??void 0,createdAt:Se.createdAt??""}));console.log(`[ChatSessionProvider] Cached metadata for ${we.length} checkpoints from ${de}`),L(B,we)},[L]),K=b.useRef(m),se=b.useRef(null),re=b.useRef(null),Oe=b.useRef(null),qe=b.useRef(!1),Ge=b.useRef(null),oe=b.useRef(new Map);b.useEffect(()=>{K.current=m},[m]);const le=b.useCallback(async()=>{g(!0),S(null);try{const B=await c.listThreads();p(B??[])}catch(B){const H=String(B);S(H),s==null||s(H)}finally{g(!1)}},[c,s]),De=b.useCallback(B=>{if(!(B!=null&&B.threadId))return;const H={threadId:B.threadId,title:B.title||`Thread ${B.threadId.slice(0,8)}`,createdAt:B.createdAt||new Date().toISOString(),updatedAt:B.updatedAt||new Date().toISOString(),messageCount:B.messageCount??1};p(de=>de.some(Se=>Se.threadId===H.threadId)?(console.debug("[ChatSessionProvider] thread_info: thread already in list",H.threadId),de):(console.debug("[ChatSessionProvider] thread_info: adding thread to list",H.threadId),[H,...de]))},[]),Be=b.useCallback(B=>{const H=B.threadId??K.current;if(!H||K.current&&K.current!==H)return;const{checkpoints:de,timeline:we}=cr(B);if(!de.length)return;U(H,de,"stream state_history");const Se=de.find(st=>st.messages&&st.messages.length>0)??de.find(st=>!!st.checkpointId)??de[0];j((Se==null?void 0:Se.messages)??[],{checkpointId:(Se==null?void 0:Se.checkpointId)??null,checkpointNs:(Se==null?void 0:Se.checkpointNs)??null}),me(we),Z(de),A(!!(Se!=null&&Se.nextCursor)),$((Se==null?void 0:Se.nextCursor)??null);const ye=`${H}:${(Se==null?void 0:Se.checkpointId)??"latest"}`;Ge.current=ye},[U,j]),Ye=b.useCallback(B=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",B.threadId),De(B),K.current!==B.threadId&&(re.current=B.threadId,console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),x(B.threadId))},[De]),{startStream:Xe,stop:Le,isStreaming:Fe,error:Je,setAuthToken:nt}=Yg({baseUrl:f,onThreadInfo:Ye,onMessageEvent:M,onStateHistory:Be,onUnhandledEvent:B=>{console.warn("[ChatSessionProvider] Unhandled event:",B.type)},onAuthError:i}),kt=b.useCallback(async B=>{try{const H=await c.createThread(B);return x(H.threadId),await le(),H.threadId}catch(H){return s==null||s(String(H)),null}},[c,le,s]),pt=b.useCallback(async B=>{try{await c.deleteThread(B),K.current===B&&(x(null),j([],{})),await le()}catch(H){s==null||s(String(H))}},[c,le,j,s]),mt=b.useCallback(async(B,H)=>{try{await c.updateThread(B,H),await le()}catch(de){s==null||s(String(de))}},[c,le,s]),gt=b.useCallback(async(B,H)=>{if(!B)return;const de=`${B}:${H??"latest"}`,we=oe.current.get(de);if(we)return we;const Se=(async()=>{const ye=B;T(!0),E(null);try{const st=await c.getStateHistory({threadId:ye,checkpointId:H||void 0});if(K.current!==ye){console.log(`[ChatSessionProvider] Thread changed during load (was ${ye}, now ${K.current}), discarding stale data`);return}const{checkpoints:Ae,timeline:et}=cr(st);U(ye,Ae,`thread load (requested: ${H})`);const yt=Ae.find(Cn=>Cn.messages&&Cn.messages.length>0)??(H?Ae.find(Cn=>Cn.checkpointId===H):null)??Ae[0];j((yt==null?void 0:yt.messages)??[],{checkpointId:(yt==null?void 0:yt.checkpointId)??null,checkpointNs:(yt==null?void 0:yt.checkpointNs)??null}),me(et),Z(Ae),A(!!(yt!=null&&yt.nextCursor)),$((yt==null?void 0:yt.nextCursor)??null)}catch(st){if(K.current===ye){const Ae=String(st);E(Ae),s==null||s(Ae)}}finally{T(!1)}})();oe.current.set(de,Se);try{await Se}finally{oe.current.delete(de)}return K.current===B&&(Ge.current=de),Se},[c,j,s,U]),Ze=b.useCallback(async(B,H)=>{Oe.current=B;try{await gt(B,H)}finally{Oe.current===B&&(Oe.current=null)}},[gt]);b.useEffect(()=>{if(!o||!m||k||Fe)return;if(re.current===m){re.current=null;return}if(Oe.current===m){Oe.current=null,se.current=m;return}if(se.current===m)return;se.current=m;const B=!qe.current&&!!n&&m===t;let H;B&&n?(H=n,qe.current=!0,console.log("[ChatSessionProvider] Loading thread with checkpoint:",H,r?`(ns: ${r})`:"")):console.log("[ChatSessionProvider] Loading thread with latest checkpoint");const de=`${m}:${H??"latest"}`;Ge.current!==de&&Ze(m,H)},[o,m,n,r,t,k,Fe,Ze]);const He=b.useCallback(async(B,H)=>{const de=K.current;if(!de)return;const we=de;je(!0);try{const Se=await c.getStateHistory({threadId:we,checkpointId:B,checkpointNs:H??void 0});if(K.current!==we){console.log(`[ChatSessionProvider] Thread changed during checkpoint navigation (was ${we}, now ${K.current}), discarding stale data`);return}const{checkpoints:ye,timeline:st}=cr(Se);U(we,ye,"checkpoint navigation");const Ae=ye.find(et=>et.checkpointId===B&&(H?et.checkpointNs===H:!0));if(!Ae){console.warn("[ChatSessionProvider] Requested checkpoint not found:",{checkpointId:B,checkpointNs:H});return}me(st),Z(ye),j(Ae.messages??[],{checkpointId:Ae.checkpointId??null,checkpointNs:Ae.checkpointNs??null})}catch(Se){K.current===we&&(s==null||s(String(Se)))}finally{je(!1)}},[c,j,s,U]),Nt=b.useCallback((B,H)=>{j(N.messages,{checkpointId:B??null,checkpointNs:H??null})},[j,N.messages]),At=b.useCallback(async()=>{K.current&&await Ze(K.current)},[Ze]),nn=b.useCallback(async()=>{if(!K.current||!J)return;const B=K.current;_(!0);try{const H=await c.getStateHistory({threadId:B,checkpointId:J});if(K.current!==B){console.log(`[ChatSessionProvider] Thread changed during history load (was ${B}, now ${K.current}), discarding stale data`);return}const{checkpoints:de}=cr(H);if(de.length>0){const we=de[de.length-1];D((we==null?void 0:we.messages)??[]),A(!!(we!=null&&we.nextCursor)),$((we==null?void 0:we.nextCursor)??null)}}catch(H){K.current===B&&(s==null||s(String(H)))}finally{_(!1)}},[c,J,D,s]),rn=b.useCallback(async()=>{j([],{}),x(null),Le(),Z([]),me([]),A(!1),$(null),T(!1),je(!1),_(!1),E(null);try{await c.getAgent("default")}catch(B){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",B)}},[j,Le,c]),Ke=b.useCallback(async(B,H,de)=>{const we=K.current;if(!we)throw new Error("No active thread to handle interrupt");const Se=H?de??!0:!1;try{const ye={threadId:we,checkpointId:N.lastCheckpointId??void 0,checkpointNs:N.lastCheckpointNs??void 0,command:{kind:"resume",value:Se}};Xe(ye)}catch(ye){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${B}:`,ye),ye}},[N.lastCheckpointId,N.lastCheckpointNs,Xe]);b.useEffect(()=>{le()},[le]),b.useEffect(()=>{a==null||a(m)},[m,a]);const Ne=b.useCallback(async(B,H)=>{let de=K.current;const we=(B==null?void 0:B.text)??"";if(!de&&!we)return;if(!de&&we){const et=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),yt=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);de=`${et}${yt}`,re.current=de,x(de)}const{contentParts:Se}=await yg(c,(B==null?void 0:B.attachments)??[]),ye=[...Se];we!=null&&we.trim()&&ye.push({type:"text",text:we});const st={id:`msg-${Date.now()}`,role:"user",content:ye,createdAt:new Date().toISOString()};P(st);const Ae={threadId:de,payload:{messages:[st]},checkpointId:(H==null?void 0:H.checkpointId)??N.lastCheckpointId??void 0,checkpointNs:(H==null?void 0:H.checkpointNs)??N.lastCheckpointNs??void 0};Xe(Ae)},[c,kt,P,N,Xe]),Mt=b.useMemo(()=>({threads:h,currentThreadId:m,setCurrentThreadId:x,isLoading:y,error:w,actions:{createThread:kt,deleteThread:pt,renameThread:mt,refreshThreads:le}}),[h,m,y,w,kt,pt,mt,le]),Ht=b.useMemo(()=>({threadId:m,messages:N.messages,interrupt:null,checkpoint:{id:N.lastCheckpointId??null,namespace:N.lastCheckpointNs??null},checkpoints:R,timelineCheckpoints:Y,metadata:null,isLoading:k,isHistoryLoading:z,isLoadingCheckpoint:Te,error:C,hasMore:F,loadOlder:nn,clearState:rn,navigateToCheckpoint:He,setCurrentCheckpointId:Nt,returnToLatest:At,loadThread:Ze,clearThread:rn,respondToInterrupt:Ke,messagePreviews:ne}),[m,N,R,Y,k,z,Te,C,F,nn,rn,He,Nt,At,Ze,Ke,ne]),W=b.useMemo(()=>({isStreaming:Fe,error:Je,connectionState:Fe?"connected":"idle",submit:Ne,send:Ne,stop:Le,setAuthToken:nt}),[Fe,Je,Ne,Le,nt]);return u.jsx(sc.Provider,{value:Mt,children:u.jsx(ic.Provider,{value:Ht,children:u.jsx(ac.Provider,{value:W,children:e})})})}function No(){const e=b.useContext(sc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Ao(){const e=b.useContext(ic);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function lc(){const e=b.useContext(ac);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function jo({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onError:i,onAuthError:a,onThreadChange:l,checkpointMetadataCache:c}){return u.jsx(gg,{apiConfig:t,children:u.jsx(Jg,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:i,onAuthError:a,onThreadChange:l,checkpointMetadataCache:c,children:e})})}function te(...e){return Up.twMerge(Hp.clsx(e))}const Zg=uo.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"}}),rt=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Un.Slot:"button";return u.jsx(i,{className:te(Zg({variant:t,size:n,className:e})),ref:s,...o})});rt.displayName="Button";const cc=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:te("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}));cc.displayName="Textarea";function uc({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,[x,y]=b.useState(e),g=(m?i:x)??"",[w,S]=b.useTransition(),k=b.useRef(null),T=b.useRef(0),C=b.useRef(null);b.useEffect(()=>{m||(y(e??""),C.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,m]);const E=b.useCallback(()=>{const z=k.current;z&&(z.style.height="auto",z.style.height=`${z.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,g]);const N=b.useCallback((z,{fromUser:_})=>{m||y(z),_&&(a==null||a(z))},[m,a]),j=b.useCallback(async z=>{z&&z.preventDefault();const _=(g??"").trim();if(!_&&!p)return;const J=++T.current;C.current={id:J,shouldClear:!0},S(()=>{var $,R,Z;try{const Y=l(_);Y&&typeof Y.then=="function"?Y.then(()=>{var me,Te;((me=C.current)==null?void 0:me.id)===J&&C.current.shouldClear&&(m||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((Te=C.current)==null?void 0:Te.id)===J&&(C.current=null)}).catch(()=>{var me;((me=C.current)==null?void 0:me.id)===J&&(C.current=null)}):((($=C.current)==null?void 0:$.id)===J&&C.current.shouldClear&&(m||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((R=C.current)==null?void 0:R.id)===J&&(C.current=null))}catch{((Z=C.current)==null?void 0:Z.id)===J&&(C.current=null)}})},[g,l,p,m,a]),D=b.useCallback(z=>{const _=z.target.value;N(_,{fromUser:!0}),C.current&&(C.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[N]),P=b.useCallback(z=>{z.key==="Enter"&&!z.shiftKey?(z.preventDefault(),j()):z.key==="Escape"&&t&&(z.preventDefault(),c==null||c())},[j,t,c]),A=`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:z=>void j(z),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(cc,{ref:k,value:g,onChange:D,onKeyDown:P,placeholder:t?"Edit your message...":n,className:A,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(rt,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(ie.Square,{size:16})}):u.jsx(rt,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!g.trim()&&!p||w,children:u.jsx(ie.Send,{size:16})})})]})})}const Qg=b.memo(uc);function pe(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 dc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function hi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=dc(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():dc(e[o],null)}}}}function We(...e){return v.useCallback(hi(...e),e)}function ex(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 kn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var g;const{scope:h,children:p,...m}=f,x=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,y=v.useMemo(()=>m,Object.values(m));return u.jsx(x.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var x;const p=((x=h==null?void 0:h[e])==null?void 0:x[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,tx(o,...t)]}function tx(...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 Et=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},nx=v[" useInsertionEffect ".trim().toString()]||Et;function dr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=rx({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=ox(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 rx({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return nx(()=>{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 ox(e){return typeof e=="function"}var sx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Re=sx.reduce((e,t)=>{const n=Un.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 fc(e,t){e&&fo.flushSync(()=>e.dispatchEvent(t))}function pi(e){const t=e+"CollectionProvider",[n,r]=kn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=x=>{const{scope:y,children:g}=x,w=b.useRef(null),S=b.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:S,collectionRef:w,children:g})};i.displayName=t;const a=e+"CollectionSlot",l=Un.createSlot(a),c=b.forwardRef((x,y)=>{const{scope:g,children:w}=x,S=s(a,g),k=We(y,S.collectionRef);return u.jsx(l,{ref:k,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=Un.createSlot(d),p=b.forwardRef((x,y)=>{const{scope:g,children:w,...S}=x,k=b.useRef(null),T=We(y,k),C=s(d,g);return b.useEffect(()=>(C.itemMap.set(k,{ref:k,...S}),()=>void C.itemMap.delete(k))),u.jsx(h,{[f]:"",ref:T,children:w})});p.displayName=d;function m(x){const y=s(e+"CollectionConsumer",x);return b.useCallback(()=>{const w=y.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((C,E)=>S.indexOf(C.ref.current)-S.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},m,r]}var ix=v.createContext(void 0);function _o(e){const t=v.useContext(ix);return e||t||"ltr"}function It(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 ax(e,t=globalThis==null?void 0:globalThis.document){const n=It(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 lx="DismissableLayer",mi="dismissableLayer.update",cx="dismissableLayer.pointerDownOutside",ux="dismissableLayer.focusOutside",hc,pc=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ro=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(pc),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),m=We(t,E=>f(E)),x=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),g=x.indexOf(y),w=d?x.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=w>=g,T=hx(E=>{const N=E.target,j=[...c.branches].some(D=>D.contains(N));!k||j||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),C=px(E=>{const N=E.target;[...c.branches].some(D=>D.contains(N))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return ax(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&&(hc=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),mc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=hc)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),mc())},[d,c]),v.useEffect(()=>{const E=()=>p({});return document.addEventListener(mi,E),()=>document.removeEventListener(mi,E)},[]),u.jsx(Re.div,{...l,ref:m,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:pe(e.onFocusCapture,C.onFocusCapture),onBlurCapture:pe(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:pe(e.onPointerDownCapture,T.onPointerDownCapture)})});Ro.displayName=lx;var dx="DismissableLayerBranch",fx=v.forwardRef((e,t)=>{const n=v.useContext(pc),r=v.useRef(null),o=We(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Re.div,{...e,ref:o})});fx.displayName=dx;function hx(e,t=globalThis==null?void 0:globalThis.document){const n=It(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){gc(cx,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 px(e,t=globalThis==null?void 0:globalThis.document){const n=It(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&gc(ux,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 mc(){const e=new CustomEvent(mi);document.dispatchEvent(e)}function gc(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?fc(o,s):o.dispatchEvent(s)}var gi=0;function xi(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??xc()),document.body.insertAdjacentElement("beforeend",e[1]??xc()),gi++,()=>{gi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),gi--}},[])}function xc(){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 yi="focusScope.autoFocusOnMount",vi="focusScope.autoFocusOnUnmount",yc={bubbles:!1,cancelable:!0},mx="FocusScope",Po=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=It(o),d=It(s),f=v.useRef(null),h=We(t,x=>l(x)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let x=function(S){if(p.paused||!a)return;const k=S.target;a.contains(k)?f.current=k:_n(f.current,{select:!0})},y=function(S){if(p.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||_n(f.current,{select:!0}))},g=function(S){if(document.activeElement===document.body)for(const T of S)T.removedNodes.length>0&&_n(a)};document.addEventListener("focusin",x),document.addEventListener("focusout",y);const w=new MutationObserver(g);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){bc.add(p);const x=document.activeElement;if(!a.contains(x)){const g=new CustomEvent(yi,yc);a.addEventListener(yi,c),a.dispatchEvent(g),g.defaultPrevented||(gx(bx(vc(a)),{select:!0}),document.activeElement===x&&_n(a))}return()=>{a.removeEventListener(yi,c),setTimeout(()=>{const g=new CustomEvent(vi,yc);a.addEventListener(vi,d),a.dispatchEvent(g),g.defaultPrevented||_n(x??document.body,{select:!0}),a.removeEventListener(vi,d),bc.remove(p)},0)}}},[a,c,d,p]);const m=v.useCallback(x=>{if(!n&&!r||p.paused)return;const y=x.key==="Tab"&&!x.altKey&&!x.ctrlKey&&!x.metaKey,g=document.activeElement;if(y&&g){const w=x.currentTarget,[S,k]=xx(w);S&&k?!x.shiftKey&&g===k?(x.preventDefault(),n&&_n(S,{select:!0})):x.shiftKey&&g===S&&(x.preventDefault(),n&&_n(k,{select:!0})):g===w&&x.preventDefault()}},[n,r,p.paused]);return u.jsx(Re.div,{tabIndex:-1,...i,ref:h,onKeyDown:m})});Po.displayName=mx;function gx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(_n(r,{select:t}),document.activeElement!==n)return}function xx(e){const t=vc(e),n=wc(t,e),r=wc(t.reverse(),e);return[n,r]}function vc(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 wc(e,t){for(const n of e)if(!yx(n,{upTo:t}))return n}function yx(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 vx(e){return e instanceof HTMLInputElement&&"select"in e}function _n(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&vx(e)&&t&&e.select()}}var bc=wx();function wx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Sc(e,t),e.unshift(t)},remove(t){var n;e=Sc(e,t),(n=e[0])==null||n.resume()}}}function Sc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function bx(e){return e.filter(t=>t.tagName!=="A")}var Sx=v[" useId ".trim().toString()]||(()=>{}),Cx=0;function En(e){const[t,n]=v.useState(Sx());return Et(()=>{n(r=>r??String(Cx++))},[e]),t?`radix-${t}`:""}const Tx=["top","right","bottom","left"],Rn=Math.min,Ut=Math.max,Oo=Math.round,Mo=Math.floor,pn=e=>({x:e,y:e}),kx={left:"right",right:"left",bottom:"top",top:"bottom"},Ex={start:"end",end:"start"};function wi(e,t,n){return Ut(e,Rn(t,n))}function In(e,t){return typeof e=="function"?e(t):e}function Nn(e){return e.split("-")[0]}function fr(e){return e.split("-")[1]}function bi(e){return e==="x"?"y":"x"}function Si(e){return e==="y"?"height":"width"}const Ix=new Set(["top","bottom"]);function mn(e){return Ix.has(Nn(e))?"y":"x"}function Ci(e){return bi(mn(e))}function Nx(e,t,n){n===void 0&&(n=!1);const r=fr(e),o=Ci(e),s=Si(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Do(i)),[i,Do(i)]}function Ax(e){const t=Do(e);return[Ti(e),t,Ti(t)]}function Ti(e){return e.replace(/start|end/g,t=>Ex[t])}const Cc=["left","right"],Tc=["right","left"],jx=["top","bottom"],_x=["bottom","top"];function Rx(e,t,n){switch(e){case"top":case"bottom":return n?t?Tc:Cc:t?Cc:Tc;case"left":case"right":return t?jx:_x;default:return[]}}function Px(e,t,n,r){const o=fr(e);let s=Rx(Nn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ti)))),s}function Do(e){return e.replace(/left|right|bottom|top/g,t=>kx[t])}function Ox(e){return{top:0,right:0,bottom:0,left:0,...e}}function kc(e){return typeof e!="number"?Ox(e):{top:e,right:e,bottom:e,left:e}}function Lo(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Ec(e,t,n){let{reference:r,floating:o}=e;const s=mn(t),i=Ci(t),a=Si(i),l=Nn(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(fr(t)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const Mx=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=Ec(c,r,l),h=r,p={},m=0;for(let x=0;x<a.length;x++){const{name:y,fn:g}=a[x],{x:w,y:S,data:k,reset:T}=await g({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=S??f,p={...p,[y]:{...p[y],...k}},T&&m<=50&&(m++,typeof T=="object"&&(T.placement&&(h=T.placement),T.rects&&(c=T.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):T.rects),{x:d,y:f}=Ec(c,h,l)),x=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function Or(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=In(t,e),m=kc(p),y=a[h?f==="floating"?"reference":"floating":f],g=Lo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),k=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},T=Lo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(g.top-T.top+m.top)/k.y,bottom:(T.bottom-g.bottom+m.bottom)/k.y,left:(g.left-T.left+m.left)/k.x,right:(T.right-g.right+m.right)/k.x}}const Dx=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=In(e,t)||{};if(c==null)return{};const f=kc(d),h={x:n,y:r},p=Ci(o),m=Si(p),x=await i.getDimensions(c),y=p==="y",g=y?"top":"left",w=y?"bottom":"right",S=y?"clientHeight":"clientWidth",k=s.reference[m]+s.reference[p]-h[p]-s.floating[m],T=h[p]-s.reference[p],C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=C?C[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(C)))&&(E=a.floating[S]||s.floating[m]);const N=k/2-T/2,j=E/2-x[m]/2-1,D=Rn(f[g],j),P=Rn(f[w],j),M=D,F=E-x[m]-P,A=E/2-x[m]/2+N,z=wi(M,A,F),_=!l.arrow&&fr(o)!=null&&A!==z&&s.reference[m]/2-(A<M?D:P)-x[m]/2<0,J=_?A<M?A-M:A-F:0;return{[p]:h[p]+J,data:{[p]:z,centerOffset:A-z-J,..._&&{alignmentOffset:J}},reset:_}}}),Lx=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:x=!0,...y}=In(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const g=Nn(o),w=mn(a),S=Nn(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),T=h||(S||!x?[Do(a)]:Ax(a)),C=m!=="none";!h&&C&&T.push(...Px(a,x,m,k));const E=[a,...T],N=await Or(t,y),j=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&j.push(N[g]),f){const A=Nx(o,i,k);j.push(N[A[0]],N[A[1]])}if(D=[...D,{placement:o,overflows:j}],!j.every(A=>A<=0)){var P,M;const A=(((P=s.flip)==null?void 0:P.index)||0)+1,z=E[A];if(z&&(!(f==="alignment"?w!==mn(z):!1)||D.every($=>mn($.placement)===w?$.overflows[0]>0:!0)))return{data:{index:A,overflows:D},reset:{placement:z}};let _=(M=D.filter(J=>J.overflows[0]<=0).sort((J,$)=>J.overflows[1]-$.overflows[1])[0])==null?void 0:M.placement;if(!_)switch(p){case"bestFit":{var F;const J=(F=D.filter($=>{if(C){const R=mn($.placement);return R===w||R==="y"}return!0}).map($=>[$.placement,$.overflows.filter(R=>R>0).reduce((R,Z)=>R+Z,0)]).sort(($,R)=>$[1]-R[1])[0])==null?void 0:F[0];J&&(_=J);break}case"initialPlacement":_=a;break}if(o!==_)return{reset:{placement:_}}}return{}}}};function Ic(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Nc(e){return Tx.some(t=>e[t]>=0)}const $x=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=In(e,t);switch(r){case"referenceHidden":{const s=await Or(t,{...o,elementContext:"reference"}),i=Ic(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Nc(i)}}}case"escaped":{const s=await Or(t,{...o,altBoundary:!0}),i=Ic(s,n.floating);return{data:{escapedOffsets:i,escaped:Nc(i)}}}default:return{}}}}},Ac=new Set(["left","top"]);async function Fx(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Nn(n),a=fr(n),l=mn(n)==="y",c=Ac.has(i)?-1:1,d=s&&l?-1:1,f=In(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}const zx=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await Fx(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},Bx=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x:g,y:w}=y;return{x:g,y:w}}},...l}=In(e,t),c={x:n,y:r},d=await Or(t,l),f=mn(Nn(o)),h=bi(f);let p=c[h],m=c[f];if(s){const y=h==="y"?"top":"left",g=h==="y"?"bottom":"right",w=p+d[y],S=p-d[g];p=wi(w,p,S)}if(i){const y=f==="y"?"top":"left",g=f==="y"?"bottom":"right",w=m+d[y],S=m-d[g];m=wi(w,m,S)}const x=a.fn({...t,[h]:p,[f]:m});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[h]:s,[f]:i}}}}}},Hx=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=In(e,t),d={x:n,y:r},f=mn(o),h=bi(f);let p=d[h],m=d[f];const x=In(a,t),y=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(l){const S=h==="y"?"height":"width",k=s.reference[h]-s.floating[S]+y.mainAxis,T=s.reference[h]+s.reference[S]-y.mainAxis;p<k?p=k:p>T&&(p=T)}if(c){var g,w;const S=h==="y"?"width":"height",k=Ac.has(Nn(o)),T=s.reference[f]-s.floating[S]+(k&&((g=i.offset)==null?void 0:g[f])||0)+(k?0:y.crossAxis),C=s.reference[f]+s.reference[S]+(k?0:((w=i.offset)==null?void 0:w[f])||0)-(k?y.crossAxis:0);m<T?m=T:m>C&&(m=C)}return{[h]:p,[f]:m}}}},Ux=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=In(e,t),d=await Or(t,c),f=Nn(o),h=fr(o),p=mn(o)==="y",{width:m,height:x}=s.floating;let y,g;f==="top"||f==="bottom"?(y=f,g=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(g=f,y=h==="end"?"top":"bottom");const w=x-d.top-d.bottom,S=m-d.left-d.right,k=Rn(x-d[y],w),T=Rn(m-d[g],S),C=!t.middlewareData.shift;let E=k,N=T;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(N=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),C&&!h){const D=Ut(d.left,0),P=Ut(d.right,0),M=Ut(d.top,0),F=Ut(d.bottom,0);p?N=m-2*(D!==0||P!==0?D+P:Ut(d.left,d.right)):E=x-2*(M!==0||F!==0?M+F:Ut(d.top,d.bottom))}await l({...t,availableWidth:N,availableHeight:E});const j=await i.getDimensions(a.floating);return m!==j.width||x!==j.height?{reset:{rects:!0}}:{}}}};function $o(){return typeof window<"u"}function hr(e){return jc(e)?(e.nodeName||"").toLowerCase():"#document"}function Wt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function gn(e){var t;return(t=(jc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function jc(e){return $o()?e instanceof Node||e instanceof Wt(e).Node:!1}function sn(e){return $o()?e instanceof Element||e instanceof Wt(e).Element:!1}function xn(e){return $o()?e instanceof HTMLElement||e instanceof Wt(e).HTMLElement:!1}function _c(e){return!$o()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Wt(e).ShadowRoot}const Wx=new Set(["inline","contents"]);function Mr(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=an(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Wx.has(o)}const Vx=new Set(["table","td","th"]);function Kx(e){return Vx.has(hr(e))}const qx=[":popover-open",":modal"];function Fo(e){return qx.some(t=>{try{return e.matches(t)}catch{return!1}})}const Gx=["transform","translate","scale","rotate","perspective"],Yx=["transform","translate","scale","rotate","perspective","filter"],Xx=["paint","layout","strict","content"];function ki(e){const t=Ei(),n=sn(e)?an(e):e;return Gx.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Yx.some(r=>(n.willChange||"").includes(r))||Xx.some(r=>(n.contain||"").includes(r))}function Jx(e){let t=Pn(e);for(;xn(t)&&!pr(t);){if(ki(t))return t;if(Fo(t))return null;t=Pn(t)}return null}function Ei(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Zx=new Set(["html","body","#document"]);function pr(e){return Zx.has(hr(e))}function an(e){return Wt(e).getComputedStyle(e)}function zo(e){return sn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Pn(e){if(hr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||_c(e)&&e.host||gn(e);return _c(t)?t.host:t}function Rc(e){const t=Pn(e);return pr(t)?e.ownerDocument?e.ownerDocument.body:e.body:xn(t)&&Mr(t)?t:Rc(t)}function Dr(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Rc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Wt(o);if(s){const a=Ii(i);return t.concat(i,i.visualViewport||[],Mr(o)?o:[],a&&n?Dr(a):[])}return t.concat(o,Dr(o,[],n))}function Ii(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Pc(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=xn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Oo(n)!==s||Oo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Ni(e){return sn(e)?e:e.contextElement}function mr(e){const t=Ni(e);if(!xn(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=Pc(t);let i=(s?Oo(n.width):n.width)/r,a=(s?Oo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Qx=pn(0);function Oc(e){const t=Wt(e);return!Ei()||!t.visualViewport?Qx:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function ey(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Wt(e)?!1:t}function qn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Ni(e);let i=pn(1);t&&(r?sn(r)&&(i=mr(r)):i=mr(e));const a=ey(s,n,r)?Oc(s):pn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const h=Wt(s),p=r&&sn(r)?Wt(r):r;let m=h,x=Ii(m);for(;x&&r&&p!==m;){const y=mr(x),g=x.getBoundingClientRect(),w=an(x),S=g.left+(x.clientLeft+parseFloat(w.paddingLeft))*y.x,k=g.top+(x.clientTop+parseFloat(w.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=S,c+=k,m=Wt(x),x=Ii(m)}}return Lo({width:d,height:f,x:l,y:c})}function Bo(e,t){const n=zo(e).scrollLeft;return t?t.left+n:qn(gn(e)).left+n}function Mc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Bo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function ty(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=gn(r),a=t?Fo(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=pn(1);const d=pn(0),f=xn(r);if((f||!f&&!s)&&((hr(r)!=="body"||Mr(i))&&(l=zo(r)),xn(r))){const p=qn(r);c=mr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?Mc(i,l):pn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}}function ny(e){return Array.from(e.getClientRects())}function ry(e){const t=gn(e),n=zo(e),r=e.ownerDocument.body,o=Ut(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ut(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Bo(e);const a=-n.scrollTop;return an(r).direction==="rtl"&&(i+=Ut(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Dc=25;function oy(e,t){const n=Wt(e),r=gn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=Ei();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Bo(r);if(c<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,m=Math.abs(r.clientWidth-f.clientWidth-p);m<=Dc&&(s-=m)}else c<=Dc&&(s+=c);return{width:s,height:i,x:a,y:l}}const sy=new Set(["absolute","fixed"]);function iy(e,t){const n=qn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=xn(e)?mr(e):pn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Lc(e,t,n){let r;if(t==="viewport")r=oy(e,n);else if(t==="document")r=ry(gn(e));else if(sn(t))r=iy(t,n);else{const o=Oc(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Lo(r)}function $c(e,t){const n=Pn(e);return n===t||!sn(n)||pr(n)?!1:an(n).position==="fixed"||$c(n,t)}function ay(e,t){const n=t.get(e);if(n)return n;let r=Dr(e,[],!1).filter(a=>sn(a)&&hr(a)!=="body"),o=null;const s=an(e).position==="fixed";let i=s?Pn(e):e;for(;sn(i)&&!pr(i);){const a=an(i),l=ki(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&sy.has(o.position)||Mr(i)&&!l&&$c(e,i))?r=r.filter(d=>d!==i):o=a,i=Pn(i)}return t.set(e,r),r}function ly(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Fo(t)?[]:ay(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Lc(t,d,o);return c.top=Ut(f.top,c.top),c.right=Rn(f.right,c.right),c.bottom=Rn(f.bottom,c.bottom),c.left=Ut(f.left,c.left),c},Lc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function cy(e){const{width:t,height:n}=Pc(e);return{width:t,height:n}}function uy(e,t,n){const r=xn(t),o=gn(t),s=n==="fixed",i=qn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=pn(0);function c(){l.x=Bo(o)}if(r||!r&&!s)if((hr(t)!=="body"||Mr(o))&&(a=zo(t)),r){const p=qn(t,!0,s,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Mc(o,a):pn(0),f=i.left+a.scrollLeft-l.x-d.x,h=i.top+a.scrollTop-l.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function Ai(e){return an(e).position==="static"}function Fc(e,t){if(!xn(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return gn(e)===n&&(n=n.ownerDocument.body),n}function zc(e,t){const n=Wt(e);if(Fo(e))return n;if(!xn(e)){let o=Pn(e);for(;o&&!pr(o);){if(sn(o)&&!Ai(o))return o;o=Pn(o)}return n}let r=Fc(e,t);for(;r&&Kx(r)&&Ai(r);)r=Fc(r,t);return r&&pr(r)&&Ai(r)&&!ki(r)?n:r||Jx(e)||n}const dy=async function(e){const t=this.getOffsetParent||zc,n=this.getDimensions,r=await n(e.floating);return{reference:uy(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function fy(e){return an(e).direction==="rtl"}const hy={convertOffsetParentRelativeRectToViewportRelativeRect:ty,getDocumentElement:gn,getClippingRect:ly,getOffsetParent:zc,getElementRects:dy,getClientRects:ny,getDimensions:cy,getScale:mr,isElement:sn,isRTL:fy};function Bc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function py(e,t){let n=null,r;const o=gn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=c;if(a||t(),!h||!p)return;const m=Mo(f),x=Mo(o.clientWidth-(d+h)),y=Mo(o.clientHeight-(f+p)),g=Mo(d),S={rootMargin:-m+"px "+-x+"px "+-y+"px "+-g+"px",threshold:Ut(0,Rn(1,l))||1};let k=!0;function T(C){const E=C[0].intersectionRatio;if(E!==l){if(!k)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Bc(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(T,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(T,S)}n.observe(e)}return i(!0),s}function my(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=Ni(e),d=o||s?[...c?Dr(c):[],...Dr(t)]:[];d.forEach(g=>{o&&g.addEventListener("scroll",n,{passive:!0}),s&&g.addEventListener("resize",n)});const f=c&&a?py(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(g=>{let[w]=g;w&&w.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var S;(S=p)==null||S.observe(t)})),n()}),c&&!l&&p.observe(c),p.observe(t));let m,x=l?qn(e):null;l&&y();function y(){const g=qn(e);x&&!Bc(x,g)&&n(),x=g,m=requestAnimationFrame(y)}return n(),()=>{var g;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(g=p)==null||g.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const gy=zx,xy=Bx,yy=Lx,vy=Ux,wy=$x,Hc=Dx,by=Hx,Sy=(e,t,n)=>{const r=new Map,o={platform:hy,...n},s={...o.platform,_c:r};return Mx(e,t,{...o,platform:s})};var Cy=typeof document<"u",Ty=function(){},Ho=Cy?b.useLayoutEffect:Ty;function Uo(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Uo(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!Uo(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Uc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Wc(e,t){const n=Uc(e);return Math.round(t*n)/n}function ji(e){const t=v.useRef(e);return Ho(()=>{t.current=e}),t}function ky(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=v.useState(r);Uo(h,r)||p(r);const[m,x]=v.useState(null),[y,g]=v.useState(null),w=v.useCallback($=>{$!==C.current&&(C.current=$,x($))},[]),S=v.useCallback($=>{$!==E.current&&(E.current=$,g($))},[]),k=s||m,T=i||y,C=v.useRef(null),E=v.useRef(null),N=v.useRef(d),j=l!=null,D=ji(l),P=ji(o),M=ji(c),F=v.useCallback(()=>{if(!C.current||!E.current)return;const $={placement:t,strategy:n,middleware:h};P.current&&($.platform=P.current),Sy(C.current,E.current,$).then(R=>{const Z={...R,isPositioned:M.current!==!1};A.current&&!Uo(N.current,Z)&&(N.current=Z,fo.flushSync(()=>{f(Z)}))})},[h,t,n,P,M]);Ho(()=>{c===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,f($=>({...$,isPositioned:!1})))},[c]);const A=v.useRef(!1);Ho(()=>(A.current=!0,()=>{A.current=!1}),[]),Ho(()=>{if(k&&(C.current=k),T&&(E.current=T),k&&T){if(D.current)return D.current(k,T,F);F()}},[k,T,F,D,j]);const z=v.useMemo(()=>({reference:C,floating:E,setReference:w,setFloating:S}),[w,S]),_=v.useMemo(()=>({reference:k,floating:T}),[k,T]),J=v.useMemo(()=>{const $={position:n,left:0,top:0};if(!_.floating)return $;const R=Wc(_.floating,d.x),Z=Wc(_.floating,d.y);return a?{...$,transform:"translate("+R+"px, "+Z+"px)",...Uc(_.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:R,top:Z}},[n,a,_.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:F,refs:z,elements:_,floatingStyles:J}),[d,F,z,_,J])}const Ey=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Hc({element:r.current,padding:o}).fn(n):{}:r?Hc({element:r,padding:o}).fn(n):{}}}},Iy=(e,t)=>({...gy(e),options:[e,t]}),Ny=(e,t)=>({...xy(e),options:[e,t]}),Ay=(e,t)=>({...by(e),options:[e,t]}),jy=(e,t)=>({...yy(e),options:[e,t]}),_y=(e,t)=>({...vy(e),options:[e,t]}),Ry=(e,t)=>({...wy(e),options:[e,t]}),Py=(e,t)=>({...Ey(e),options:[e,t]});var Oy="Arrow",Vc=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Re.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Vc.displayName=Oy;var My=Vc;function Kc(e){const[t,n]=v.useState(void 0);return Et(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var _i="Popper",[qc,Wo]=kn(_i),[Dy,Gc]=qc(_i),Yc=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(Dy,{scope:t,anchor:r,onAnchorChange:o,children:n})};Yc.displayName=_i;var Xc="PopperAnchor",Jc=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Gc(Xc,n),i=v.useRef(null),a=We(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(Re.div,{...o,ref:a})});Jc.displayName=Xc;var Ri="PopperContent",[Ly,$y]=qc(Ri),Zc=v.forwardRef((e,t)=>{var X,L,U,K,se,re;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:m,...x}=e,y=Gc(Ri,n),[g,w]=v.useState(null),S=We(t,Oe=>w(Oe)),[k,T]=v.useState(null),C=Kc(k),E=(C==null?void 0:C.width)??0,N=(C==null?void 0:C.height)??0,j=r+(s!=="center"?"-"+s:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},P=Array.isArray(c)?c:[c],M=P.length>0,F={padding:D,boundary:P.filter(zy),altBoundary:M},{refs:A,floatingStyles:z,placement:_,isPositioned:J,middlewareData:$}=ky({strategy:"fixed",placement:j,whileElementsMounted:(...Oe)=>my(...Oe,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[Iy({mainAxis:o+N,alignmentAxis:i}),l&&Ny({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Ay():void 0,...F}),l&&jy({...F}),_y({...F,apply:({elements:Oe,rects:qe,availableWidth:Ge,availableHeight:oe})=>{const{width:le,height:De}=qe.reference,Be=Oe.floating.style;Be.setProperty("--radix-popper-available-width",`${Ge}px`),Be.setProperty("--radix-popper-available-height",`${oe}px`),Be.setProperty("--radix-popper-anchor-width",`${le}px`),Be.setProperty("--radix-popper-anchor-height",`${De}px`)}}),k&&Py({element:k,padding:a}),By({arrowWidth:E,arrowHeight:N}),h&&Ry({strategy:"referenceHidden",...F})]}),[R,Z]=tu(_),Y=It(m);Et(()=>{J&&(Y==null||Y())},[J,Y]);const me=(X=$.arrow)==null?void 0:X.x,Te=(L=$.arrow)==null?void 0:L.y,je=((U=$.arrow)==null?void 0:U.centerOffset)!==0,[G,ne]=v.useState();return Et(()=>{g&&ne(window.getComputedStyle(g).zIndex)},[g]),u.jsx("div",{ref:A.setFloating,"data-radix-popper-content-wrapper":"",style:{...z,transform:J?z.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:G,"--radix-popper-transform-origin":[(K=$.transformOrigin)==null?void 0:K.x,(se=$.transformOrigin)==null?void 0:se.y].join(" "),...((re=$.hide)==null?void 0:re.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(Ly,{scope:n,placedSide:R,onArrowChange:T,arrowX:me,arrowY:Te,shouldHideArrow:je,children:u.jsx(Re.div,{"data-side":R,"data-align":Z,...x,ref:S,style:{...x.style,animation:J?void 0:"none"}})})})});Zc.displayName=Ri;var Qc="PopperArrow",Fy={top:"bottom",right:"left",bottom:"top",left:"right"},eu=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=$y(Qc,r),i=Fy[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(My,{...o,ref:n,style:{...o.style,display:"block"}})})});eu.displayName=Qc;function zy(e){return e!==null}var By=e=>({name:"transformOrigin",options:e,fn(t){var y,g,w;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=tu(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((g=o.arrow)==null?void 0:g.x)??0)+a/2,p=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let m="",x="";return c==="bottom"?(m=i?f:`${h}px`,x=`${-l}px`):c==="top"?(m=i?f:`${h}px`,x=`${r.floating.height+l}px`):c==="right"?(m=`${-l}px`,x=i?f:`${p}px`):c==="left"&&(m=`${r.floating.width+l}px`,x=i?f:`${p}px`),{data:{x:m,y:x}}}});function tu(e){const[t,n="center"]=e.split("-");return[t,n]}var nu=Yc,ru=Jc,ou=Zc,su=eu,Hy="Portal",Vo=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Et(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ks.createPortal(u.jsx(Re.div,{...r,ref:t}),i):null});Vo.displayName=Hy;function Uy(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Xt=e=>{const{present:t,children:n}=e,r=Wy(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=We(r.ref,Vy(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Xt.displayName="Presence";function Wy(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Uy(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Ko(r.current);s.current=a==="mounted"?c:"none"},[a]),Et(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=Ko(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]),Et(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const x=Ko(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&x&&(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=Ko(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 Ko(e){return(e==null?void 0:e.animationName)||"none"}function Vy(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 Pi="rovingFocusGroup.onEntryFocus",Ky={bubbles:!1,cancelable:!0},Lr="RovingFocusGroup",[Oi,iu,qy]=pi(Lr),[Gy,au]=kn(Lr,[qy]),[Yy,Xy]=Gy(Lr),lu=v.forwardRef((e,t)=>u.jsx(Oi.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Oi.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Jy,{...e,ref:t})})}));lu.displayName=Lr;var Jy=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,h=v.useRef(null),p=We(t,h),m=_o(s),[x,y]=dr({prop:i,defaultProp:a??null,onChange:l,caller:Lr}),[g,w]=v.useState(!1),S=It(c),k=iu(n),T=v.useRef(!1),[C,E]=v.useState(0);return v.useEffect(()=>{const N=h.current;if(N)return N.addEventListener(Pi,S),()=>N.removeEventListener(Pi,S)},[S]),u.jsx(Yy,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:x,onItemFocus:v.useCallback(N=>y(N),[y]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(N=>N+1),[]),onFocusableItemRemove:v.useCallback(()=>E(N=>N-1),[]),children:u.jsx(Re.div,{tabIndex:g||C===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:pe(e.onMouseDown,()=>{T.current=!0}),onFocus:pe(e.onFocus,N=>{const j=!T.current;if(N.target===N.currentTarget&&j&&!g){const D=new CustomEvent(Pi,Ky);if(N.currentTarget.dispatchEvent(D),!D.defaultPrevented){const P=k().filter(_=>_.focusable),M=P.find(_=>_.active),F=P.find(_=>_.id===x),z=[M,F,...P].filter(Boolean).map(_=>_.ref.current);du(z,d)}}T.current=!1}),onBlur:pe(e.onBlur,()=>w(!1))})})}),cu="RovingFocusGroupItem",uu=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=En(),c=s||l,d=Xy(cu,n),f=d.currentTabStopId===c,h=iu(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:x}=d;return v.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),u.jsx(Oi.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Re.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:pe(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:pe(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:pe(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const g=ev(y,d.orientation,d.dir);if(g!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let S=h().filter(k=>k.focusable).map(k=>k.ref.current);if(g==="last")S.reverse();else if(g==="prev"||g==="next"){g==="prev"&&S.reverse();const k=S.indexOf(y.currentTarget);S=d.loop?tv(S,k+1):S.slice(k+1)}setTimeout(()=>du(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:x!=null}):i})})});uu.displayName=cu;var Zy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Qy(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ev(e,t,n){const r=Qy(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Zy[r]}function du(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function tv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var nv=lu,rv=uu,ov=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},gr=new WeakMap,qo=new WeakMap,Go={},Mi=0,fu=function(e){return e&&(e.host||fu(e.parentNode))},sv=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=fu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},iv=function(e,t,n,r){var o=sv(t,Array.isArray(e)?e:[e]);Go[n]||(Go[n]=new WeakMap);var s=Go[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))d(h);else try{var p=h.getAttribute(r),m=p!==null&&p!=="false",x=(gr.get(h)||0)+1,y=(s.get(h)||0)+1;gr.set(h,x),s.set(h,y),i.push(h),x===1&&m&&qo.set(h,!0),y===1&&h.setAttribute(n,"true"),m||h.setAttribute(r,"true")}catch(g){console.error("aria-hidden: cannot operate on ",h,g)}})};return d(t),a.clear(),Mi++,function(){i.forEach(function(f){var h=gr.get(f)-1,p=s.get(f)-1;gr.set(f,h),s.set(f,p),h||(qo.has(f)||f.removeAttribute(r),qo.delete(f)),p||f.removeAttribute(n)}),Mi--,Mi||(gr=new WeakMap,gr=new WeakMap,qo=new WeakMap,Go={})}},Di=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=ov(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),iv(r,o,n,"aria-hidden")):function(){return null}},yn=function(){return yn=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},yn.apply(this,arguments)};function hu(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 av(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 Yo="right-scroll-bar-position",Xo="width-before-scroll-bar",lv="with-scroll-bars-hidden",cv="--removed-body-scroll-bar-size";function Li(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function uv(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 dv=typeof window<"u"?v.useLayoutEffect:v.useEffect,pu=new WeakMap;function fv(e,t){var n=uv(null,function(r){return e.forEach(function(o){return Li(o,r)})});return dv(function(){var r=pu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Li(a,null)}),s.forEach(function(a){o.has(a)||Li(a,i)})}pu.set(n,e)},[e]),n}function hv(e){return e}function pv(e,t){t===void 0&&(t=hv);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 mv(e){e===void 0&&(e={});var t=pv(null);return t.options=yn({async:!0,ssr:!1},e),t}var mu=function(e){var t=e.sideCar,n=hu(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,yn({},n))};mu.isSideCarExport=!0;function gv(e,t){return e.useMedium(t),mu}var gu=mv(),$i=function(){},Jo=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:$i,onWheelCapture:$i,onTouchMoveCapture:$i}),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,x=e.inert,y=e.allowPinchZoom,g=e.as,w=g===void 0?"div":g,S=e.gapMode,k=hu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),T=h,C=fv([n,t]),E=yn(yn({},k),o);return v.createElement(v.Fragment,null,d&&v.createElement(T,{sideCar:gu,removeScrollBar:c,shards:f,noRelative:p,noIsolation:m,inert:x,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),yn(yn({},E),{ref:C})):v.createElement(w,yn({},E,{className:l,ref:C}),a))});Jo.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Jo.classNames={fullWidth:Xo,zeroRight:Yo};var xv=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function yv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=xv();return t&&e.setAttribute("nonce",t),e}function vv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function wv(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var bv=function(){var e=0,t=null;return{add:function(n){e==0&&(t=yv())&&(vv(t,n),wv(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Sv=function(){var e=bv();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},xu=function(){var e=Sv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Cv={left:0,top:0,right:0,gap:0},Fi=function(e){return parseInt(e||"",10)||0},Tv=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[Fi(n),Fi(r),Fi(o)]},kv=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Cv;var t=Tv(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])}},Ev=xu(),xr="data-scroll-locked",Iv=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(lv,` {
|
|
40
40
|
overflow: hidden `).concat(r,`;
|
|
41
41
|
padding-right: `).concat(a,"px ").concat(r,`;
|
package/package.json
CHANGED