@botuyo/chat-widget-standalone 1.5.0 → 1.5.2
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/{AudioPlayer-DPt7qBNl.js → AudioPlayer-C-4kk-Q-.js} +2 -2
- package/dist/{AudioPlayer-DPt7qBNl.js.map → AudioPlayer-C-4kk-Q-.js.map} +1 -1
- package/dist/{Gallery-BZR48TKA.js → Gallery-BbQ2FJOf.js} +2 -2
- package/dist/{Gallery-BZR48TKA.js.map → Gallery-BbQ2FJOf.js.map} +1 -1
- package/dist/botuyo-chat.es.js +1 -1
- package/dist/botuyo-chat.umd.js +1 -1
- package/dist/botuyo-chat.umd.js.map +1 -1
- package/dist/src/chat-widget/components/MessageBubble.d.ts.map +1 -1
- package/dist/src/chat-widget/components/MessageList.d.ts.map +1 -1
- package/dist/src/chat-widget/hooks/useChatState.d.ts.map +1 -1
- package/dist/{standalone-COoohdwQ.js → standalone-D5pCeR_m.js} +35 -33
- package/dist/{standalone-COoohdwQ.js.map → standalone-D5pCeR_m.js.map} +1 -1
- package/dist/stats-umd.html +1 -1
- package/dist/stats.html +1 -1
- package/package.json +1 -1
|
@@ -26,17 +26,17 @@ return y("div",{className:"w-full my-2 rounded-2xl border shadow-sm overflow-hid
|
|
|
26
26
|
/* @__PURE__ */y("button",{type:"button",onClick:()=>{d||(c("cancelled"),o?.(e.proposalId))},"data-testid":"tool-proposal-cancel",className:"flex-1 flex items-center justify-center gap-1.5 py-3 text-xs font-bold transition-colors hover:bg-muted/50 active:scale-[0.98]",style:{color:"hsl(var(--muted-foreground))"},children:[
|
|
27
27
|
/* @__PURE__ */b(ce,{size:14,strokeWidth:2.5}),a("cancel")]}),
|
|
28
28
|
/* @__PURE__ */y("button",{type:"button",onClick:()=>{p||(c("confirmed"),r?.(e.proposalId))},disabled:p,"data-testid":"tool-proposal-confirm",className:"flex-1 flex items-center justify-center gap-1.5 py-3 text-xs font-black text-white transition-all active:scale-[0.98] disabled:opacity-40 disabled:cursor-not-allowed disabled:active:scale-100",style:{backgroundColor:s},children:[
|
|
29
|
-
/* @__PURE__ */b(q,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Wl=p(()=>import("./AudioPlayer-
|
|
29
|
+
/* @__PURE__ */b(q,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Wl=p(()=>import("./AudioPlayer-C-4kk-Q-.js").then(e=>({default:e.AudioPlayer}))),Hl=p(()=>import("./Gallery-BbQ2FJOf.js").then(e=>({default:e.Gallery})));function Zl({message:e,brandColor:t,onButtonClick:n}){const[r,o]=i(e.selectedId||null);/* @__PURE__ */
|
|
30
30
|
return y("div",{className:"space-y-3",children:[
|
|
31
31
|
/* @__PURE__ */b("div",{className:At("prose prose-sm max-w-none break-words leading-relaxed dark:prose-invert text-foreground"),children:/* @__PURE__ */b(Fa,{remarkPlugins:[Ol],rehypePlugins:[[Ul,{tagNames:["p","strong","em","br","span"],attributes:{}}]],components:{p:({children:e})=>/* @__PURE__ */b("p",{className:"mb-0 last:mb-0",children:e})},children:e.content})}),
|
|
32
32
|
/* @__PURE__ */b("div",{className:"flex flex-col gap-2",children:e.buttons.map((i,a)=>{const s=r===i.id;/* @__PURE__ */
|
|
33
33
|
return b("button",{type:"button",onClick:()=>(t=>{r||(o(t.id),n?.(t.label,e))})(i),disabled:null!==r,className:At("w-full text-left px-4 py-3 rounded-xl border text-sm font-semibold","transition-all duration-200 cursor-pointer",s?"scale-[0.98] ring-2 shadow-md":null===r||s?"hover:scale-[1.02] hover:shadow-md active:scale-[0.97]":"opacity-40 cursor-default"),style:{backgroundColor:s?`${t}15`:"hsl(var(--muted) / 0.5)",borderColor:s?t:"hsl(var(--border))",color:s?t:"hsl(var(--foreground))",...s?{ringColor:t}:{}},children:/* @__PURE__ */y("span",{className:"flex items-center gap-3",children:[
|
|
34
34
|
/* @__PURE__ */b("span",{className:"flex items-center justify-center w-6 h-6 rounded-full text-xs font-black shrink-0",style:{backgroundColor:s?t:"hsl(var(--muted))",color:s?"white":"hsl(var(--muted-foreground))"},children:String.fromCharCode(65+a)}),
|
|
35
|
-
/* @__PURE__ */b("span",{children:i.label})]})},i.id)})})]})}const Jl=d(function({message:e,primaryColor:t,botAvatar:n,botName:r="BotUyo",avatars:i,isFirst:a=!0,isLast:s=!0,index:l=0,onButtonClick:c,onProposalAction:d}){const{t:p}=D("extracted"),f="user"===e.sender,m="system"===e.type||"system"===e.sender,g=!f&&!m,w=It({primaryColor:t}),x=function(){const e=o(Pt);return e.enabled&&"none"!==e.messageEntry?{slide:"animate-message-slide",fade:"animate-message-fade",scale:"animate-message-scale",spring:"animate-message-spring"}[e.messageEntry]||"animate-message-spring":""}(),k=u(()=>{if(f)return null;if("text"===e.type){const t=e;if(t.emotion&&i?.[t.emotion])return i[t.emotion]}return n},[e,i,n,f]),_=({href:e,children:t})=>{if(!e)return null;const n=String(t).toLowerCase(),r=n.includes("reservar")||n.includes("ver")||n.includes("pagar"),
|
|
35
|
+
/* @__PURE__ */b("span",{children:i.label})]})},i.id)})})]})}const Jl=d(function({message:e,primaryColor:t,botAvatar:n,botName:r="BotUyo",avatars:i,isFirst:a=!0,isLast:s=!0,index:l=0,onButtonClick:c,onProposalAction:d}){const{t:p}=D("extracted"),f="user"===e.sender,m="system"===e.type||"system"===e.sender,g=!f&&!m,w=It({primaryColor:t}),x=function(){const e=o(Pt);return e.enabled&&"none"!==e.messageEntry?{slide:"animate-message-slide",fade:"animate-message-fade",scale:"animate-message-scale",spring:"animate-message-spring"}[e.messageEntry]||"animate-message-spring":""}(),k=u(()=>{if(f)return null;if("text"===e.type){const t=e;if(t.emotion&&i?.[t.emotion])return i[t.emotion]}return n},[e,i,n,f]),_=({href:e,children:t})=>{if(!e)return null;const n=String(t).toLowerCase(),r=String(e).startsWith("mailto:"),o=String(e).startsWith("tel:"),i=!r&&!o&&(n.includes("reservar")||n.includes("ver")||n.includes("pagar")),a=e.includes("maps.google")||e.includes("goo.gl")||e.includes("google.com/maps");let s=!1;try{s=new URL(e,window.location.origin).hostname===window.location.hostname}catch{}const l=s?t=>{t.preventDefault(),window.location.href=e}:void 0,c=s?void 0:"_blank",u=s?void 0:"noopener noreferrer";return a?/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"block my-2 no-underline group",children:/* @__PURE__ */y("span",{className:"flex items-center gap-3 p-3 border rounded-xl shadow-sm group-hover:border-primary/30 transition-all",style:{backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))"},children:[
|
|
36
36
|
/* @__PURE__ */b("span",{className:"flex-shrink-0 p-2 rounded-full",style:{backgroundColor:`${w}1a`,color:w},children:/* @__PURE__ */b(Y,{size:16,strokeWidth:2.5})}),
|
|
37
37
|
/* @__PURE__ */b("span",{className:"flex flex-col min-w-0 flex-1 text-[11px] font-bold text-foreground leading-tight uppercase tracking-tight",children:p("ver_ubicacion")}),
|
|
38
|
-
/* @__PURE__ */b(W,{size:12,className:"text-muted-foreground/40 group-hover:text-primary"})]})}):
|
|
39
|
-
/* @__PURE__ */b(B,{size:14})]}):/* @__PURE__ */b("a",{href:e,target:
|
|
38
|
+
/* @__PURE__ */b(W,{size:12,className:"text-muted-foreground/40 group-hover:text-primary"})]})}):i?/* @__PURE__ */y("a",{href:e,target:c,rel:u,onClick:l,className:"inline-flex items-center justify-center gap-2 px-4 py-2.5 mt-2 mx-1 text-[11px] font-black w-[calc(100%-0.5rem)] sm:w-auto rounded-xl shadow-md uppercase tracking-widest transition-transform active:scale-95 text-white",style:{backgroundColor:w},children:[t," ",
|
|
39
|
+
/* @__PURE__ */b(B,{size:14})]}):/* @__PURE__ */b("a",{href:e,target:c,rel:u,onClick:l,className:"font-bold underline decoration-primary/30 hover:decoration-primary transition-all break-words",style:{color:f?"inherit":w},children:t})},S=({src:e,alt:t})=>e?/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"my-3 animate-pulse",children:/* @__PURE__ */b("div",{className:"w-full h-48 bg-muted rounded-xl"})}),children:/* @__PURE__ */b(Hl,{images:[{src:e,alt:t}],radius:"rounded-xl"})}):null;return"tool_proposal"===e.type?/* @__PURE__ */b(Vl,{message:e,primaryColor:t,onConfirm:e=>d?.(e,"confirm"),onCancel:e=>d?.(e,"reject")}):m?/* @__PURE__ */b("div",{className:"flex justify-center my-4 animate-in fade-in zoom-in-95 w-full",children:/* @__PURE__ */b("span",{className:"px-3 py-1 border rounded-full text-[9px] font-black uppercase tracking-widest",style:{backgroundColor:"hsl(var(--muted))",borderColor:"hsl(var(--border))",color:"hsl(var(--muted-foreground))"},children:e.content})}):/* @__PURE__ */y("div",{className:At("flex w-full mb-0.5 group",x,f?"justify-end":"justify-start gap-3",a&&"mt-3",s&&"mb-3"),style:{animationDelay:50*l+"ms"},children:[!f&&/* @__PURE__ */b("div",{className:"w-9 shrink-0 flex flex-col justify-end pb-1",children:/* @__PURE__ */b("div",s?{className:"h-9 w-9 rounded-full overflow-hidden border shadow-sm",style:{borderColor:"hsl(var(--border))",backgroundColor:"hsl(var(--background))"},children:k?/* @__PURE__ */b("img",{src:k,alt:r,className:"h-full w-full object-cover"}):/* @__PURE__ */b("div",{className:"h-full w-full flex items-center justify-center text-white text-[10px] font-black uppercase",style:{backgroundColor:w},children:r.charAt(0)})}:{className:"w-9"})}),
|
|
40
40
|
/* @__PURE__ */y("div",{className:At("max-w-[85%] shadow-sm transition-all duration-300 relative",f?"text-primary-foreground":"border",f?At("rounded-[18px]",a&&"rounded-tr-[4px]",!s&&"rounded-br-[4px]",!a&&!s&&"rounded-r-[4px]"):At("rounded-[18px]",a&&"rounded-tl-[4px]",!s&&"rounded-bl-[4px]",!a&&!s&&"rounded-l-[4px]")),style:f?{padding:"var(--spacing-4) var(--spacing-5)",backgroundColor:w,boxShadow:s?`0 8px 20px -6px ${w}33`:"none"}:{padding:"var(--spacing-4) var(--spacing-5)",backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border) / 0.6)",color:"hsl(var(--foreground))"},children:[(()=>{switch(e.type){case"audio":/* @__PURE__ */
|
|
41
41
|
return b(h,{fallback:/* @__PURE__ */y("div",{className:"flex items-center gap-3 py-1 min-w-[200px] animate-pulse",children:[
|
|
42
42
|
/* @__PURE__ */b("div",{className:"w-8 h-8 rounded-full bg-muted"}),
|
|
@@ -52,7 +52,8 @@ return y("a",{href:t.fileUrl,download:t.fileName,target:"_blank",rel:"noopener n
|
|
|
52
52
|
return b(Zl,{message:e,brandColor:w,onButtonClick:c});default:{const t=e.content||"",n=/!\[([^\]]*)\]\(([^)]+)\)/g,r=[];let o;for(;null!==(o=n.exec(t));)r.push({src:o[2],alt:o[1]||"Foto"});const i=r.length>1?t.replace(/!\[[^\]]*\]\([^)]+\)/g,"").replace(/---\s*\n?\s*---/g,"").trim():t;/* @__PURE__ */
|
|
53
53
|
return y(v,{children:[r.length>1&&/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"my-3 animate-pulse",children:/* @__PURE__ */b("div",{className:"w-full h-48 bg-muted rounded-xl"})}),children:/* @__PURE__ */b(Hl,{images:r,radius:"rounded-xl"})}),i&&/* @__PURE__ */b("div",{className:At("prose prose-sm max-w-none break-words leading-relaxed dark:prose-invert",f?"text-primary-foreground prose-p:text-white":"text-foreground"),children:/* @__PURE__ */b(Fa,{remarkPlugins:[Ol],rehypePlugins:[[Ul,{tagNames:["p","a","img","strong","em","ul","ol","li","br","span"],attributes:{a:["href","target","rel"],img:["src","alt"],span:["className"]},protocols:{a:{href:["http","https","mailto","tel"]},img:{src:["http","https","data"]}}}]],components:{a:_,img:S,p:({children:e})=>/* @__PURE__ */b("p",{className:"mb-0 last:mb-0",children:e})},children:i})})]})}}})(),s&&/* @__PURE__ */y("div",{className:At("flex items-center gap-1 mt-1.5 opacity-50 select-none text-[9px]",f?"justify-end":"justify-start"),children:[
|
|
54
54
|
/* @__PURE__ */b("span",{className:"font-bold tabular-nums uppercase tracking-tighter",children:(e=>{const t=new Date(e);return isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})})(e.timestamp)}),f&&/* @__PURE__ */b(U,{className:"h-2.5 w-2.5"})]})]}),g&&s&&"text"===e.type&&e.sources&&/* @__PURE__ */b(ql,{sources:e.sources})]})},(e,t)=>e.message.id===t.message.id&&e.message.timestamp===t.message.timestamp&&e.message.status===t.message.status&&e.primaryColor===t.primaryColor&&e.botAvatar===t.botAvatar&&e.botName===t.botName&&e.isFirst===t.isFirst&&e.isLast===t.isLast&&JSON.stringify(e.styles)===JSON.stringify(t.styles)),Kl=d(function(){/* @__PURE__ */
|
|
55
|
-
return b("div",{style:{display:"flex",alignItems:"center",alignSelf:"flex-start",maxWidth:"85%",animation:"message-fade 0.2s ease-out forwards"},children:/* @__PURE__ */b("div",{style:{backgroundColor:"hsl(var(--card, 0 0% 100%))",border:"1px solid hsl(var(--border, 0 0% 90%))",borderRadius:"18px",borderTopLeftRadius:"4px",padding:"14px 20px",boxShadow:"0 1px 3px rgba(0,0,0,0.06)"},children:/* @__PURE__ */b("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[0,1,2].map(e=>/* @__PURE__ */b("span",{className:"animate-typing-dots",style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:"hsl(var(--primary, 250 84% 54%) / 0.6)",animationDelay:200*e+"ms"}},e))})})})});function Gl(e,t){const n=e.getTime()-t.getTime();return Math.floor(n/1e3/60)}function Yl(e){return new Intl.DateTimeFormat("es-ES",{hour:"2-digit",minute:"2-digit"}).format(e)}const Ql=d(function({messages:e,isTyping:r,welcomeMessage:o="¡Hola! ¿En qué puedo ayudarte?",primaryColor:s,logoUrl:l,botName:c="BotUyo",bubbleStyles:u,avatars:d,onButtonClick:p,onProposalAction:h}){const m=f(null),g=f(null),[v,x]=i(!1),[k,_]=i(!1),S=It({primaryColor:s}),C=e.length>100,E=(z={count:e.length,getScrollElement:()=>g.current,estimateSize:()=>80,overscan:5,enabled:C},function({useFlushSync:e=!0,...n}){const r=t.useReducer(()=>({}),{})[1],o={...n,onChange:(t,o)=>{var i;e&&o?w(r):r(),null==(i=n.onChange)||i.call(n,t,o)}},[i]=t.useState(()=>new on(o));return i.setOptions(o),sn(()=>i._didMount(),[]),sn(()=>i._willUpdate()),i}({observeElementRect:Qt,observeElementOffset:tn,scrollToFn:rn,...z}));var z;a(()=>{x(!0)},[]),a(()=>{if(v&&(e.length>0||r)){const t=setTimeout(()=>{C?E.scrollToIndex(e.length-1,{align:"end",behavior:e.length<=1?"auto":"smooth"}):m.current?.scrollIntoView({behavior:e.length<=1?"auto":"smooth",block:"end"})},100);return()=>clearTimeout(t)}},[e.length,r,v,C,E]);const A=e=>{const t=new Date(e);return isNaN(t.getTime())?"":function(e){return function(e){const t=/* @__PURE__ */new Date;return e.getDate()===t.getDate()&&e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear()}(e)?`Hoy, ${Yl(e)}`:function(e){const t=/* @__PURE__ */new Date;return t.setDate(t.getDate()-1),e.getDate()===t.getDate()&&e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear()}(e)?`Ayer, ${Yl(e)}`:function(e){return new Intl.DateTimeFormat("es-ES",{day:"numeric",month:"long",hour:"2-digit",minute:"2-digit"}).format(e)}(e)}(t)};
|
|
55
|
+
return b("div",{style:{display:"flex",alignItems:"center",alignSelf:"flex-start",maxWidth:"85%",animation:"message-fade 0.2s ease-out forwards"},children:/* @__PURE__ */b("div",{style:{backgroundColor:"hsl(var(--card, 0 0% 100%))",border:"1px solid hsl(var(--border, 0 0% 90%))",borderRadius:"18px",borderTopLeftRadius:"4px",padding:"14px 20px",boxShadow:"0 1px 3px rgba(0,0,0,0.06)"},children:/* @__PURE__ */b("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[0,1,2].map(e=>/* @__PURE__ */b("span",{className:"animate-typing-dots",style:{display:"inline-block",height:"8px",width:"8px",borderRadius:"50%",backgroundColor:"hsl(var(--primary, 250 84% 54%) / 0.6)",animationDelay:200*e+"ms"}},e))})})})});function Gl(e,t){const n=e.getTime()-t.getTime();return Math.floor(n/1e3/60)}function Yl(e){return new Intl.DateTimeFormat("es-ES",{hour:"2-digit",minute:"2-digit"}).format(e)}const Ql=d(function({messages:e,isTyping:r,welcomeMessage:o="¡Hola! ¿En qué puedo ayudarte?",primaryColor:s,logoUrl:l,botName:c="BotUyo",bubbleStyles:u,avatars:d,onButtonClick:p,onProposalAction:h}){const m=f(null),g=f(null),[v,x]=i(!1),[k,_]=i(!1),S=It({primaryColor:s}),C=e.length>100,E=(z={count:e.length,getScrollElement:()=>g.current,estimateSize:()=>80,overscan:5,enabled:C},function({useFlushSync:e=!0,...n}){const r=t.useReducer(()=>({}),{})[1],o={...n,onChange:(t,o)=>{var i;e&&o?w(r):r(),null==(i=n.onChange)||i.call(n,t,o)}},[i]=t.useState(()=>new on(o));return i.setOptions(o),sn(()=>i._didMount(),[]),sn(()=>i._willUpdate()),i}({observeElementRect:Qt,observeElementOffset:tn,scrollToFn:rn,...z}));var z;a(()=>{x(!0)},[]),a(()=>{if(v&&(e.length>0||r)){const t=setTimeout(()=>{C?E.scrollToIndex(e.length-1,{align:"end",behavior:e.length<=1?"auto":"smooth"}):m.current?.scrollIntoView({behavior:e.length<=1?"auto":"smooth",block:"end"})},100);return()=>clearTimeout(t)}},[e.length,r,v,C,E]);const A=e=>{const t=new Date(e);return isNaN(t.getTime())?"":function(e){return function(e){const t=/* @__PURE__ */new Date;return e.getDate()===t.getDate()&&e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear()}(e)?`Hoy, ${Yl(e)}`:function(e){const t=/* @__PURE__ */new Date;return t.setDate(t.getDate()-1),e.getDate()===t.getDate()&&e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear()}(e)?`Ayer, ${Yl(e)}`:function(e){return new Intl.DateTimeFormat("es-ES",{day:"numeric",month:"long",hour:"2-digit",minute:"2-digit"}).format(e)}(e)}(t)};if(!v)/* @__PURE__ */return b("div",{className:"flex-1 bg-background"});if(C)/* @__PURE__ */
|
|
56
|
+
return y("div",{ref:g,className:"flex-1 overflow-y-auto scroll-smooth scrollbar-none",style:{padding:"var(--spacing-5)",scrollbarWidth:"none",msOverflowStyle:"none"},children:[
|
|
56
57
|
/* @__PURE__ */b("div",{style:{height:`${E.getTotalSize()}px`,width:"100%",position:"relative"},children:E.getVirtualItems().map(t=>{const n=e[t.index],r=t.index,o=e[r-1],i=e[r+1],a=o&&Gl(new Date(n.timestamp),new Date(o.timestamp))>15,f=o&&o.sender===n.sender&&Gl(new Date(n.timestamp),new Date(o.timestamp))<5&&!a,m=i&&i.sender===n.sender&&Gl(new Date(i.timestamp),new Date(n.timestamp))<5;/* @__PURE__ */
|
|
57
58
|
return y("div",{style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${t.start}px)`},children:[a&&/* @__PURE__ */b("div",{className:"flex justify-center my-8 animate-in fade-in zoom-in-95",children:/* @__PURE__ */b("span",{className:"px-4 py-1.5 bg-muted/40 backdrop-blur-md rounded-full text-[10px] font-black text-muted-foreground uppercase tracking-[0.2em] border border-border/50 shadow-sm",children:A(n.timestamp)})}),
|
|
58
59
|
/* @__PURE__ */b(Jl,{message:n,primaryColor:s,botAvatar:l,botName:c,styles:u,avatars:d,isFirst:!f,isLast:!m,onButtonClick:p,onProposalAction:h})]},t.key)})}),r&&/* @__PURE__ */y("div",{className:"flex items-end gap-3 mt-4 mb-2 animate-in fade-in slide-in-from-left-4 duration-500",children:[
|
|
@@ -60,7 +61,8 @@ return y("div",{style:{position:"absolute",top:0,left:0,width:"100%",transform:`
|
|
|
60
61
|
/* @__PURE__ */b("span",{className:"w-1 h-1 bg-primary/50 rounded-full animate-bounce [animation-delay:-0.3s]"}),
|
|
61
62
|
/* @__PURE__ */b("span",{className:"w-1 h-1 bg-primary/50 rounded-full animate-bounce [animation-delay:-0.15s]"}),
|
|
62
63
|
/* @__PURE__ */b("span",{className:"w-1 h-1 bg-primary/50 rounded-full animate-bounce"})]})}),
|
|
63
|
-
/* @__PURE__ */b(Kl,{})]})]})
|
|
64
|
+
/* @__PURE__ */b(Kl,{})]})]});const N=/* @__PURE__ */new Map;/* @__PURE__ */
|
|
65
|
+
return b("div",{ref:g,className:"flex-1 overflow-y-auto scroll-smooth p-4 scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:/* @__PURE__ */y("div",{className:"min-h-full flex flex-col justify-end",children:[0===e.length&&/* @__PURE__ */y("div",{className:"flex-1 flex flex-col items-center justify-center py-16 text-center animate-in fade-in zoom-in-95 duration-1000",children:[
|
|
64
66
|
/* @__PURE__ */y("div",{className:"relative h-24 w-24 mb-6",children:[
|
|
65
67
|
/* @__PURE__ */b("div",{className:"absolute inset-0 bg-primary/20 rounded-full animate-pulse blur-2xl"}),
|
|
66
68
|
/* @__PURE__ */b("div",{className:"relative h-full w-full rounded-[28px] border-2 border-primary/20 overflow-hidden shadow-soft-2xl transition-transform hover:scale-105 duration-500",children:k?/* @__PURE__ */b("div",{className:"h-full w-full flex items-center justify-center text-3xl",style:{backgroundColor:S},children:"👋"}):l?/* @__PURE__ */b("img",{src:l,className:"object-cover h-full w-full",alt:c,onError:()=>_(!0)}):/* @__PURE__ */b("div",{className:"h-full w-full flex items-center justify-center text-3xl",style:{backgroundColor:S},children:"👋"})})]}),
|
|
@@ -69,13 +71,13 @@ return y("div",{style:{position:"absolute",top:0,left:0,width:"100%",transform:`
|
|
|
69
71
|
/* @__PURE__ */y("p",{className:"text-[12px] font-bold text-muted-foreground italic px-10 leading-relaxed opacity-60",children:['"',o,'"']})]})]}),
|
|
70
72
|
/* @__PURE__ */b("div",{className:"flex flex-col",style:{gap:"var(--spacing-3)"},children:e.map((t,r)=>{const o=e[r-1],i=e[r+1],a=o&&Gl(new Date(t.timestamp),new Date(o.timestamp))>15,f=o&&o.sender===t.sender&&Gl(new Date(t.timestamp),new Date(o.timestamp))<5&&!a,m=i&&i.sender===t.sender&&Gl(new Date(i.timestamp),new Date(t.timestamp))<5;/* @__PURE__ */
|
|
71
73
|
return y(n.Fragment,{children:[a&&/* @__PURE__ */b("div",{className:"flex justify-center my-8 animate-in fade-in zoom-in-95",children:/* @__PURE__ */b("span",{className:"px-4 py-1.5 bg-muted/40 backdrop-blur-md rounded-full text-[10px] font-black text-muted-foreground uppercase tracking-[0.2em] border border-border/50 shadow-sm",children:A(t.timestamp)})}),
|
|
72
|
-
/* @__PURE__ */b(Jl,{message:t,primaryColor:s,botAvatar:l,botName:c,styles:u,avatars:d,isFirst:!f,isLast:!m,onButtonClick:p,onProposalAction:h})]},t.id||`
|
|
74
|
+
/* @__PURE__ */b(Jl,{message:t,primaryColor:s,botAvatar:l,botName:c,styles:u,avatars:d,isFirst:!f,isLast:!m,onButtonClick:p,onProposalAction:h})]},((e,t)=>{const n=e.id||`idx-${t}`,r=N.get(n)??0;return N.set(n,r+1),0===r?n:`${n}__${r}`})(t,r))})}),r&&/* @__PURE__ */y("div",{className:"flex items-end gap-3 mt-4 mb-2 animate-in fade-in slide-in-from-left-4 duration-500",children:[
|
|
73
75
|
/* @__PURE__ */b("div",{className:"w-8 h-8 rounded-xl bg-muted/60 border border-border/50 flex items-center justify-center shrink-0 shadow-soft-sm",children:/* @__PURE__ */y("div",{className:"flex gap-[2px]",children:[
|
|
74
76
|
/* @__PURE__ */b("span",{className:"w-1 h-1 bg-primary/50 rounded-full animate-bounce [animation-delay:-0.3s]"}),
|
|
75
77
|
/* @__PURE__ */b("span",{className:"w-1 h-1 bg-primary/50 rounded-full animate-bounce [animation-delay:-0.15s]"}),
|
|
76
78
|
/* @__PURE__ */b("span",{className:"w-1 h-1 bg-primary/50 rounded-full animate-bounce"})]})}),
|
|
77
79
|
/* @__PURE__ */b(Kl,{})]}),
|
|
78
|
-
/* @__PURE__ */b("div",{ref:m,className:"h-6 shrink-0"})]})})
|
|
80
|
+
/* @__PURE__ */b("div",{ref:m,className:"h-6 shrink-0"})]})})},(e,t)=>{if(e.messages.length!==t.messages.length)return!1;if(e.isTyping!==t.isTyping)return!1;if(e.primaryColor!==t.primaryColor)return!1;if(e.botName!==t.botName)return!1;if(e.logoUrl!==t.logoUrl)return!1;const n=e.messages[e.messages.length-1],r=t.messages[t.messages.length-1];return n?.id===r?.id}),Xl={"image/jpeg":[255,216,255],"image/png":[137,80,78,71,13,10,26,10],"image/webp":[82,73,70,70],"image/gif":[71,73,70,56],"audio/mpeg":[255,251],"audio/wav":[82,73,70,70],"audio/webm":[26,69,223,163],"audio/ogg":[79,103,103,83]};async function ec(e,t={}){const{maxSizeMB:n=10,allowedExtensions:r,checkMagicBytes:o=!0}=t;if(!function(e,t=10){const n=1024*t*1024;return e.size<=n}(e,n))return{valid:!1,error:`El archivo es demasiado grande. Máximo ${n}MB`};if(r&&!function(e,t){const n=e.name.split(".").pop()?.toLowerCase();return!!n&&t.includes(n)}(e,r))return{valid:!1,error:`Extensión no permitida. Solo: ${r.join(", ")}`};if(o){const t=await async function(e){try{const t=Xl[e.type];if(!t)return!0;const n=await e.slice(0,12).arrayBuffer(),r=new Uint8Array(n);return t.every((e,t)=>r[t]===e)}catch(t){return console.error("File validation error:",t),!1}}(e);if(!t)return{valid:!1,error:"El archivo está corrupto o no es del tipo indicado"}}return{valid:!0}}const tc=1e3,nc={enableImages:!0,enableAudio:!0,enableFiles:!0,enableLocation:!0,allowedFileTypes:["jpg","jpeg","png","webp","gif","pdf","doc","docx","txt","zip"],maxFileSizeMB:10};function rc({isConnected:e,placeholder:t="Escribe un mensaje...",primaryColor:n,mediaConfig:r,onSendMessage:o,onSendAttachment:a,onSendLocation:s,onVoiceCall:l}){const{t:c}=D(),[d,p]=i(""),[h,m]=i(!1),[g,w]=i(!1),[x,k]=i(0),[_,S]=i(null),[C,E]=i(!1),[z,A]=i(!1),N=f(null),T=f(null),I=f(null),O=f(null),M=f([]),P=f(null),L=It({primaryColor:n}),j=u(()=>({...nc,...r}),[r]),R=u(()=>j.enableImages||j.enableAudio||j.enableFiles||j.enableLocation,[j]),F=()=>{const t=d.trim();N.current&&(N.current.focus(),N.current.style.height="40px"),_?(a?.(_.file,_.type),S(null),p("")):t&&e&&(o(t),p("")),requestAnimationFrame(()=>{N.current?.focus()})},$=async e=>{const t=e.target.files?.[0];if(!t)return;m(!1);const n=await ec(t,{maxSizeMB:j.maxFileSizeMB||10,allowedExtensions:j.allowedFileTypes||["jpg","jpeg","png","webp","gif","pdf","doc","docx","txt","zip"],checkMagicBytes:!0});if(n.valid)if(t.type.startsWith("image/")&&j.enableImages){E(!0);try{const{default:e}=await import("./browser-image-compression-CsxM8KJN.js"),n={maxSizeMB:.8,maxWidthOrHeight:1200,useWebWorker:!0},r=await e(t,n);S({type:"image",file:r,previewUrl:URL.createObjectURL(r)})}catch(r){Ft("Image compression failed:",r),S({type:"image",file:t,previewUrl:URL.createObjectURL(t)})}finally{E(!1)}}else S({type:"file",file:t,previewUrl:""});else alert(n.error||"Archivo no válido")},B=async e=>{if(O.current&&(e||(O.current.onstop=null),O.current.stop(),O.current.stream.getTracks().forEach(e=>e.stop())),P.current&&clearInterval(P.current),w(!1),k(0),e&&M.current.length>0){const e=new Blob(M.current,{type:"audio/webm"}),t=new File([e],`audio-${Date.now()}.webm`,{type:"audio/webm"}),n=await ec(t,{maxSizeMB:10});if(!n.valid)return Ft("Audio validation failed:",n.error),alert(n.error),void(M.current=[]);a?.(t,"audio"),M.current=[]}};/* @__PURE__ */
|
|
79
81
|
return y("div",{className:"relative",children:[(_||C)&&/* @__PURE__ */b("div",{className:"absolute bottom-full left-0 mb-2 p-2 rounded-2xl border shadow-soft-2xl animate-in slide-in-from-bottom-2 z-50",style:{backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))"},children:/* @__PURE__ */b("div",{className:"relative w-16 h-16",children:C?/* @__PURE__ */b("div",{className:"w-full h-full flex flex-col items-center justify-center bg-muted rounded-xl",children:/* @__PURE__ */b(G,{className:"animate-spin text-primary h-5 w-5"})}):/* @__PURE__ */y(v,"image"===_?.type?{children:[
|
|
80
82
|
/* @__PURE__ */b("img",{src:_?.previewUrl,className:"w-full h-full object-cover rounded-xl border",alt:c("preview")}),
|
|
81
83
|
/* @__PURE__ */b("button",{onClick:()=>S(null),className:"absolute -top-1.5 -right-1.5 bg-destructive text-white rounded-full p-1 shadow-md hover:scale-105",children:/* @__PURE__ */b(ce,{size:10,strokeWidth:3})})]}:{children:[
|
|
@@ -179,32 +181,32 @@ return y(v,{children:[
|
|
|
179
181
|
/* @__PURE__ */b("div",{className:"text-6xl mb-4",children:"⚠️"}),
|
|
180
182
|
/* @__PURE__ */b("h2",{className:"text-xl font-bold text-foreground mb-2",children:"Algo salió mal"}),
|
|
181
183
|
/* @__PURE__ */b("p",{className:"text-sm text-muted-foreground mb-6 max-w-md",children:this.state.error?.message||"Ocurrió un error inesperado"}),
|
|
182
|
-
/* @__PURE__ */b("button",{onClick:this.handleReset,className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium hover:opacity-90 transition-opacity",children:"Intentar de nuevo"})]}):this.props.children}}const Jc={bubble:"rounded-2xl",image:"rounded-xl",button:"rounded-xl",card:"rounded-2xl"},Kc={bg:"bg-muted/50 dark:bg-muted/20",text:"text-foreground",border:"border-border/50"},Gc={text:"text-primary-foreground"};const Yc=(e,t)=>t.some(t=>e instanceof t);let Qc,Xc;const eu=/* @__PURE__ */new WeakMap,tu=/* @__PURE__ */new WeakMap,nu=/* @__PURE__ */new WeakMap;let ru={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return eu.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return au(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function ou(e){ru=e(ru)}function iu(e){return"function"==typeof e?(t=e,(Xc||(Xc=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(su(this),e),au(this.request)}:function(...e){return au(t.apply(su(this),e))}):(e instanceof IDBTransaction&&function(e){if(eu.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{t(),r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)});eu.set(e,t)}(e),Yc(e,Qc||(Qc=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,ru):e);var t}function au(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{t(au(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)});return nu.set(t,e),t}(e);if(tu.has(e))return tu.get(e);const t=iu(e);return t!==e&&(tu.set(e,t),nu.set(t,e)),t}const su=e=>nu.get(e),lu=["get","getKey","getAll","getAllKeys","count"],cu=["put","add","delete","clear"],uu=/* @__PURE__ */new Map;function du(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(uu.get(t))return uu.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=cu.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!lu.includes(n))return;const i=async function(e,...t){const i=this.transaction(e,o?"readwrite":"readonly");let a=i.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),o&&i.done]))[0]};return uu.set(t,i),i}ou(e=>({...e,get:(t,n,r)=>du(t,n)||e.get(t,n,r),has:(t,n)=>!!du(t,n)||e.has(t,n)}));const pu=["continue","continuePrimaryKey","advance"],hu={},fu=/* @__PURE__ */new WeakMap,mu=/* @__PURE__ */new WeakMap,gu={get(e,t){if(!pu.includes(t))return e[t];let n=hu[t];return n||(n=hu[t]=function(...e){fu.set(this,mu.get(this)[t](...e))}),n}};async function*bu(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,gu);for(mu.set(n,t),nu.set(n,su(t));t;)yield n,t=await(fu.get(n)||t.continue()),fu.delete(n)}function yu(e,t){return t===Symbol.asyncIterator&&Yc(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&Yc(e,[IDBIndex,IDBObjectStore])}ou(e=>({...e,get:(t,n,r)=>yu(t,n)?bu:e.get(t,n,r),has:(t,n)=>yu(t,n)||e.has(t,n)}));class vu{db=null;DB_NAME;DB_VERSION=1;constructor(e,t="default"){this.DB_NAME=`botuyo-chat-${e}-${t}`}async init(){try{this.db=await function(e,t,{blocked:n,upgrade:r,blocking:o,terminated:i}={}){const a=indexedDB.open(e,t),s=au(a);return r&&a.addEventListener("upgradeneeded",e=>{r(au(a.result),e.oldVersion,e.newVersion,au(a.transaction),e)}),n&&a.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{i&&e.addEventListener("close",()=>i()),o&&e.addEventListener("versionchange",e=>o(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}(this.DB_NAME,this.DB_VERSION,{upgrade(e){e.objectStoreNames.contains("messages")||e.createObjectStore("messages",{keyPath:"id"}).createIndex("by-timestamp","timestamp"),e.objectStoreNames.contains("metadata")||e.createObjectStore("metadata")}}),Bt("IndexedDB initialized")}catch(e){throw Ft("Failed to initialize IndexedDB:",e),e}}async saveMessage(e){this.db||await this.init();try{await this.db.put("messages",e)}catch(t){Ft("Failed to save message:",t)}}async saveMessages(e){this.db||await this.init();try{const t=this.db.transaction("messages","readwrite");await Promise.all([...e.map(e=>t.store.put(e)),t.done])}catch(t){Ft("Failed to save messages:",t)}}async getMessages(e=100){this.db||await this.init();try{return(await this.db.getAllFromIndex("messages","by-timestamp")).slice(-e)}catch(t){return Ft("Failed to get messages:",t),[]}}async getMessage(e){this.db||await this.init();try{return await this.db.get("messages",e)}catch(t){return void Ft("Failed to get message:",t)}}async deleteMessage(e){this.db||await this.init();try{await this.db.delete("messages",e)}catch(t){Ft("Failed to delete message:",t)}}async clearMessages(){this.db||await this.init();try{await this.db.clear("messages"),Bt("Messages cleared from IndexedDB")}catch(e){Ft("Failed to clear messages:",e)}}async setMetadata(e){this.db||await this.init();try{await this.db.put("metadata",e,"chat-metadata")}catch(t){Ft("Failed to set metadata:",t)}}async getMetadata(){this.db||await this.init();try{return await this.db.get("metadata","chat-metadata")}catch(e){return Ft("Failed to get metadata:",e),null}}async clearAll(){this.db||await this.init();try{await Promise.all([this.db.clear("messages"),this.db.clear("metadata")]),Bt("All data cleared from IndexedDB")}catch(e){Ft("Failed to clear all data:",e)}}async migrateFromLocalStorage(e,t="default"){try{const n=`botuyo_chat_v1_${e}_${t}`,r=localStorage.getItem(n);if(!r)return;const o=JSON.parse(r);if(o.messages&&Array.isArray(o.messages)){const e=o.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}));await this.saveMessages(e),Bt(`Migrated ${e.length} messages from localStorage`)}o.sessionId&&await this.setMetadata({sessionId:o.sessionId}),localStorage.removeItem(n),Bt("Migration from localStorage completed")}catch(n){Ft("Failed to migrate from localStorage:",n)}}}const wu=/* @__PURE__ */new Map,xu={isOpen:!1,isConnected:!1,isTyping:!1,messages:[],error:null,sessionId:null};function ku(e,t){switch(t.type){case"TOGGLE_WINDOW":return{...e,isOpen:!e.isOpen};case"OPEN_WINDOW":return{...e,isOpen:!0};case"CLOSE_WINDOW":return{...e,isOpen:!1};case"SET_CONNECTED":return{...e,isConnected:t.payload};case"SET_TYPING":return{...e,isTyping:t.payload};case"ADD_MESSAGE":{if(e.messages.some(e=>e.id===t.payload.id))return e;if(t.payload.id.startsWith("msg-")&&"text"===t.payload.type){const n=/* @__PURE__ */(new Date).getTime();if(e.messages.slice(-10).some(e=>"text"===e.type&&e.sender===t.payload.sender&&"content"in e&&"content"in t.payload&&e.content===t.payload.content&&Math.abs(n-new Date(e.timestamp).getTime())<3e4))return e}const n=[...e.messages,t.payload],r="bot"===t.payload.sender;return{...e,messages:n,isTyping:!r&&e.isTyping}}case"SET_MESSAGES":return{...e,messages:[...t.payload]};case"SET_ERROR":return{...e,error:t.payload};case"SET_SESSION_ID":return{...e,sessionId:t.payload};case"ANSWER_QUIZ":{const{messageId:n,buttonId:r}=t.payload;return{...e,messages:e.messages.map(e=>e.id===n&&"buttons"===e.type?{...e,answered:!0,...r?{selectedId:r}:{}}:e)}}case"RESOLVE_PROPOSAL":{const{proposalId:n,status:r}=t.payload;return{...e,messages:e.messages.map(e=>"tool_proposal"===e.type&&e.proposalId===n?{...e,status:r}:e)}}case"CLEAR_CHAT":return{...xu,isOpen:e.isOpen};case"RESTORE_SESSION":return{...e,...t.payload,isConnected:!1,isTyping:!1,error:null};default:return e}}function _u(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:/* @__PURE__ */new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const o=a.prototype,i=Object.keys(o);for(let e=0;e<i.length;e++){const t=i[e];t in n||(n[t]=o[t].bind(n))}}const o=n?.Parent??Object;class i extends o{}function a(e){var t;const o=n?.Parent?new i:this;r(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const n of o._zod.deferred)n();return o}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class Su extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Cu extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Eu={};function zu(e){return Eu}function Au(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function Nu(e,t){return"bigint"==typeof t?t.toString():t}function Tu(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Iu(e){return null==e}function Ou(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const Mu=/* @__PURE__ */Symbol("evaluating");function Pu(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Mu)return void 0===r&&(r=Mu,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Lu(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Du(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function ju(e){return JSON.stringify(e)}const Ru="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Fu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const $u=Tu(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Bu(e){if(!1===Fu(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==Fu(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Uu(e){return Bu(e)?{...e}:Array.isArray(e)?[...e]:e}const qu=/* @__PURE__ */new Set(["string","number","symbol"]);function Vu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wu(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Hu(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const Zu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ju(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Ku(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Gu(e){return"string"==typeof e?e:e?.message}function Yu(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=Gu(e.inst?._zod.def?.error?.(e))??Gu(t?.error?.(e))??Gu(n.customError?.(e))??Gu(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Qu(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Xu(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const ed=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Nu,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},td=_u("$ZodError",ed),nd=_u("$ZodError",ed,{Parent:Error}),rd=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Su;if(a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Yu(e,i,zu())));throw Ru(t,o?.callee),t}return a.value},od=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Yu(e,i,zu())));throw Ru(t,o?.callee),t}return a.value},id=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Su;return i.issues.length?{success:!1,error:new(e??td)(i.issues.map(e=>Yu(e,o,zu())))}:{success:!0,data:i.value}},ad=/* @__PURE__ */id(nd),sd=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>Yu(e,o,zu())))}:{success:!0,data:i.value}},ld=/* @__PURE__ */sd(nd),cd=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return rd(e)(t,n,o)},ud=e=>(t,n,r)=>rd(e)(t,n,r),dd=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return od(e)(t,n,o)},pd=e=>async(t,n,r)=>od(e)(t,n,r),hd=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return id(e)(t,n,o)},fd=e=>(t,n,r)=>id(e)(t,n,r),md=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return sd(e)(t,n,o)},gd=e=>async(t,n,r)=>sd(e)(t,n,r),bd=/^[cC][^\s-]{8,}$/,yd=/^[0-9a-z]+$/,vd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,wd=/^[0-9a-vA-V]{20}$/,xd=/^[A-Za-z0-9]{27}$/,kd=/^[a-zA-Z0-9_-]{21}$/,_d=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Sd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Cd=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ed=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,zd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ad=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Nd=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Td=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Id=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Od=/^[A-Za-z0-9_-]*$/,Md=/^\+[1-9]\d{6,14}$/,Pd="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Ld=/* @__PURE__ */new RegExp(`^${Pd}$`);function Dd(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const jd=/^-?\d+$/,Rd=/^-?\d+(?:\.\d+)?$/,Fd=/^(?:true|false)$/i,$d=/^[^A-Z]*$/,Bd=/^[^a-z]*$/,Ud=/* @__PURE__ */_u("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),qd={number:"number",bigint:"bigint",object:"date"},Vd=/* @__PURE__ */_u("$ZodCheckLessThan",(e,t)=>{Ud.init(e,t);const n=qd[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Wd=/* @__PURE__ */_u("$ZodCheckGreaterThan",(e,t)=>{Ud.init(e,t);const n=qd[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Hd=/* @__PURE__ */_u("$ZodCheckMultipleOf",(e,t)=>{Ud.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(0===o&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(o=Number.parseInt(e[1]))}const i=n>o?n:o;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Zd=/* @__PURE__ */_u("$ZodCheckNumberFormat",(e,t)=>{Ud.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Zu[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=o,r.maximum=i,n&&(r.pattern=jd)}),e._zod.check=a=>{const s=a.value;if(n){if(!Number.isInteger(s))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}s<o&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Jd=/* @__PURE__ */_u("$ZodCheckMaxLength",(e,t)=>{var n;Ud.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Iu(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const o=Qu(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Kd=/* @__PURE__ */_u("$ZodCheckMinLength",(e,t)=>{var n;Ud.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Iu(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const o=Qu(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Gd=/* @__PURE__ */_u("$ZodCheckLengthEquals",(e,t)=>{var n;Ud.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Iu(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,o=r.length;if(o===t.length)return;const i=Qu(r),a=o>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Yd=/* @__PURE__ */_u("$ZodCheckStringFormat",(e,t)=>{var n,r;Ud.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=/* @__PURE__ */new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Qd=/* @__PURE__ */_u("$ZodCheckRegex",(e,t)=>{Yd.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Xd=/* @__PURE__ */_u("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=$d),Yd.init(e,t)}),ep=/* @__PURE__ */_u("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Bd),Yd.init(e,t)}),tp=/* @__PURE__ */_u("$ZodCheckIncludes",(e,t)=>{Ud.init(e,t);const n=Vu(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),np=/* @__PURE__ */_u("$ZodCheckStartsWith",(e,t)=>{Ud.init(e,t);const n=new RegExp(`^${Vu(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),rp=/* @__PURE__ */_u("$ZodCheckEndsWith",(e,t)=>{Ud.init(e,t);const n=new RegExp(`.*${Vu(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),op=/* @__PURE__ */_u("$ZodCheckOverwrite",(e,t)=>{Ud.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class ip{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const o of r)this.content.push(o)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const ap={major:4,minor:3,patch:6},sp=/* @__PURE__ */_u("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ap;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const t of o._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,o=Ju(e);for(const i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,a=i._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new Su;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(o||(o=Ju(e,t)))});else{if(e.issues.length===t)continue;o||(o=Ju(e,t))}}return r?r.then(()=>e):e},n=(n,o,i)=>{if(Ju(n))return n.aborted=!0,n;const a=t(o,r,i);if(a instanceof Promise){if(!1===i.async)throw new Su;return a.then(t=>e._zod.parse(t,i))}return e._zod.parse(a,i)};e._zod.run=(o,i)=>{if(i.skipChecks)return e._zod.parse(o,i);if("backward"===i.direction){const t=e._zod.parse({value:o.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,o,i)):n(t,o,i)}const a=e._zod.parse(o,i);if(a instanceof Promise){if(!1===i.async)throw new Su;return a.then(e=>t(e,r,i))}return t(a,r,i)}}Pu(e,"~standard",()=>({validate:t=>{try{const n=ad(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return ld(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),lp=/* @__PURE__ */_u("$ZodString",(e,t)=>{var n;sp.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),cp=/* @__PURE__ */_u("$ZodStringFormat",(e,t)=>{Yd.init(e,t),lp.init(e,t)}),up=/* @__PURE__ */_u("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Sd),cp.init(e,t)}),dp=/* @__PURE__ */_u("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Cd(e))}else t.pattern??(t.pattern=Cd());cp.init(e,t)}),pp=/* @__PURE__ */_u("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ed),cp.init(e,t)}),hp=/* @__PURE__ */_u("$ZodURL",(e,t)=>{cp.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=o.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),fp=/* @__PURE__ */_u("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),cp.init(e,t)}),mp=/* @__PURE__ */_u("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=kd),cp.init(e,t)}),gp=/* @__PURE__ */_u("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=bd),cp.init(e,t)}),bp=/* @__PURE__ */_u("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=yd),cp.init(e,t)}),yp=/* @__PURE__ */_u("$ZodULID",(e,t)=>{t.pattern??(t.pattern=vd),cp.init(e,t)}),vp=/* @__PURE__ */_u("$ZodXID",(e,t)=>{t.pattern??(t.pattern=wd),cp.init(e,t)}),wp=/* @__PURE__ */_u("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=xd),cp.init(e,t)}),xp=/* @__PURE__ */_u("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=Dd({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Pd}T(?:${r})$`)}(t)),cp.init(e,t)}),kp=/* @__PURE__ */_u("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ld),cp.init(e,t)}),_p=/* @__PURE__ */_u("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${Dd(t)}$`)),cp.init(e,t)}),Sp=/* @__PURE__ */_u("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=_d),cp.init(e,t)}),Cp=/* @__PURE__ */_u("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=zd),cp.init(e,t),e._zod.bag.format="ipv4"}),Ep=/* @__PURE__ */_u("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ad),cp.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),zp=/* @__PURE__ */_u("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Nd),cp.init(e,t)}),Ap=/* @__PURE__ */_u("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Td),cp.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Np(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Tp=/* @__PURE__ */_u("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Id),cp.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Np(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Ip=/* @__PURE__ */_u("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Od),cp.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!Od.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Np(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Op=/* @__PURE__ */_u("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Md),cp.init(e,t)}),Mp=/* @__PURE__ */_u("$ZodJWT",(e,t)=>{cp.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&"JWT"!==o?.typ||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Pp=/* @__PURE__ */_u("$ZodNumber",(e,t)=>{sp.init(e,t),e._zod.pattern=e._zod.bag.pattern??Rd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}const o=n.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Lp=/* @__PURE__ */_u("$ZodNumberFormat",(e,t)=>{Zd.init(e,t),Pp.init(e,t)}),Dp=/* @__PURE__ */_u("$ZodBoolean",(e,t)=>{sp.init(e,t),e._zod.pattern=Fd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}const o=n.value;return"boolean"==typeof o||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),jp=/* @__PURE__ */_u("$ZodAny",(e,t)=>{sp.init(e,t),e._zod.parse=e=>e}),Rp=/* @__PURE__ */_u("$ZodUnknown",(e,t)=>{sp.init(e,t),e._zod.parse=e=>e}),Fp=/* @__PURE__ */_u("$ZodNever",(e,t)=>{sp.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function $p(e,t,n){e.issues.length&&t.issues.push(...Ku(n,e.issues)),t.value[n]=e.value}const Bp=/* @__PURE__ */_u("$ZodArray",(e,t)=>{sp.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const a=o[e],s=t.element._zod.run({value:a,issues:[]},r);s instanceof Promise?i.push(s.then(t=>$p(t,n,e))):$p(s,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function Up(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...Ku(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function qp(e){const t=Object.keys(e.shape);for(const o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Vp(e,t,n,r,o,i){const a=[],s=o.keySet,l=o.catchall._zod,c=l.def.type,u="optional"===l.optout;for(const d in t){if(s.has(d))continue;if("never"===c){a.push(d);continue}const o=l.run({value:t[d],issues:[]},r);o instanceof Promise?e.push(o.then(e=>Up(e,n,d,t,u))):Up(o,n,d,t,u)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const Wp=/* @__PURE__ */_u("$ZodObject",(e,t)=>{sp.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=Tu(()=>qp(t));Pu(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */new Set);for(const e of r.values)n[t].add(e)}}return n});const o=Fu,i=t.catchall;let a;e._zod.parse=(t,n)=>{a??(a=r.value);const s=t.value;if(!o(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};const l=[],c=a.shape;for(const e of a.keys){const r=c[e],o="optional"===r._zod.optout,i=r._zod.run({value:s[e],issues:[]},n);i instanceof Promise?l.push(i.then(n=>Up(n,t,e,s,o))):Up(i,t,e,s,o)}return i?Vp(l,s,t,n,r.value,e):l.length?Promise.all(l).then(()=>t):t}}),Hp=/* @__PURE__ */_u("$ZodObjectJIT",(e,t)=>{Wp.init(e,t);const n=e._zod.parse,r=Tu(()=>qp(t));let o;const i=Fu,a=!Eu.jitless,s=a&&$u.value,l=t.catchall;let c;e._zod.parse=(u,d)=>{c??(c=r.value);const p=u.value;return i(p)?a&&s&&!1===d?.async&&!0!==d.jitless?(o||(o=(e=>{const t=new ip(["shape","payload","ctx"]),n=r.value,o=e=>{const t=ju(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=/* @__PURE__ */Object.create(null);let a=0;for(const r of n.keys)i[r]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=i[r],a=ju(r),s=e[r],l="optional"===s?._zod?.optout;t.write(`const ${n} = ${o(r)};`),l?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const s=t.compile();return(t,n)=>s(e,t,n)})(t.shape)),u=o(u,d),l?Vp([],p,u,d,c,e):u):n(u,d):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function Zp(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const o=e.filter(e=>!Ju(e));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Yu(e,r,zu())))}),t)}const Jp=/* @__PURE__ */_u("$ZodUnion",(e,t)=>{sp.init(e,t),Pu(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Pu(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Pu(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Pu(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>Ou(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n)return r(o,i);let a=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:o.value,issues:[]},i);if(t instanceof Promise)s.push(t),a=!0;else{if(0===t.issues.length)return t;s.push(t)}}return a?Promise.all(s).then(t=>Zp(t,o,e,i)):Zp(s,o,e,i)}}),Kp=/* @__PURE__ */_u("$ZodIntersection",(e,t)=>{sp.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([t,n])=>Yp(e,t,n)):Yp(e,o,i)}});function Gp(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Bu(e)&&Bu(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),o={...e,...t};for(const i of r){const n=Gp(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};o[i]=n.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=Gp(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Yp(e,t,n){const r=/* @__PURE__ */new Map;let o;for(const s of t.issues)if("unrecognized_keys"===s.code){o??(o=s);for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(s);for(const s of n.issues)if("unrecognized_keys"===s.code)for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(s);const i=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(i.length&&o&&e.issues.push({...o,keys:i}),Ju(e))return e;const a=Gp(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}const Qp=/* @__PURE__ */_u("$ZodRecord",(e,t)=>{sp.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Bu(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[],a=t.keyType._zod.values;if(a){n.value={};const s=/* @__PURE__ */new Set;for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){s.add("number"==typeof e?e.toString():e);const a=t.valueType._zod.run({value:o[e],issues:[]},r);a instanceof Promise?i.push(a.then(t=>{t.issues.length&&n.issues.push(...Ku(e,t.issues)),n.value[e]=t.value})):(a.issues.length&&n.issues.push(...Ku(e,a.issues)),n.value[e]=a.value)}let l;for(const e in o)s.has(e)||(l=l??[],l.push(e));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:l})}else{n.value={};for(const a of Reflect.ownKeys(o)){if("__proto__"===a)continue;let s=t.keyType._zod.run({value:a,issues:[]},r);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof a&&Rd.test(a)&&s.issues.length){const e=t.keyType._zod.run({value:Number(a),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(s=e)}if(s.issues.length){"loose"===t.mode?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(e=>Yu(e,r,zu())),input:a,path:[a],inst:e});continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?i.push(l.then(e=>{e.issues.length&&n.issues.push(...Ku(a,e.issues)),n.value[s.value]=e.value})):(l.issues.length&&n.issues.push(...Ku(a,l.issues)),n.value[s.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),Xp=/* @__PURE__ */_u("$ZodEnum",(e,t)=>{sp.init(e,t);const n=Au(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>qu.has(typeof e)).map(e=>"string"==typeof e?Vu(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}}),eh=/* @__PURE__ */_u("$ZodTransform",(e,t)=>{sp.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Cu(e.constructor.name);const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n));if(o instanceof Promise)throw new Su;return n.value=o,n}});function th(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const nh=/* @__PURE__ */_u("$ZodOptional",(e,t)=>{sp.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Pu(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,void 0]):void 0),Pu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Ou(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>th(t,e.value)):th(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),rh=/* @__PURE__ */_u("$ZodExactOptional",(e,t)=>{nh.init(e,t),Pu(e._zod,"values",()=>t.innerType._zod.values),Pu(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),oh=/* @__PURE__ */_u("$ZodNullable",(e,t)=>{sp.init(e,t),Pu(e._zod,"optin",()=>t.innerType._zod.optin),Pu(e._zod,"optout",()=>t.innerType._zod.optout),Pu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Ou(e.source)}|null)$`):void 0}),Pu(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),ih=/* @__PURE__ */_u("$ZodDefault",(e,t)=>{sp.init(e,t),e._zod.optin="optional",Pu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>ah(e,t)):ah(r,t)}});function ah(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const sh=/* @__PURE__ */_u("$ZodPrefault",(e,t)=>{sp.init(e,t),e._zod.optin="optional",Pu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),lh=/* @__PURE__ */_u("$ZodNonOptional",(e,t)=>{sp.init(e,t),Pu(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(t=>ch(t,e)):ch(o,e)}});function ch(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const uh=/* @__PURE__ */_u("$ZodCatch",(e,t)=>{sp.init(e,t),Pu(e._zod,"optin",()=>t.innerType._zod.optin),Pu(e._zod,"optout",()=>t.innerType._zod.optout),Pu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Yu(e,n,zu()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Yu(e,n,zu()))},input:e.value}),e.issues=[]),e)}}),dh=/* @__PURE__ */_u("$ZodPipe",(e,t)=>{sp.init(e,t),Pu(e._zod,"values",()=>t.in._zod.values),Pu(e._zod,"optin",()=>t.in._zod.optin),Pu(e._zod,"optout",()=>t.out._zod.optout),Pu(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>ph(e,t.in,n)):ph(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ph(e,t.out,n)):ph(r,t.out,n)}});function ph(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const hh=/* @__PURE__ */_u("$ZodReadonly",(e,t)=>{sp.init(e,t),Pu(e._zod,"propValues",()=>t.innerType._zod.propValues),Pu(e._zod,"values",()=>t.innerType._zod.values),Pu(e._zod,"optin",()=>t.innerType?._zod?.optin),Pu(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(fh):fh(r)}});function fh(e){return e.value=Object.freeze(e.value),e}const mh=/* @__PURE__ */_u("$ZodCustom",(e,t)=>{Ud.init(e,t),sp.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(t=>gh(t,n,r,e));gh(o,n,r,e)}});function gh(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Xu(e))}}var bh;(bh=globalThis).__zod_globalRegistry??(bh.__zod_globalRegistry=new class{constructor(){this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const yh=globalThis.__zod_globalRegistry;function vh(e,t){return new e({type:"string",...Hu(t)})}function wh(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Hu(t)})}function xh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Hu(t)})}function kh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Hu(t)})}function _h(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Hu(t)})}function Sh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Hu(t)})}function Ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Hu(t)})}function Eh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Hu(t)})}function zh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Hu(t)})}function Ah(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Hu(t)})}function Nh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Hu(t)})}function Th(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Hu(t)})}function Ih(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Hu(t)})}function Oh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Hu(t)})}function Mh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Hu(t)})}function Ph(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Hu(t)})}function Lh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Hu(t)})}function Dh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Hu(t)})}function jh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Hu(t)})}function Rh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Hu(t)})}function Fh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Hu(t)})}function $h(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Hu(t)})}function Bh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Hu(t)})}function Uh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Hu(t)})}function qh(e,t){return new e({type:"string",format:"date",check:"string_format",...Hu(t)})}function Vh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Hu(t)})}function Wh(e,t){return new e({type:"string",format:"duration",check:"string_format",...Hu(t)})}function Hh(e,t){return new e({type:"number",checks:[],...Hu(t)})}function Zh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Hu(t)})}function Jh(e,t){return new e({type:"boolean",...Hu(t)})}function Kh(e){return new e({type:"any"})}function Gh(e){return new e({type:"unknown"})}function Yh(e,t){return new e({type:"never",...Hu(t)})}function Qh(e,t){return new Vd({check:"less_than",...Hu(t),value:e,inclusive:!1})}function Xh(e,t){return new Vd({check:"less_than",...Hu(t),value:e,inclusive:!0})}function ef(e,t){return new Wd({check:"greater_than",...Hu(t),value:e,inclusive:!1})}function tf(e,t){return new Wd({check:"greater_than",...Hu(t),value:e,inclusive:!0})}function nf(e,t){return new Hd({check:"multiple_of",...Hu(t),value:e})}function rf(e,t){return new Jd({check:"max_length",...Hu(t),maximum:e})}function of(e,t){return new Kd({check:"min_length",...Hu(t),minimum:e})}function af(e,t){return new Gd({check:"length_equals",...Hu(t),length:e})}function sf(e,t){return new Qd({check:"string_format",format:"regex",...Hu(t),pattern:e})}function lf(e){return new Xd({check:"string_format",format:"lowercase",...Hu(e)})}function cf(e){return new ep({check:"string_format",format:"uppercase",...Hu(e)})}function uf(e,t){return new tp({check:"string_format",format:"includes",...Hu(t),includes:e})}function df(e,t){return new np({check:"string_format",format:"starts_with",...Hu(t),prefix:e})}function pf(e,t){return new rp({check:"string_format",format:"ends_with",...Hu(t),suffix:e})}function hf(e){return new op({check:"overwrite",tx:e})}function ff(e){/* @__PURE__ */
|
|
183
|
-
return
|
|
184
|
-
return
|
|
185
|
-
return
|
|
186
|
-
return
|
|
187
|
-
return
|
|
188
|
-
return
|
|
189
|
-
return
|
|
190
|
-
return
|
|
191
|
-
return
|
|
192
|
-
return
|
|
193
|
-
return
|
|
194
|
-
return
|
|
195
|
-
return
|
|
196
|
-
return
|
|
197
|
-
return vf(zm,e,t)}const Nm=/* @__PURE__ */_u("ZodObject",(e,t)=>{Hp.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const a=i.shape;for(const c in a)o.properties[c]=Sf(a[c],t,{...r,path:[...r.path,"properties",c]});const s=new Set(Object.keys(a)),l=new Set([...s].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));l.size>0&&(o.required=Array.from(l)),"never"===i.catchall?._zod.def.type?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Sf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),Pu(e,"shape",()=>t.shape),e.keyof=()=>Lm(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Cm()}),e.loose=()=>e.clone({...e._zod.def,catchall:Cm()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */Yh(Em,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Bu(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=Du(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Lu(this,"shape",n),n}});return Wu(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Bu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Du(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Lu(this,"shape",n),n}});return Wu(e,n)}(e,t),e.merge=t=>function(e,t){const n=Du(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Lu(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Wu(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return Wu(e,Du(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Lu(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=Du(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Lu(this,"shape",r),r},checks:[]});return Wu(e,o)}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=Du(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Lu(this,"shape",o),o},checks:[]});return Wu(t,o)}(jm,e,t[0]),e.required=(...t)=>function(e,t,n){const r=Du(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)o[t]=new e({type:"nonoptional",innerType:r[t]});return Lu(this,"shape",o),o}});return Wu(t,r)}(Vm,e,t[0])});function Tm(e,t){const n={type:"object",shape:e??{},...Hu(t)};return new Nm(n)}const Im=/* @__PURE__ */_u("ZodUnion",(e,t)=>{Jp.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=!1===o.inclusive,a=o.options.map((e,n)=>Sf(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options}),Om=/* @__PURE__ */_u("ZodIntersection",(e,t)=>{Kp.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Sf(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=Sf(o.right,t,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length,l=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];n.allOf=l})(e,t,n,r)}),Mm=/* @__PURE__ */_u("ZodRecord",(e,t)=>{Qp.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object";const a=i.keyType,s=a._zod.bag,l=s?.patterns;if("loose"===i.mode&&l&&l.size>0){const e=Sf(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const t of l)o.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(o.propertyNames=Sf(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=Sf(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=a._zod.values;if(c){const e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(o.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType}),Pm=/* @__PURE__ */_u("ZodEnum",(e,t)=>{Xp.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Au(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);o[i]=t.entries[i]}return new Pm({...t,checks:[],...Hu(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new Pm({...t,checks:[],...Hu(r),entries:o})}});function Lm(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Pm({type:"enum",entries:n,...Hu(t)})}const Dm=/* @__PURE__ */_u("ZodTransform",(e,t)=>{eh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Cu(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Xu(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Xu(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),jm=/* @__PURE__ */_u("ZodOptional",(e,t)=>{nh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Rm(e){return new jm({type:"optional",innerType:e})}const Fm=/* @__PURE__ */_u("ZodExactOptional",(e,t)=>{rh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),$m=/* @__PURE__ */_u("ZodNullable",(e,t)=>{oh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Sf(o.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bm(e){return new $m({type:"nullable",innerType:e})}const Um=/* @__PURE__ */_u("ZodDefault",(e,t)=>{ih.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Sf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),qm=/* @__PURE__ */_u("ZodPrefault",(e,t)=>{sh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Sf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Vm=/* @__PURE__ */_u("ZodNonOptional",(e,t)=>{lh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Sf(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Wm=/* @__PURE__ */_u("ZodCatch",(e,t)=>{uh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;Sf(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Hm=/* @__PURE__ */_u("ZodPipe",(e,t)=>{dh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i="input"===t.io?"transform"===o.in._zod.def.type?o.out:o.in:o.out;Sf(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function Zm(e,t){return new Hm({type:"pipe",in:e,out:t})}const Jm=/* @__PURE__ */_u("ZodReadonly",(e,t)=>{hh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Sf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Km=/* @__PURE__ */_u("ZodCustom",(e,t)=>{mh.init(e,t),Jf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)}),Gm=/* @__PURE__ */Object.create(null);Gm.open="0",Gm.close="1",Gm.ping="2",Gm.pong="3",Gm.message="4",Gm.upgrade="5",Gm.noop="6";const Ym=/* @__PURE__ */Object.create(null);Object.keys(Gm).forEach(e=>{Ym[Gm[e]]=e});const Qm={type:"error",data:"parser error"},Xm="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),eg="function"==typeof ArrayBuffer,tg=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ng=({type:e,data:t},n,r)=>Xm&&t instanceof Blob?n?r(t):rg(t,r):eg&&(t instanceof ArrayBuffer||tg(t))?n?r(t):rg(new Blob([t]),r):r(Gm[e]+(t||"")),rg=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function og(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ig;const ag="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let ty=0;ty<64;ty++)ag["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(ty)]=ty;const sg="function"==typeof ArrayBuffer,lg=(e,t)=>{if("string"!=typeof e)return{type:"message",data:ug(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:cg(e.substring(1),t)}:Ym[n]?e.length>1?{type:Ym[n],data:e.substring(1)}:{type:Ym[n]}:Qm},cg=(e,t)=>{if(sg){const n=(e=>{let t,n,r,o,i,a=.75*e.length,s=e.length,l=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);const c=new ArrayBuffer(a),u=new Uint8Array(c);for(t=0;t<s;t+=4)n=ag[e.charCodeAt(t)],r=ag[e.charCodeAt(t+1)],o=ag[e.charCodeAt(t+2)],i=ag[e.charCodeAt(t+3)],u[l++]=n<<2|r>>4,u[l++]=(15&r)<<4|o>>2,u[l++]=(3&o)<<6|63&i;return c})(e);return ug(n,t)}return{base64:!0,data:e}},ug=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,dg=String.fromCharCode(30);let pg;function hg(e){return e.reduce((e,t)=>e+t.length,0)}function fg(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;o<t;o++)n[o]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function mg(e){if(e)return function(e){for(var t in mg.prototype)e[t]=mg.prototype[t];return e}(e)}mg.prototype.on=mg.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},mg.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},mg.prototype.off=mg.prototype.removeListener=mg.prototype.removeAllListeners=mg.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<r.length;o++)if((n=r[o])===t||n.fn===t){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},mg.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,t)}return this},mg.prototype.emitReserved=mg.prototype.emit,mg.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},mg.prototype.hasListeners=function(e){return!!this.listeners(e).length};const gg="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),bg="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function yg(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const vg=bg.setTimeout,wg=bg.clearTimeout;function xg(e,t){t.useNativeTimers?(e.setTimeoutFn=vg.bind(bg),e.clearTimeoutFn=wg.bind(bg)):(e.setTimeoutFn=bg.setTimeout.bind(bg),e.clearTimeoutFn=bg.clearTimeout.bind(bg))}function kg(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,o=e.length;r<o;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function _g(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Sg extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Cg extends mg{constructor(e){super(),this.writable=!1,xg(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new Sg(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=lg(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class Eg extends Cg{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(dg),r=[];for(let o=0;o<n.length;o++){const e=lg(n[o],t);if(r.push(e),"error"===e.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((e,i)=>{ng(e,!1,e=>{r[i]=e,++o===n&&t(r.join(dg))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=_g()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let zg=!1;try{zg="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(ey){}const Ag=zg;function Ng(){}class Tg extends Eg{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class Ig extends mg{constructor(e,t,n){super(),this.createRequest=e,xg(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=yg(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(r){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(r){}try{n.setRequestHeader("Accept","*/*")}catch(r){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(r){return void this.setTimeoutFn(()=>{this._onError(r)},0)}"undefined"!=typeof document&&(this._index=Ig.requestsCount++,Ig.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Ng,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Ig.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function Og(){for(let e in Ig.requests)Ig.requests.hasOwnProperty(e)&&Ig.requests[e].abort()}Ig.requestsCount=0,Ig.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Og):"function"==typeof addEventListener&&addEventListener("onpagehide"in bg?"pagehide":"unload",Og,!1));const Mg=function(){const e=Pg({xdomain:!1});return e&&null!==e.responseType}();function Pg(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Ag))return new XMLHttpRequest}catch(n){}if(!t)try{return new(bg[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const Lg="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Dg extends Cg{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Lg?{}:yg(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(ey){return this.emitReserved("error",ey)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;ng(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&gg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=_g()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const jg=bg.WebSocket||bg.MozWebSocket,Rg={websocket:class extends Dg{createSocket(e,t,n){return Lg?new jg(e,t,n):t?new jg(e,t):new jg(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Cg{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(ey){return this.emitReserved("error",ey)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){pg||(pg=new TextDecoder);const n=[];let r=0,o=-1,i=!1;return new TransformStream({transform(a,s){for(n.push(a);;){if(0===r){if(hg(n)<1)break;const e=fg(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(hg(n)<2)break;const e=fg(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(hg(n)<8)break;const e=fg(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(Qm);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(hg(n)<o)break;const e=fg(n,o);s.enqueue(lg(i?e:pg.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(Qm);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){Xm&&e.data instanceof Blob?e.data.arrayBuffer().then(og).then(t):eg&&(e.data instanceof ArrayBuffer||tg(e.data))?t(og(e.data)):ng(e,!1,e=>{ig||(ig=new TextEncoder),t(ig.encode(e))})}(e,n=>{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}});r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const o=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this._writer.write(i).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&gg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Tg{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Mg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Ig(Pg,this.uri(),e)}}},Fg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,$g=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Bg(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=Fg.exec(e||""),i={},a=14;for(;a--;)i[$g[a]]=o[a]||"";return-1!=n&&-1!=r&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,i.path),i.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}(0,i.query),i}const Ug="function"==typeof addEventListener&&"function"==typeof removeEventListener,qg=[];Ug&&addEventListener("offline",()=>{qg.forEach(e=>e())},!1);class Vg extends mg{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=Bg(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Bg(t.host).host);xg(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let r=0,o=n.length;r<o;r++){let e=n[r].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),Ug&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},qg.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Vg.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Vg.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=kg(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,gg(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const o={type:e,data:t,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Vg.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Ug&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=qg.indexOf(this._offlineEventListener);-1!==e&&qg.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Vg.protocol=4;class Wg extends Vg{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Vg.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Vg.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function o(){n||(n=!0,c(),t.close(),t=null)}const i=e=>{const n=new Error("probe error: "+e);n.transport=t.name,o(),this.emitReserved("upgradeError",n)};function a(){i("transport closed")}function s(){i("socket closed")}function l(e){t&&e.name!==t.name&&o()}const c=()=>{t.removeListener("open",r),t.removeListener("error",i),t.removeListener("close",a),this.off("close",s),this.off("upgrading",l)};t.once("open",r),t.once("error",i),t.once("close",a),this.once("close",s),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let Hg=class extends Wg{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>Rg[e]).filter(e=>!!e)),super(e,n)}};const Zg="function"==typeof ArrayBuffer,Jg=Object.prototype.toString,Kg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Jg.call(Blob),Gg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Jg.call(File);function Yg(e){return Zg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Kg&&e instanceof Blob||Gg&&e instanceof File}function Qg(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Qg(e[t]))return!0;return!1}if(Yg(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Qg(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&Qg(e[n]))return!0;return!1}function Xg(e){const t=[],n=e.data,r=e;return r.data=eb(n,t),r.attachments=t.length,{packet:r,buffers:t}}function eb(e,t){if(!e)return e;if(Yg(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=eb(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=eb(e[r],t));return n}return e}function tb(e,t){return e.data=nb(e.data,t),delete e.attachments,e}function nb(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=nb(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=nb(e[n],t));return e}const rb=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ob,ib;(ib=ob||(ob={}))[ib.CONNECT=0]="CONNECT",ib[ib.DISCONNECT=1]="DISCONNECT",ib[ib.EVENT=2]="EVENT",ib[ib.ACK=3]="ACK",ib[ib.CONNECT_ERROR=4]="CONNECT_ERROR",ib[ib.BINARY_EVENT=5]="BINARY_EVENT",ib[ib.BINARY_ACK=6]="BINARY_ACK";class ab extends mg{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof e?{reviver:e}:e)}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===ob.BINARY_EVENT;n||t.type===ob.BINARY_ACK?(t.type=n?ob.EVENT:ob.ACK,this.reconstructor=new sb(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Yg(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===ob[n.type])throw new Error("unknown packet type "+n.type);if(n.type===ob.BINARY_EVENT||n.type===ob.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");const i=Number(o);if(!lb(i)||i<0)throw new Error("Illegal attachments");if(i>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=i}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!ab.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(e,t){switch(e){case ob.CONNECT:return cb(t);case ob.DISCONNECT:return void 0===t;case ob.CONNECT_ERROR:return"string"==typeof t||cb(t);case ob.EVENT:case ob.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===rb.indexOf(t[0]));case ob.ACK:case ob.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class sb{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=tb(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const lb=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function cb(e){return"[object Object]"===Object.prototype.toString.call(e)}const ub=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:ab,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==ob.EVENT&&e.type!==ob.ACK||!Qg(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===ob.EVENT?ob.BINARY_EVENT:ob.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==ob.BINARY_EVENT&&e.type!==ob.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Xg(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return ob}},Symbol.toStringTag,{value:"Module"}));function db(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const pb=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class hb extends mg{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[db(e,"open",this.onopen.bind(this)),db(e,"packet",this.onpacket.bind(this)),db(e,"error",this.onerror.bind(this)),db(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,r,o;if(pb.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:ob.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const a=null===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,s=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!a||(s?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),i=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{const o=(e,t)=>e?r(e):n(t);o.withError=!0,t.push(o),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:ob.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case ob.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ob.EVENT:case ob.BINARY_EVENT:this.onevent(e);break;case ob.ACK:case ob.BINARY_ACK:this.onack(e);break;case ob.DISCONNECT:this.ondisconnect();break;case ob.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:ob.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ob.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function fb(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}fb.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},fb.prototype.reset=function(){this.attempts=0},fb.prototype.setMin=function(e){this.ms=e},fb.prototype.setMax=function(e){this.max=e},fb.prototype.setJitter=function(e){this.jitter=e};class mb extends mg{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,xg(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new fb({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||ub;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Hg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=db(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=db(t,"error",o);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{r(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(db(e,"ping",this.onping.bind(this)),db(e,"data",this.ondata.bind(this)),db(e,"error",this.onerror.bind(this)),db(e,"close",this.onclose.bind(this)),db(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){gg(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new hb(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const gb={};function bb(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=Bg(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const o=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port+t,r.href=r.protocol+"://"+o+(n&&n.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=n.source,o=n.id,i=n.path,a=gb[o]&&i in gb[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new mb(r,t):(gb[o]||(gb[o]=new mb(r,t)),s=gb[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(bb,{Manager:mb,Socket:hb,io:bb,connect:bb});const yb=Tm({proposalId:Yf().min(1),tool:Yf().min(1),title:Yf().optional(),summary:Yf().optional(),args:(vb=Yf(),wb=Cm(),new Mm({type:"record",keyType:vb,valueType:wb,...Hu(void 0)})).optional(),ownerOnly:/* @__PURE__ */Jh(km,void 0).optional()});var vb,wb;const xb=Tm({proposalId:Yf().min(1),status:Lm(["confirmed","cancelled","expired"]).optional()}),kb="chat_device_id";function _b(){const e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if("function"==typeof e?.randomUUID)return e.randomUUID();if("function"==typeof e?.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=Array.from(t,e=>e.toString(16).padStart(2,"0"));return n.slice(0,4).join("")+"-"+n.slice(4,6).join("")+"-"+n.slice(6,8).join("")+"-"+n.slice(8,10).join("")+"-"+n.slice(10,16).join("")}return Rt("[deviceId] Web Crypto API unavailable, falling back to Math.random()"),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const Sb=Tm({id:Yf().optional(),type:Lm(["text","image","audio","location","system"]).default("text"),content:Yf().optional(),imageUrl:Yf().url().optional(),audioUrl:Yf().optional(),latitude:vm().optional(),longitude:vm().optional(),timestamp:Yf().optional(),sender:Lm(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Kh(_m).optional(),sources:Am(Yf()).optional()}),Cb=Tm({agentId:Yf().optional(),name:Yf().optional(),label:Yf().optional(),avatarUrl:Yf().optional(),variantKey:Yf().optional()}),Eb=/USER_IDENTITY_REQUIRED|AUTH_EXPIRED|AUTH_INVALID|AUTH_REQUIRED|unauthorized/i;class zb{queue=[];endpoint;apiKey;flushInterval=null;isFlushing=!1;isDisabled=!1;MAX_QUEUE_SIZE=100;FLUSH_INTERVAL_MS=3e4;BATCH_SIZE=10;constructor(e,t){this.endpoint=e,this.apiKey=t,this.startAutoFlush()}startAutoFlush(){this.flushInterval=setInterval(()=>{!this.isDisabled&&this.queue.length>0&&this.flush()},this.FLUSH_INTERVAL_MS)}trackOpen(){this.track("chat_opened")}trackClose(){this.track("chat_closed")}trackMessageSent(e){this.track("message_sent",{type:e})}trackMessageReceived(e,t){this.track("message_received",{type:e,latency:t})}trackError(e,t){this.track("error",{error:e,context:t})}trackConnectionStatus(e){this.track("connection_status",{isConnected:e})}trackFeatureUsed(e){this.track("feature_used",{feature:e})}trackTypingStarted(){this.track("typing_started")}trackAttachmentSent(e,t){this.track("attachment_sent",{type:e,size:t})}track(e,t){this.isDisabled||(this.queue.push({event:e,properties:{...t,userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0,url:"undefined"!=typeof window?window.location.href:void 0},timestamp:Date.now()}),this.queue.length>=this.BATCH_SIZE&&this.flush(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE),Rt("Analytics queue overflow, dropping old events")))}async flush(){if(this.isDisabled||0===this.queue.length||this.isFlushing)return;this.isFlushing=!0;const e=[...this.queue];this.queue=[];try{const t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({events:e}),keepalive:!0});t.ok?$t():(this.isDisabled=!0,this.queue=[],$t(t.status))}catch(t){this.isDisabled=!0,this.queue=[],$t()}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}const Ab=e=>{const t=new Date(e.timestamp).getTime();return Number.isFinite(t)?t:0},Nb=e=>`${e.sender}|${(e=>{const t=e.content;return"string"==typeof t?t:""})(e).trim()}`;let Tb=null,Ib=null;function Ob(e){Tb=e}function Mb(e){Ib=e}const Pb=r(null);function Lb({children:e,defaultLocale:t,initialState:n,onStateChange:r,...o}){const[a,l]=i(n?.isOpen??!1),[c,u]=i(0),d=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:open"))},[r]),p=s(()=>{l(!1),r?.(!1),window.dispatchEvent(new CustomEvent("botuyo-chat:close"))},[r]),h=s(()=>{l(e=>{const t=!e;return t&&u(0),r?.(t),t}),window.dispatchEvent(new CustomEvent("botuyo-chat:toggle"))},[r]),f=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))},[r]),m=s(e=>{Tb?(Tb(e),$t(0)):Rt("sendMessage called but no handler registered")},[]),g=s(()=>{Ib?(Ib(),$t()):Rt("clearMessages called but no handler registered")},[]),v={isOpen:a,open:d,close:p,toggle:h,startCall:f,sendMessage:m,clearMessages:g,unreadCount:c},w=s((e,t)=>{"message:received"!==e||a||u(e=>e+1),o.onEvent?.(e,t)},[a,o]);/* @__PURE__ */
|
|
198
|
-
return y(
|
|
199
|
-
/* @__PURE__ */b(Ub,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:w})]})}function Db(){const e=o(Pb);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const jb=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function Rb(e){const{apiKey:t,apiBaseUrl:r,agentId:o,pageContext:l,includeSEOMetadata:c=!1,theme:d,userContext:p,onLogin:h,onNavigate:m,onEvent:b,onStateChange:y,getUserToken:v,onAuthRequired:w,onThemeUpdate:x}=e,[k,_]=i(0),S=f(0),{t:C}=D(),E=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new zb(o,t);const i=()=>r.current?.flush(),a=()=>{"hidden"===document.visibilityState&&r.current?.flush()};return window.addEventListener("beforeunload",i),window.addEventListener("visibilitychange",a),()=>{window.removeEventListener("beforeunload",i),window.removeEventListener("visibilitychange",a),r.current?.destroy()}},[e,t,n]),{trackOpen:s(()=>{r.current?.trackOpen()},[]),trackClose:s(()=>{r.current?.trackClose()},[]),trackMessageSent:s(e=>{r.current?.trackMessageSent(e)},[]),trackMessageReceived:s((e,t)=>{r.current?.trackMessageReceived(e,t)},[]),trackError:s((e,t)=>{r.current?.trackError(e,t)},[]),trackConnectionStatus:s(e=>{r.current?.trackConnectionStatus(e)},[]),trackFeatureUsed:s(e=>{r.current?.trackFeatureUsed(e)},[])}}(r,t,!0),z=function({enabled:e=!0,soundEnabled:t=!0,desktopEnabled:n=!0,botName:r="BotUyo",logoUrl:o,notificationSoundUrl:l}={}){const[c,u]=i("default"),d=f(null),p=o||Ut,h=l||qt;a(()=>{t&&"undefined"!=typeof window&&(d.current=new Audio(h),d.current.volume=.3)},[t,h]),a(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return Rt("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),Bt("Notification permission:",e),"granted"===e}catch(e){return Ft("Error requesting notification permission:",e),!1}},[]),g=s(t=>{if(e&&n&&"granted"===c&&("undefined"==typeof document||!document.hasFocus()))try{const e=`Nuevo mensaje de ${r}`;let n="Mensaje recibido";"text"===t.type&&"content"in t?n=t.content?.slice(0,100)||"Mensaje recibido":"image"===t.type?n="📷 Imagen":"audio"===t.type?n="🎵 Audio":"location"===t.type&&(n="📍 Ubicación");const o=new Notification(e,{body:n,icon:p,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(o){Ft("Error showing notification:",o)}},[e,n,c,r,p]),b=s(()=>{if(e&&t&&("undefined"==typeof document||!document.hasFocus()))try{d.current?.play().catch(e=>{$t(0)})}catch(n){Ft("Error playing sound:",n)}},[e,t]),y=s(e=>{g(e),b()},[g,b]);return{permission:c,requestPermission:m,notify:g,playSound:b,notifyWithSound:y}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:d?.botName||"BotUyo",logoUrl:d?.logoUrl}),A=function(e=10,t=6e4){const n=f([]);return{isAllowed:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),!(n.current.length>=e||(n.current.push(r),0))},[e,t]),getRemainingAttempts:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),Math.max(0,e-n.current.length)},[e,t]),getTimeUntilReset:s(()=>{if(0===n.current.length)return 0;const e=Date.now(),r=n.current[0],o=t-(e-r);return Math.max(0,o)},[t]),reset:s(()=>{n.current=[]},[])}}(10,6e4),{state:N,actions:T}=function(e,t="default"){const[r,o]=g(ku,xu),[l,c]=i(!1),u=n.useMemo(()=>function(e,t="default"){return`botuyo_chat_v1_${e}_${t}`}(e,t),[e,t]),d=n.useMemo(()=>((e,t="default")=>{const n=`${e}_${t}`;return wu.has(n)||wu.set(n,new vu(e,t)),wu.get(n)})(e,t),[e,t]);a(()=>{"undefined"==typeof window||l||(async()=>{try{await d.migrateFromLocalStorage(e,t);const n=await d.getMessages(100),r=await d.getMetadata();if(n.length>0||r){const e={messages:n.map(e=>({...e,timestamp:new Date(e.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};o({type:"RESTORE_SESSION",payload:e})}}catch(n){Rt("Chat: Error rehydrating from IndexedDB",n);try{const e=localStorage.getItem(u);if(e){const t=JSON.parse(e);t.messages&&(t.messages=t.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}))),o({type:"RESTORE_SESSION",payload:t})}}catch(r){Ft("Chat: Fallback rehydration failed",r)}}finally{c(!0)}})()},[l]),a(()=>{if(!l)return;const e=setTimeout(async()=>{try{await d.saveMessages(r.messages),await d.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(e){Ft("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){Ft("Chat: Fallback persistence failed",t)}}},500);return()=>clearTimeout(e)},[r.isOpen,r.messages,r.sessionId,l]);const p=s(e=>{o({type:"ADD_MESSAGE",payload:e})},[]),h=s(()=>o({type:"TOGGLE_WINDOW"}),[]),f=s(()=>o({type:"OPEN_WINDOW"}),[]),m=s(()=>o({type:"CLOSE_WINDOW"}),[]),b=s(e=>o({type:"SET_CONNECTED",payload:e}),[]),y=s(e=>o({type:"SET_TYPING",payload:e}),[]),v=s(e=>o({type:"SET_MESSAGES",payload:e}),[]),w=s(e=>o({type:"SET_ERROR",payload:e}),[]),x=s(e=>o({type:"SET_SESSION_ID",payload:e}),[]),k=s(()=>{localStorage.removeItem(u),o({type:"CLEAR_CHAT"})},[]),_=s(()=>{o({type:"SET_MESSAGES",payload:[]})},[]),S=s((e,t)=>o({type:"ANSWER_QUIZ",payload:{messageId:e,buttonId:t}}),[]),C=s((e,t)=>o({type:"RESOLVE_PROPOSAL",payload:{proposalId:e,status:t}}),[]);return{state:r,isHydrated:l,actions:{toggleWindow:h,openWindow:f,closeWindow:m,setConnected:b,setTyping:y,addMessage:p,setMessages:v,setError:w,setSessionId:x,clearChat:k,clearMessages:_,answerQuiz:S,resolveProposal:C}}}(t,o),I=function(e=!1){const t="undefined"!=typeof window?window.location.pathname:"",n=u(()=>t,[t]),[r,o]=i({});return a(()=>{if(!e)return void o({});const t=setTimeout(()=>{const e=function(){if("undefined"==typeof window)return{};const e={};e.title=document.title,document.querySelectorAll("meta").forEach(t=>{const n=t.getAttribute("name"),r=t.getAttribute("property"),o=t.getAttribute("content");if(o){if(n)switch(n){case"description":e.description=o;break;case"keywords":e.keywords=o.split(",").map(e=>e.trim());break;case"author":e.author=o}if(r){if(r.startsWith("og:")){const t=r.replace("og:","og_");e[t]=o}if(r.startsWith("twitter:")){const t=r.replace("twitter:","twitter_");e[t]=o}}}});try{const t=document.querySelectorAll('script[type="application/ld+json"]');if(t.length>0){const n=[];t.forEach(e=>{try{const t=JSON.parse(e.textContent||"");n.push(t)}catch{}}),n.length>0&&(e.structuredData=n)}}catch{}return e}();o(e)},100);return()=>clearTimeout(t)},[n,e]),e&&Object.keys(r).length>0?r:void 0}(c),O=function(e){const{apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,userContext:l}=e,c=f(e);a(()=>{c.current=e},[e]);const d=f(null),[p,h]=i(!1),[m,g]=i(!1),b=f(function(){try{const e=localStorage.getItem(kb);if(e)return e;const t=_b();return localStorage.setItem(kb,t),t}catch{return Rt("localStorage not available, using session-only device ID"),_b()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=Sb.safeParse(e),r=t.success&&t.data.id?t.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=t.success&&t.data.sender?t.data.sender:"bot",i=t.success&&t.data.timestamp?new Date(t.data.timestamp):/* @__PURE__ */new Date,a=t.success?t.data:{type:"text"};switch(a.type){case"image":return{id:r,type:"image",sender:o,timestamp:i,imageUrl:a.imageUrl||a.content||"",altText:"Imagen enviada"};case"audio":{const e=a.audioUrl||"";return{id:r,type:"audio",sender:o,timestamp:i,content:e.startsWith("http://")||e.startsWith("https://")?e:e?`${n}/api/voice/audio/${r}`:a.content||"",text:a.content||void 0}}case"location":return{id:r,type:"location",sender:o,timestamp:i,latitude:Number(a.latitude||0),longitude:Number(a.longitude||0),name:a.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:i,content:String(a.content||"")};default:return{id:r,type:"text",sender:o,timestamp:i,content:String(a.content||"Sin contenido"),emotion:a.emotion,...a.sources?.length?{sources:a.sources}:{}}}},[]),w=s(()=>{if(!t||!n)return;if(d.current?.connected)return;h(!0);const e=e=>{const o=bb(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});o.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),o.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),o.on("connect_error",e=>{h(!1);const n=String(e?.data instanceof Object?e?.data?.code:e?.data??e?.message??"");if(Eb.test(n)||Eb.test(e?.message??"")){c.current.onAuthRequired?.();const e=c.current.getUserToken;e&&e().then(e=>{d.current&&(d.current.auth={apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata})}).catch(e=>Ft("[useChatSocket] Token refresh failed:",e))}c.current.onError(`Error de conexión: ${e.message}`)}),o.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),o.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){Ft("ChatSocket Error processing bot_message:",t)}}),o.on("chat_history",e=>{if(e.messages&&Array.isArray(e.messages))if(c.current.onHistoryLoaded){const t=e.messages.map(e=>{try{return v(e)}catch(t){return $t(),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){$t()}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),o.on("bot_typing",e=>c.current.onTyping(e));const i=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};o.on("onboarding:command",e=>i(e)),o.on("form:command",e=>i(e)),o.on("request_form_state",()=>{i({type:"botuyo-request-form-state"})}),o.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),o.on("custom_event",e=>{if(i({type:"botuyo-custom-event",...e}),"quiz_question"===e?.eventName&&e?.data){const{question:t,buttons:n}=e.data;if(t&&n?.length){const e={id:`quiz-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"buttons",sender:"bot",timestamp:/* @__PURE__ */new Date,content:t,buttons:n};c.current.onMessage(e)}}if("agent_switched"===e?.eventName&&e?.data){const t=Cb.safeParse(e.data);t.success?c.current.onAgentSwitched?.(t.data):$t()}if("tool_proposal"===e?.eventName&&e?.data){const t=yb.safeParse(e.data);if(t.success){const e=t.data,n={id:`proposal-${e.proposalId}`,type:"tool_proposal",sender:"bot",timestamp:/* @__PURE__ */new Date,proposalId:e.proposalId,toolName:e.tool,title:e.title,summary:e.summary,ownerOnly:e.ownerOnly,status:"pending"};c.current.onMessage(n)}else $t()}if(("tool_proposal_resolved"===e?.eventName||"tool_proposal_expired"===e?.eventName)&&e?.data){const t=xb.safeParse(e.data);if(t.success){const n="tool_proposal_expired"===e.eventName?"expired":t.data.status??"confirmed";c.current.onToolProposalResolved?.(t.data.proposalId,n)}else $t()}});const a=e=>{const{type:t}=e.data||{};"botuyo-onboarding-state"!==t&&"botuyo-form-state"!==t||o.emit("form_state",e.data)};window.addEventListener("message",a),d.current=o,o.__formCleanup=()=>window.removeEventListener("message",a)},o=c.current.getUserToken;o?o().then(t=>e(t)).catch(t=>{Ft("[useChatSocket] getUserToken failed:",t),c.current.onAuthRequired?.(),e(l?.token)}):e(l?.token)},[t,n]),x=s(()=>{d.current&&(d.current.disconnect(),d.current=null,g(!1))},[]),k=f(w);k.current=w,a(()=>(k.current(),()=>{d.current&&(d.current.disconnect(),d.current=null)}),[]);const _=f([]),S=f([]),C=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),E=s(()=>{if(d.current?.connected)for(;_.current.length>0;){const e=_.current.shift();d.current.emit("user_message",e)}},[]);a(()=>{m&&E()},[m,E]),a(()=>{if(!m)return;const e=setInterval(()=>{const e=Date.now();S.current=S.current.filter(t=>e<t.nextRetryAt||(t.attempts>=t.maxAttempts?(c.current.onEvent?.("message_failed",{id:t.id,payload:t.payload}),Ft("Message failed after max retries:",t.id),!1):!d.current?.connected||(d.current.emit("user_message",t.payload,e=>{e?.success&&c.current.onEvent?.("message_sent",{id:t.id})}),t.attempts++,t.nextRetryAt=e+1e3*Math.pow(2,t.attempts),t.attempts<t.maxAttempts)))},500);return()=>clearInterval(e)},[m]);const z=s((e,t="text")=>{const n=C(),r={...y.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:b.current},o={id:n,content:e.trim(),type:t,metadata:r};return d.current?.connected?(d.current.emit("user_message",o,e=>{!1!==e?.success&&e?c.current.onEvent?.("message_sent",{id:n}):(S.current.push({id:n,payload:o,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),c.current.onEvent?.("message_retry_queued",{id:n}))}),n):(_.current.push(o),c.current.onEvent?.("queued_message",{id:n,payload:o}),n)},[C]),A=u(()=>ac(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:A,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x,confirmProposal:s(e=>{d.current?.emit("tool_confirm",{proposalId:e})},[]),rejectProposal:s(e=>{d.current?.emit("tool_reject",{proposalId:e})},[])}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>I?{...l||{},seo:{...I||{}}}:l,[l,I]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=S.current>0?t-S.current:void 0;S.current=t,T.addMessage(e),E.trackMessageReceived(e.type,n),N.isOpen||"bot"!==e.sender||(_(e=>e+1),z.notifyWithSound(e))},[T,N.isOpen,E,z]),onConnected:s((e,t)=>{T.setConnected(!0),T.setSessionId(e),E.trackConnectionStatus(!0),t&&x&&x(t),t&&b&&b("backend_config",t)},[T,b,x,E]),onDisconnected:s(()=>{T.setConnected(!1),E.trackConnectionStatus(!1)},[T,E]),onTyping:s(e=>T.setTyping(e),[T]),onError:s(e=>{T.setError(e),E.trackError(e)},[T,E]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:x,onAgentSwitched:s(e=>{const t=function(e,t){const n=(e||"").trim(),r=(t||"").trim();return n&&r&&!n.toLowerCase().includes(r.toLowerCase())?`${n} · ${r}`:n||r}(e.name,e.label);x&&x(n=>({...n||{},...t?{botName:t}:{},...e.avatarUrl?{logoUrl:e.avatarUrl}:{}})),t&&T.addMessage({id:`agent-switched-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"system",sender:"system",timestamp:/* @__PURE__ */new Date,content:C("agent_switched",{name:t})})},[x,T,C]),onHistoryLoaded:s(e=>{0!==e.length&&T.setMessages(function(e,t){if(!t||0===t.length)return e;const n=t.reduce((e,t)=>Math.max(e,Ab(t)),0),r=new Set(t.map(e=>e.id)),o=new Set(t.map(Nb)),i=e.filter(e=>!r.has(e.id)&&Ab(e)>n&&!o.has(Nb(e)));return[...t,...i]}(N.messages,e))},[N.messages,T]),getUserToken:v,onAuthRequired:w,onToolProposalResolved:s((e,t)=>T.resolveProposal(e,t),[T])}),M=u(()=>function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("buttons"===n.type&&!n.answered)return n}return null}(N.messages),[N.messages]),P=f(M);a(()=>{P.current=M},[M]);const L=s(()=>{$t(0,N.isOpen),N.isOpen?(T.closeWindow(),E.trackClose(),y?.(!1),$t()):(T.openWindow(),_(0),E.trackOpen(),y?.(!0),$t())},[N.isOpen,T,y,E]),j=s(e=>{if(!A.isAllowed()){const e=A.getTimeUntilReset(),t=Math.ceil(e/1e3);return void T.setError(C("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};T.addMessage(t),E.trackMessageSent("text"),O.sendMessage(e,"text"),P.current&&T.answerQuiz(P.current.id)},[T,O,A,E,C]),R=s((e,t,n)=>{T.answerQuiz(e.id,n),O.sendMessage(`Answer: ${t}`,"text"),E.trackMessageSent("text")},[T,O,E]),F=s(e=>{T.resolveProposal(e,"confirmed"),O.confirmProposal(e)},[T,O]),$=s(e=>{T.resolveProposal(e,"cancelled"),O.rejectProposal(e)},[T,O]),B=s(async(e,t)=>{let n;n="audio"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(e)}:"image"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(e)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${e.name}`},T.addMessage(n);const r=await jb(e);O.sendMessage(r,t)},[T,O]),U=s(e=>{const t={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:e.latitude,longitude:e.longitude,name:"Mi ubicación"};T.addMessage(t),O.sendMessage(JSON.stringify(e),"location")},[T,O]);a(()=>{const e=()=>{N.isOpen||T.openWindow()},t=()=>{N.isOpen&&T.closeWindow()},n=()=>{N.isOpen?T.closeWindow():T.openWindow()},r=e=>{e.detail?.message&&j(e.detail.message)},o=()=>{N.isOpen||T.openWindow()};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),window.addEventListener("botuyo-chat:start-call",o),window.addEventListener("botuyo-chat:send-message",r),()=>{window.removeEventListener("botuyo-chat:open",e),window.removeEventListener("botuyo-chat:close",t),window.removeEventListener("botuyo-chat:toggle",n),window.removeEventListener("botuyo-chat:start-call",o),window.removeEventListener("botuyo-chat:send-message",r)}},[N.isOpen,T,j]),a(()=>(Ob(j),()=>Ob(null)),[j]);const q=s(()=>{T.clearMessages(),Bt("Chat history cleared")},[T]);a(()=>(Mb(q),()=>Mb(null)),[q]);const V=u(()=>{if(N.isTyping)return"thinking";const e=[...N.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[N.isTyping,N.messages]);return{state:N,actions:T,unreadCount:k,currentBotEmotion:V,isConnected:O.isConnected,getSocket:O.getSocket,activeQuiz:M,handleToggle:L,handleSendText:j,handleSendAttachment:B,handleSendLocation:U,handleQuizAnswer:R,handleConfirmProposal:F,handleCancelProposal:$}}function Fb({children:e}){const t=f(null),n=f(null),[r,o]=i(!1);return a(()=>{if("undefined"==typeof document)return;let e,r,i=document.getElementById("botuyo-chat-widget-root");if(i&&i.shadowRoot)e=i.shadowRoot,r=e.getElementById("botuyo-chat-widget-root")||e.querySelector("div");else{i=document.createElement("div"),i.id="botuyo-chat-widget-root",document.body.appendChild(i),e=i.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=L.replace(/:root/g,":host"),e.appendChild(t),r=document.createElement("div"),r.id="botuyo-chat-widget-root",e.appendChild(r)}return n.current=i,t.current=r,o(!0),$t(),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function $b(e){const{apiKey:t,apiBaseUrl:n="https://api.botuyo.com",agentId:r,pageContext:o,includeSEOMetadata:l=!1,theme:c,mediaConfig:d,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,initialOpen:k=!1,hideLauncher:_=!1,voiceFirst:S=!1}=e,C=f(null),E=sc(),z=function(e){const[t,n]=i(!1);return a(()=>{let t=null;const r=()=>{if(!e.current)return;const t=!!e.current.parentElement?.closest(".dark"),r=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),o=document.getElementById("botuyo-chat-widget-root"),i=!!o?.parentElement?.closest(".dark"),a=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),l="dark"===document.documentElement.getAttribute("data-theme"),c="dark"===document.body.getAttribute("data-theme"),u=!!e.current.parentElement?.closest('[data-theme="dark"]'),d=window.matchMedia("(prefers-color-scheme: dark)").matches,p=t||r||i||a||s||l||c||u||d;e.current&&(p?e.current.classList.add("dark"):e.current.classList.remove("dark")),n(p)};r();const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r();o.addEventListener("change",i);const a=new MutationObserver(()=>{r()}),s=document.getElementById("botuyo-chat-widget-root");s&&(a.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(a.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=s.parentElement)),a.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),a.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let l=e.current?.parentElement;for(;l;)a.observe(l,{attributes:!0,attributeFilter:["class","data-theme"]}),l=l.parentElement;const c=setInterval(()=>{const e=document.getElementById("botuyo-chat-widget-root");e&&e.parentElement!==t&&(t&&e.parentElement&&(a.observe(e.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=e.parentElement),r())},100);return()=>{a.disconnect(),o.removeEventListener("change",i),clearInterval(c)}},[e]),t}(C),[A,N]=i(),{mergedTheme:T,mergedStyles:I,getContainerStyle:O}=function(e,t){const n=function(){const[e,t]=i(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return a(()=>{const e=window.matchMedia("(prefers-contrast: high)"),n=window.matchMedia("(prefers-contrast: more)"),r=e=>{t(e.matches)};return e.addEventListener("change",r),n.addEventListener("change",r),()=>{e.removeEventListener("change",r),n.removeEventListener("change",r)}},[]),e}(),r=u(()=>{const r=function(e,t){const n={...Nt,...t?.cssVariables||{},...e?.cssVariables||{}};return{botName:e?.botName||t?.botName||"BotUyo",logoUrl:e?.logoUrl||t?.logoUrl||"",position:e?.position||t?.position||"bottom-right",welcomeMessage:e?.welcomeMessage||t?.welcomeMessage||"¡Hola! ¿En qué puedo ayudarte?",inputPlaceholder:e?.inputPlaceholder||t?.inputPlaceholder||"Escribe un mensaje...",cssVariables:n,isHidden:e?.isHidden??t?.isHidden??!1}}(e,t);return n?{...r,cssVariables:{...r.cssVariables,primary:"0 0% 0%",primaryForeground:"0 0% 100%",background:"0 0% 100%",foreground:"0 0% 0%",card:"0 0% 100%",cardForeground:"0 0% 0%",muted:"0 0% 96%",mutedForeground:"0 0% 0%",border:"0 0% 0%"}}:r},[e,t,n]),o=u(()=>({radius:{...Jc,...e?.bubbleStyles?.radius},bot:{...Kc,...e?.bubbleStyles?.bot},user:{...Gc,...e?.bubbleStyles?.user},launcher:{...e?.bubbleStyles?.launcher},mapCard:{...e?.bubbleStyles?.mapCard}}),[e?.bubbleStyles]);return{mergedTheme:r,mergedStyles:o,getContainerStyle:(e,t,n)=>({"--chat-primary":`hsl(${r.cssVariables.primary})`,zIndex:e?2147483647:9999,position:"fixed",top:t&&e?0:"auto",left:t&&e?0:"bottom-left"===n?"24px":"auto",right:t&&e?0:"bottom-right"!==n&&n?"auto":"24px",bottom:t&&e?0:"24px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,A);a(()=>{T.isHidden&&console.warn('[BotUyo] ⚠️ El agente (o Flow) de IA asociado a esta API Key se encuentra pausado o en estado "boceto" (draft). El widget no se mostrará hasta que lo publiques dentro de la plataforma BotUyo.')},[T.isHidden]);const{state:M,actions:P,unreadCount:L,currentBotEmotion:D,isConnected:j,handleToggle:R,handleSendText:F,handleSendAttachment:$,handleSendLocation:B,getSocket:U,activeQuiz:q,handleQuizAnswer:V,handleConfirmProposal:W,handleCancelProposal:H}=Rb({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,onThemeUpdate:N}),Z=f(!1);a(()=>{k&&A&&!Z.current&&(Z.current=!0,M.isOpen||P.openWindow())},[k,A,M.isOpen,P]);const J=u(()=>{const e={...d||{}},t=A;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,A]),K=s(()=>{P.closeWindow()},[P]),G=s(e=>{e.stopPropagation()},[]),Y=O(M.isOpen,E,c?.position),Q=u(()=>{const e={"--background":"0 0% 100%","--foreground":"240 10% 3.9%","--card":"0 0% 100%","--card-foreground":"240 10% 3.9%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 4.8% 95.9%","--muted-foreground":"240 3.8% 46.1%","--border":"240 5.9% 90%","--destructive":"0 84.2% 60.2%","--radius":"0.5rem","--window-border-radius":"24px","--launcher-border-radius":"50%","--window-height":"700px","--window-bottom":"24px","--spacing-1":"0.25rem","--spacing-2":"0.5rem","--spacing-3":"0.75rem","--spacing-4":"1rem","--spacing-5":"0.75rem","--spacing-6":"1.5rem","--spacing-7":"1.75rem","--spacing-8":"2rem"};if(!T.cssVariables)return e;let t={...T.cssVariables};if(z){const e=A?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Tt,...e,...n}}const n={...e};return t.background&&(n["--background"]=t.background),t.foreground&&(n["--foreground"]=t.foreground),t.card&&(n["--card"]=t.card),t.cardForeground&&(n["--card-foreground"]=t.cardForeground),t.primary&&(n["--primary"]=t.primary),t.primaryForeground&&(n["--primary-foreground"]=t.primaryForeground),t.muted&&(n["--muted"]=t.muted),t.mutedForeground&&(n["--muted-foreground"]=t.mutedForeground),t.border&&(n["--border"]=t.border),t.destructive&&(n["--destructive"]=t.destructive),t.radius&&(n["--radius"]=t.radius),t.windowBorderRadius&&(n["--window-border-radius"]=t.windowBorderRadius),t.launcherBorderRadius&&(n["--launcher-border-radius"]=t.launcherBorderRadius),t.windowHeight&&(n["--window-height"]=t.windowHeight),t.windowBottom&&(n["--window-bottom"]=t.windowBottom),t.spacing1&&(n["--spacing-1"]=t.spacing1),t.spacing2&&(n["--spacing-2"]=t.spacing2),t.spacing3&&(n["--spacing-3"]=t.spacing3),t.spacing4&&(n["--spacing-4"]=t.spacing4),t.spacing5&&(n["--spacing-5"]=t.spacing5),t.spacing6&&(n["--spacing-6"]=t.spacing6),t.spacing7&&(n["--spacing-7"]=t.spacing7),t.spacing8&&(n["--spacing-8"]=t.spacing8),n},[T.cssVariables,z,A,c?.darkCssVariables]),X=c?.voiceNoiseGate??A?.voiceNoiseGate,ee=u(()=>({noiseGate:X}),[X]),[te,ne]=i(!1);return a(()=>{S&&j&&ne(!0)},[S,j]),T.isHidden?null:A?S?/* @__PURE__ */b("div",{ref:C,id:"botuyo-chat-widget-root",className:"botuyo-chat-widget",style:{position:"fixed",inset:0,zIndex:2147483e3,...Q},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,children:/* @__PURE__ */b(Zc,{children:/* @__PURE__ */b(Wc,{isOpen:te,onClose:()=>g?.("voice_first_ended",{}),onCallEnded:e=>g?.("voice_call_ended",{reason:e}),primaryColor:It(T),avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},logoUrl:T.logoUrl,avatar3dUrl:c?.avatar3dUrl||A?.avatar3dUrl,voiceConfig:ee,getSocket:U})})}):/* @__PURE__ */y("div",{ref:C,id:"botuyo-chat-widget-root",className:At("botuyo-chat-widget flex flex-col",!E&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...Y,...Q,pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===c?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===c?.effects?.softShadows?"false":void 0,children:[
|
|
200
|
-
/* @__PURE__ */b("div",{className:At("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",E?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",M.isOpen?"opacity-100 scale-100 h-full w-full translate-y-0 pointer-events-auto":"opacity-0 scale-[0.85] pointer-events-none translate-y-8 h-0 w-0"),style:{pointerEvents:M.isOpen?"auto":"none"},onMouseDown:G,onTouchStart:G,children:/* @__PURE__ */b(Zc,{children:/* @__PURE__ */b(Hc,{isOpen:M.isOpen,isConnected:j,isTyping:M.isTyping,messages:M.messages,onClose:K,onSendMessage:F,onSendAttachment:$,onSendLocation:B,botName:T.botName,logoUrl:T.logoUrl,welcomeMessage:T.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||A?.inputPlaceholder,position:c?.position,bubbleStyles:I,avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},mediaConfig:J,theme:T,avatar3dUrl:c?.avatar3dUrl||A?.avatar3dUrl,voiceConfig:ee,getSocket:U,suggestedQuestions:A?.suggestedQuestions,activeQuiz:q,onQuizAnswer:V,onProposalAction:(e,t)=>"confirm"===t?W(e):H(e)})})}),!_&&/* @__PURE__ */b("div",{className:At(M.isOpen?"hidden":"block",!E&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:G,onTouchStart:G,children:/* @__PURE__ */b(Wt,{isOpen:M.isOpen,onClick:R,unreadCount:L,position:c?.position||"bottom-right",primaryColor:It(T),logoUrl:T.logoUrl,starterPrompt:c?.starterPrompt||A?.starterPrompt,avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},emotion:D,styles:I,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??A?.avatarScale,showPromptAvatar:c?.showPromptAvatar??A?.showPromptAvatar})})]}):null}function
|
|
201
|
-
return b(Dt,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(
|
|
202
|
-
return b(M,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b(
|
|
203
|
-
return b("div",{style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:/* @__PURE__ */b(M,{defaultLocale:r,children:/* @__PURE__ */b(
|
|
204
|
-
/* @__PURE__ */b(
|
|
184
|
+
/* @__PURE__ */b("button",{onClick:this.handleReset,className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium hover:opacity-90 transition-opacity",children:"Intentar de nuevo"})]}):this.props.children}}const Jc={bubble:"rounded-2xl",image:"rounded-xl",button:"rounded-xl",card:"rounded-2xl"},Kc={bg:"bg-muted/50 dark:bg-muted/20",text:"text-foreground",border:"border-border/50"},Gc={text:"text-primary-foreground"};const Yc=(e,t)=>t.some(t=>e instanceof t);let Qc,Xc;const eu=/* @__PURE__ */new WeakMap,tu=/* @__PURE__ */new WeakMap,nu=/* @__PURE__ */new WeakMap;let ru={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return eu.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return au(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function ou(e){ru=e(ru)}function iu(e){return"function"==typeof e?(t=e,(Xc||(Xc=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(su(this),e),au(this.request)}:function(...e){return au(t.apply(su(this),e))}):(e instanceof IDBTransaction&&function(e){if(eu.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{t(),r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)});eu.set(e,t)}(e),Yc(e,Qc||(Qc=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,ru):e);var t}function au(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{t(au(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)});return nu.set(t,e),t}(e);if(tu.has(e))return tu.get(e);const t=iu(e);return t!==e&&(tu.set(e,t),nu.set(t,e)),t}const su=e=>nu.get(e),lu=["get","getKey","getAll","getAllKeys","count"],cu=["put","add","delete","clear"],uu=/* @__PURE__ */new Map;function du(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(uu.get(t))return uu.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=cu.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!lu.includes(n))return;const i=async function(e,...t){const i=this.transaction(e,o?"readwrite":"readonly");let a=i.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),o&&i.done]))[0]};return uu.set(t,i),i}ou(e=>({...e,get:(t,n,r)=>du(t,n)||e.get(t,n,r),has:(t,n)=>!!du(t,n)||e.has(t,n)}));const pu=["continue","continuePrimaryKey","advance"],hu={},fu=/* @__PURE__ */new WeakMap,mu=/* @__PURE__ */new WeakMap,gu={get(e,t){if(!pu.includes(t))return e[t];let n=hu[t];return n||(n=hu[t]=function(...e){fu.set(this,mu.get(this)[t](...e))}),n}};async function*bu(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,gu);for(mu.set(n,t),nu.set(n,su(t));t;)yield n,t=await(fu.get(n)||t.continue()),fu.delete(n)}function yu(e,t){return t===Symbol.asyncIterator&&Yc(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&Yc(e,[IDBIndex,IDBObjectStore])}ou(e=>({...e,get:(t,n,r)=>yu(t,n)?bu:e.get(t,n,r),has:(t,n)=>yu(t,n)||e.has(t,n)}));class vu{db=null;DB_NAME;DB_VERSION=1;constructor(e,t="default"){this.DB_NAME=`botuyo-chat-${e}-${t}`}async init(){try{this.db=await function(e,t,{blocked:n,upgrade:r,blocking:o,terminated:i}={}){const a=indexedDB.open(e,t),s=au(a);return r&&a.addEventListener("upgradeneeded",e=>{r(au(a.result),e.oldVersion,e.newVersion,au(a.transaction),e)}),n&&a.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{i&&e.addEventListener("close",()=>i()),o&&e.addEventListener("versionchange",e=>o(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}(this.DB_NAME,this.DB_VERSION,{upgrade(e){e.objectStoreNames.contains("messages")||e.createObjectStore("messages",{keyPath:"id"}).createIndex("by-timestamp","timestamp"),e.objectStoreNames.contains("metadata")||e.createObjectStore("metadata")}}),Bt("IndexedDB initialized")}catch(e){throw Ft("Failed to initialize IndexedDB:",e),e}}async saveMessage(e){this.db||await this.init();try{await this.db.put("messages",e)}catch(t){Ft("Failed to save message:",t)}}async saveMessages(e){this.db||await this.init();try{const t=this.db.transaction("messages","readwrite");await Promise.all([...e.map(e=>t.store.put(e)),t.done])}catch(t){Ft("Failed to save messages:",t)}}async getMessages(e=100){this.db||await this.init();try{return(await this.db.getAllFromIndex("messages","by-timestamp")).slice(-e)}catch(t){return Ft("Failed to get messages:",t),[]}}async getMessage(e){this.db||await this.init();try{return await this.db.get("messages",e)}catch(t){return void Ft("Failed to get message:",t)}}async deleteMessage(e){this.db||await this.init();try{await this.db.delete("messages",e)}catch(t){Ft("Failed to delete message:",t)}}async clearMessages(){this.db||await this.init();try{await this.db.clear("messages"),Bt("Messages cleared from IndexedDB")}catch(e){Ft("Failed to clear messages:",e)}}async setMetadata(e){this.db||await this.init();try{await this.db.put("metadata",e,"chat-metadata")}catch(t){Ft("Failed to set metadata:",t)}}async getMetadata(){this.db||await this.init();try{return await this.db.get("metadata","chat-metadata")}catch(e){return Ft("Failed to get metadata:",e),null}}async clearAll(){this.db||await this.init();try{await Promise.all([this.db.clear("messages"),this.db.clear("metadata")]),Bt("All data cleared from IndexedDB")}catch(e){Ft("Failed to clear all data:",e)}}async migrateFromLocalStorage(e,t="default"){try{const n=`botuyo_chat_v1_${e}_${t}`,r=localStorage.getItem(n);if(!r)return;const o=JSON.parse(r);if(o.messages&&Array.isArray(o.messages)){const e=o.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}));await this.saveMessages(e),Bt(`Migrated ${e.length} messages from localStorage`)}o.sessionId&&await this.setMetadata({sessionId:o.sessionId}),localStorage.removeItem(n),Bt("Migration from localStorage completed")}catch(n){Ft("Failed to migrate from localStorage:",n)}}}const wu=/* @__PURE__ */new Map,xu={isOpen:!1,isConnected:!1,isTyping:!1,messages:[],error:null,sessionId:null};function ku(e){const t=/* @__PURE__ */new Set,n=[];for(const r of e){if(r.id){if(t.has(r.id))continue;t.add(r.id)}n.push(r)}return n}function _u(e,t){switch(t.type){case"TOGGLE_WINDOW":return{...e,isOpen:!e.isOpen};case"OPEN_WINDOW":return{...e,isOpen:!0};case"CLOSE_WINDOW":return{...e,isOpen:!1};case"SET_CONNECTED":return{...e,isConnected:t.payload};case"SET_TYPING":return{...e,isTyping:t.payload};case"ADD_MESSAGE":{if(e.messages.some(e=>e.id===t.payload.id))return e;if(t.payload.id.startsWith("msg-")&&"text"===t.payload.type){const n=/* @__PURE__ */(new Date).getTime();if(e.messages.slice(-10).some(e=>"text"===e.type&&e.sender===t.payload.sender&&"content"in e&&"content"in t.payload&&e.content===t.payload.content&&Math.abs(n-new Date(e.timestamp).getTime())<3e4))return e}const n=[...e.messages,t.payload],r="bot"===t.payload.sender;return{...e,messages:n,isTyping:!r&&e.isTyping}}case"SET_MESSAGES":return{...e,messages:ku(t.payload)};case"SET_ERROR":return{...e,error:t.payload};case"SET_SESSION_ID":return{...e,sessionId:t.payload};case"ANSWER_QUIZ":{const{messageId:n,buttonId:r}=t.payload;return{...e,messages:e.messages.map(e=>e.id===n&&"buttons"===e.type?{...e,answered:!0,...r?{selectedId:r}:{}}:e)}}case"RESOLVE_PROPOSAL":{const{proposalId:n,status:r}=t.payload;return{...e,messages:e.messages.map(e=>"tool_proposal"===e.type&&e.proposalId===n?{...e,status:r}:e)}}case"CLEAR_CHAT":return{...xu,isOpen:e.isOpen};case"RESTORE_SESSION":return{...e,...t.payload,messages:t.payload.messages?ku(t.payload.messages):e.messages,isConnected:!1,isTyping:!1,error:null};default:return e}}function Su(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:/* @__PURE__ */new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const o=a.prototype,i=Object.keys(o);for(let e=0;e<i.length;e++){const t=i[e];t in n||(n[t]=o[t].bind(n))}}const o=n?.Parent??Object;class i extends o{}function a(e){var t;const o=n?.Parent?new i:this;r(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const n of o._zod.deferred)n();return o}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class Cu extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Eu extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const zu={};function Au(e){return zu}function Nu(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function Tu(e,t){return"bigint"==typeof t?t.toString():t}function Iu(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ou(e){return null==e}function Mu(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const Pu=/* @__PURE__ */Symbol("evaluating");function Lu(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Pu)return void 0===r&&(r=Pu,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Du(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ju(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Ru(e){return JSON.stringify(e)}const Fu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function $u(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Bu=Iu(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Uu(e){if(!1===$u(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==$u(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function qu(e){return Uu(e)?{...e}:Array.isArray(e)?[...e]:e}const Vu=/* @__PURE__ */new Set(["string","number","symbol"]);function Wu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hu(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Zu(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const Ju={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ku(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Gu(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Yu(e){return"string"==typeof e?e:e?.message}function Qu(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=Yu(e.inst?._zod.def?.error?.(e))??Yu(t?.error?.(e))??Yu(n.customError?.(e))??Yu(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Xu(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ed(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const td=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Tu,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},nd=Su("$ZodError",td),rd=Su("$ZodError",td,{Parent:Error}),od=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Cu;if(a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Qu(e,i,Au())));throw Fu(t,o?.callee),t}return a.value},id=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Qu(e,i,Au())));throw Fu(t,o?.callee),t}return a.value},ad=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Cu;return i.issues.length?{success:!1,error:new(e??nd)(i.issues.map(e=>Qu(e,o,Au())))}:{success:!0,data:i.value}},sd=/* @__PURE__ */ad(rd),ld=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>Qu(e,o,Au())))}:{success:!0,data:i.value}},cd=/* @__PURE__ */ld(rd),ud=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return od(e)(t,n,o)},dd=e=>(t,n,r)=>od(e)(t,n,r),pd=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return id(e)(t,n,o)},hd=e=>async(t,n,r)=>id(e)(t,n,r),fd=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ad(e)(t,n,o)},md=e=>(t,n,r)=>ad(e)(t,n,r),gd=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ld(e)(t,n,o)},bd=e=>async(t,n,r)=>ld(e)(t,n,r),yd=/^[cC][^\s-]{8,}$/,vd=/^[0-9a-z]+$/,wd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xd=/^[0-9a-vA-V]{20}$/,kd=/^[A-Za-z0-9]{27}$/,_d=/^[a-zA-Z0-9_-]{21}$/,Sd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ed=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,zd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ad=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Nd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Td=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Id=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Od=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Md=/^[A-Za-z0-9_-]*$/,Pd=/^\+[1-9]\d{6,14}$/,Ld="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Dd=/* @__PURE__ */new RegExp(`^${Ld}$`);function jd(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const Rd=/^-?\d+$/,Fd=/^-?\d+(?:\.\d+)?$/,$d=/^(?:true|false)$/i,Bd=/^[^A-Z]*$/,Ud=/^[^a-z]*$/,qd=/* @__PURE__ */Su("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Vd={number:"number",bigint:"bigint",object:"date"},Wd=/* @__PURE__ */Su("$ZodCheckLessThan",(e,t)=>{qd.init(e,t);const n=Vd[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Hd=/* @__PURE__ */Su("$ZodCheckGreaterThan",(e,t)=>{qd.init(e,t);const n=Vd[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Zd=/* @__PURE__ */Su("$ZodCheckMultipleOf",(e,t)=>{qd.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(0===o&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(o=Number.parseInt(e[1]))}const i=n>o?n:o;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Jd=/* @__PURE__ */Su("$ZodCheckNumberFormat",(e,t)=>{qd.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Ju[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=o,r.maximum=i,n&&(r.pattern=Rd)}),e._zod.check=a=>{const s=a.value;if(n){if(!Number.isInteger(s))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}s<o&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Kd=/* @__PURE__ */Su("$ZodCheckMaxLength",(e,t)=>{var n;qd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ou(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const o=Xu(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Gd=/* @__PURE__ */Su("$ZodCheckMinLength",(e,t)=>{var n;qd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ou(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const o=Xu(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Yd=/* @__PURE__ */Su("$ZodCheckLengthEquals",(e,t)=>{var n;qd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ou(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,o=r.length;if(o===t.length)return;const i=Xu(r),a=o>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Qd=/* @__PURE__ */Su("$ZodCheckStringFormat",(e,t)=>{var n,r;qd.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=/* @__PURE__ */new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Xd=/* @__PURE__ */Su("$ZodCheckRegex",(e,t)=>{Qd.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ep=/* @__PURE__ */Su("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Bd),Qd.init(e,t)}),tp=/* @__PURE__ */Su("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ud),Qd.init(e,t)}),np=/* @__PURE__ */Su("$ZodCheckIncludes",(e,t)=>{qd.init(e,t);const n=Wu(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),rp=/* @__PURE__ */Su("$ZodCheckStartsWith",(e,t)=>{qd.init(e,t);const n=new RegExp(`^${Wu(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),op=/* @__PURE__ */Su("$ZodCheckEndsWith",(e,t)=>{qd.init(e,t);const n=new RegExp(`.*${Wu(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),ip=/* @__PURE__ */Su("$ZodCheckOverwrite",(e,t)=>{qd.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class ap{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const o of r)this.content.push(o)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const sp={major:4,minor:3,patch:6},lp=/* @__PURE__ */Su("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=sp;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const t of o._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,o=Ku(e);for(const i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,a=i._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new Cu;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(o||(o=Ku(e,t)))});else{if(e.issues.length===t)continue;o||(o=Ku(e,t))}}return r?r.then(()=>e):e},n=(n,o,i)=>{if(Ku(n))return n.aborted=!0,n;const a=t(o,r,i);if(a instanceof Promise){if(!1===i.async)throw new Cu;return a.then(t=>e._zod.parse(t,i))}return e._zod.parse(a,i)};e._zod.run=(o,i)=>{if(i.skipChecks)return e._zod.parse(o,i);if("backward"===i.direction){const t=e._zod.parse({value:o.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,o,i)):n(t,o,i)}const a=e._zod.parse(o,i);if(a instanceof Promise){if(!1===i.async)throw new Cu;return a.then(e=>t(e,r,i))}return t(a,r,i)}}Lu(e,"~standard",()=>({validate:t=>{try{const n=sd(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return cd(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),cp=/* @__PURE__ */Su("$ZodString",(e,t)=>{var n;lp.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),up=/* @__PURE__ */Su("$ZodStringFormat",(e,t)=>{Qd.init(e,t),cp.init(e,t)}),dp=/* @__PURE__ */Su("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Cd),up.init(e,t)}),pp=/* @__PURE__ */Su("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ed(e))}else t.pattern??(t.pattern=Ed());up.init(e,t)}),hp=/* @__PURE__ */Su("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=zd),up.init(e,t)}),fp=/* @__PURE__ */Su("$ZodURL",(e,t)=>{up.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=o.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),mp=/* @__PURE__ */Su("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),up.init(e,t)}),gp=/* @__PURE__ */Su("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=_d),up.init(e,t)}),bp=/* @__PURE__ */Su("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=yd),up.init(e,t)}),yp=/* @__PURE__ */Su("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=vd),up.init(e,t)}),vp=/* @__PURE__ */Su("$ZodULID",(e,t)=>{t.pattern??(t.pattern=wd),up.init(e,t)}),wp=/* @__PURE__ */Su("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xd),up.init(e,t)}),xp=/* @__PURE__ */Su("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=kd),up.init(e,t)}),kp=/* @__PURE__ */Su("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=jd({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Ld}T(?:${r})$`)}(t)),up.init(e,t)}),_p=/* @__PURE__ */Su("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Dd),up.init(e,t)}),Sp=/* @__PURE__ */Su("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${jd(t)}$`)),up.init(e,t)}),Cp=/* @__PURE__ */Su("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Sd),up.init(e,t)}),Ep=/* @__PURE__ */Su("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ad),up.init(e,t),e._zod.bag.format="ipv4"}),zp=/* @__PURE__ */Su("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Nd),up.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Ap=/* @__PURE__ */Su("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Td),up.init(e,t)}),Np=/* @__PURE__ */Su("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Id),up.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Tp(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Ip=/* @__PURE__ */Su("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Od),up.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Tp(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Op=/* @__PURE__ */Su("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Md),up.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!Md.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Tp(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Mp=/* @__PURE__ */Su("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Pd),up.init(e,t)}),Pp=/* @__PURE__ */Su("$ZodJWT",(e,t)=>{up.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&"JWT"!==o?.typ||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Lp=/* @__PURE__ */Su("$ZodNumber",(e,t)=>{lp.init(e,t),e._zod.pattern=e._zod.bag.pattern??Fd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}const o=n.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Dp=/* @__PURE__ */Su("$ZodNumberFormat",(e,t)=>{Jd.init(e,t),Lp.init(e,t)}),jp=/* @__PURE__ */Su("$ZodBoolean",(e,t)=>{lp.init(e,t),e._zod.pattern=$d,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}const o=n.value;return"boolean"==typeof o||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Rp=/* @__PURE__ */Su("$ZodAny",(e,t)=>{lp.init(e,t),e._zod.parse=e=>e}),Fp=/* @__PURE__ */Su("$ZodUnknown",(e,t)=>{lp.init(e,t),e._zod.parse=e=>e}),$p=/* @__PURE__ */Su("$ZodNever",(e,t)=>{lp.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Bp(e,t,n){e.issues.length&&t.issues.push(...Gu(n,e.issues)),t.value[n]=e.value}const Up=/* @__PURE__ */Su("$ZodArray",(e,t)=>{lp.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const a=o[e],s=t.element._zod.run({value:a,issues:[]},r);s instanceof Promise?i.push(s.then(t=>Bp(t,n,e))):Bp(s,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function qp(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...Gu(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function Vp(e){const t=Object.keys(e.shape);for(const o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Wp(e,t,n,r,o,i){const a=[],s=o.keySet,l=o.catchall._zod,c=l.def.type,u="optional"===l.optout;for(const d in t){if(s.has(d))continue;if("never"===c){a.push(d);continue}const o=l.run({value:t[d],issues:[]},r);o instanceof Promise?e.push(o.then(e=>qp(e,n,d,t,u))):qp(o,n,d,t,u)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const Hp=/* @__PURE__ */Su("$ZodObject",(e,t)=>{lp.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=Iu(()=>Vp(t));Lu(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */new Set);for(const e of r.values)n[t].add(e)}}return n});const o=$u,i=t.catchall;let a;e._zod.parse=(t,n)=>{a??(a=r.value);const s=t.value;if(!o(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};const l=[],c=a.shape;for(const e of a.keys){const r=c[e],o="optional"===r._zod.optout,i=r._zod.run({value:s[e],issues:[]},n);i instanceof Promise?l.push(i.then(n=>qp(n,t,e,s,o))):qp(i,t,e,s,o)}return i?Wp(l,s,t,n,r.value,e):l.length?Promise.all(l).then(()=>t):t}}),Zp=/* @__PURE__ */Su("$ZodObjectJIT",(e,t)=>{Hp.init(e,t);const n=e._zod.parse,r=Iu(()=>Vp(t));let o;const i=$u,a=!zu.jitless,s=a&&Bu.value,l=t.catchall;let c;e._zod.parse=(u,d)=>{c??(c=r.value);const p=u.value;return i(p)?a&&s&&!1===d?.async&&!0!==d.jitless?(o||(o=(e=>{const t=new ap(["shape","payload","ctx"]),n=r.value,o=e=>{const t=Ru(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=/* @__PURE__ */Object.create(null);let a=0;for(const r of n.keys)i[r]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=i[r],a=Ru(r),s=e[r],l="optional"===s?._zod?.optout;t.write(`const ${n} = ${o(r)};`),l?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const s=t.compile();return(t,n)=>s(e,t,n)})(t.shape)),u=o(u,d),l?Wp([],p,u,d,c,e):u):n(u,d):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function Jp(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const o=e.filter(e=>!Ku(e));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Qu(e,r,Au())))}),t)}const Kp=/* @__PURE__ */Su("$ZodUnion",(e,t)=>{lp.init(e,t),Lu(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Lu(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Lu(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Lu(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>Mu(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n)return r(o,i);let a=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:o.value,issues:[]},i);if(t instanceof Promise)s.push(t),a=!0;else{if(0===t.issues.length)return t;s.push(t)}}return a?Promise.all(s).then(t=>Jp(t,o,e,i)):Jp(s,o,e,i)}}),Gp=/* @__PURE__ */Su("$ZodIntersection",(e,t)=>{lp.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([t,n])=>Qp(e,t,n)):Qp(e,o,i)}});function Yp(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Uu(e)&&Uu(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),o={...e,...t};for(const i of r){const n=Yp(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};o[i]=n.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=Yp(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Qp(e,t,n){const r=/* @__PURE__ */new Map;let o;for(const s of t.issues)if("unrecognized_keys"===s.code){o??(o=s);for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(s);for(const s of n.issues)if("unrecognized_keys"===s.code)for(const e of s.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(s);const i=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(i.length&&o&&e.issues.push({...o,keys:i}),Ku(e))return e;const a=Yp(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}const Xp=/* @__PURE__ */Su("$ZodRecord",(e,t)=>{lp.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Uu(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[],a=t.keyType._zod.values;if(a){n.value={};const s=/* @__PURE__ */new Set;for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){s.add("number"==typeof e?e.toString():e);const a=t.valueType._zod.run({value:o[e],issues:[]},r);a instanceof Promise?i.push(a.then(t=>{t.issues.length&&n.issues.push(...Gu(e,t.issues)),n.value[e]=t.value})):(a.issues.length&&n.issues.push(...Gu(e,a.issues)),n.value[e]=a.value)}let l;for(const e in o)s.has(e)||(l=l??[],l.push(e));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:l})}else{n.value={};for(const a of Reflect.ownKeys(o)){if("__proto__"===a)continue;let s=t.keyType._zod.run({value:a,issues:[]},r);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof a&&Fd.test(a)&&s.issues.length){const e=t.keyType._zod.run({value:Number(a),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(s=e)}if(s.issues.length){"loose"===t.mode?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(e=>Qu(e,r,Au())),input:a,path:[a],inst:e});continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?i.push(l.then(e=>{e.issues.length&&n.issues.push(...Gu(a,e.issues)),n.value[s.value]=e.value})):(l.issues.length&&n.issues.push(...Gu(a,l.issues)),n.value[s.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),eh=/* @__PURE__ */Su("$ZodEnum",(e,t)=>{lp.init(e,t);const n=Nu(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>Vu.has(typeof e)).map(e=>"string"==typeof e?Wu(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}}),th=/* @__PURE__ */Su("$ZodTransform",(e,t)=>{lp.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Eu(e.constructor.name);const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n));if(o instanceof Promise)throw new Cu;return n.value=o,n}});function nh(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const rh=/* @__PURE__ */Su("$ZodOptional",(e,t)=>{lp.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Lu(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,void 0]):void 0),Lu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Mu(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>nh(t,e.value)):nh(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),oh=/* @__PURE__ */Su("$ZodExactOptional",(e,t)=>{rh.init(e,t),Lu(e._zod,"values",()=>t.innerType._zod.values),Lu(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ih=/* @__PURE__ */Su("$ZodNullable",(e,t)=>{lp.init(e,t),Lu(e._zod,"optin",()=>t.innerType._zod.optin),Lu(e._zod,"optout",()=>t.innerType._zod.optout),Lu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Mu(e.source)}|null)$`):void 0}),Lu(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),ah=/* @__PURE__ */Su("$ZodDefault",(e,t)=>{lp.init(e,t),e._zod.optin="optional",Lu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>sh(e,t)):sh(r,t)}});function sh(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const lh=/* @__PURE__ */Su("$ZodPrefault",(e,t)=>{lp.init(e,t),e._zod.optin="optional",Lu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ch=/* @__PURE__ */Su("$ZodNonOptional",(e,t)=>{lp.init(e,t),Lu(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(t=>uh(t,e)):uh(o,e)}});function uh(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const dh=/* @__PURE__ */Su("$ZodCatch",(e,t)=>{lp.init(e,t),Lu(e._zod,"optin",()=>t.innerType._zod.optin),Lu(e._zod,"optout",()=>t.innerType._zod.optout),Lu(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Qu(e,n,Au()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Qu(e,n,Au()))},input:e.value}),e.issues=[]),e)}}),ph=/* @__PURE__ */Su("$ZodPipe",(e,t)=>{lp.init(e,t),Lu(e._zod,"values",()=>t.in._zod.values),Lu(e._zod,"optin",()=>t.in._zod.optin),Lu(e._zod,"optout",()=>t.out._zod.optout),Lu(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>hh(e,t.in,n)):hh(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>hh(e,t.out,n)):hh(r,t.out,n)}});function hh(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const fh=/* @__PURE__ */Su("$ZodReadonly",(e,t)=>{lp.init(e,t),Lu(e._zod,"propValues",()=>t.innerType._zod.propValues),Lu(e._zod,"values",()=>t.innerType._zod.values),Lu(e._zod,"optin",()=>t.innerType?._zod?.optin),Lu(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(mh):mh(r)}});function mh(e){return e.value=Object.freeze(e.value),e}const gh=/* @__PURE__ */Su("$ZodCustom",(e,t)=>{qd.init(e,t),lp.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(t=>bh(t,n,r,e));bh(o,n,r,e)}});function bh(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ed(e))}}var yh;(yh=globalThis).__zod_globalRegistry??(yh.__zod_globalRegistry=new class{constructor(){this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const vh=globalThis.__zod_globalRegistry;function wh(e,t){return new e({type:"string",...Zu(t)})}function xh(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Zu(t)})}function kh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Zu(t)})}function _h(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Zu(t)})}function Sh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Zu(t)})}function Ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Zu(t)})}function Eh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Zu(t)})}function zh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Zu(t)})}function Ah(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Zu(t)})}function Nh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Zu(t)})}function Th(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Zu(t)})}function Ih(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Zu(t)})}function Oh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Zu(t)})}function Mh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Zu(t)})}function Ph(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Zu(t)})}function Lh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Zu(t)})}function Dh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Zu(t)})}function jh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Zu(t)})}function Rh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Zu(t)})}function Fh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Zu(t)})}function $h(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Zu(t)})}function Bh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Zu(t)})}function Uh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Zu(t)})}function qh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Zu(t)})}function Vh(e,t){return new e({type:"string",format:"date",check:"string_format",...Zu(t)})}function Wh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Zu(t)})}function Hh(e,t){return new e({type:"string",format:"duration",check:"string_format",...Zu(t)})}function Zh(e,t){return new e({type:"number",checks:[],...Zu(t)})}function Jh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Zu(t)})}function Kh(e,t){return new e({type:"boolean",...Zu(t)})}function Gh(e){return new e({type:"any"})}function Yh(e){return new e({type:"unknown"})}function Qh(e,t){return new e({type:"never",...Zu(t)})}function Xh(e,t){return new Wd({check:"less_than",...Zu(t),value:e,inclusive:!1})}function ef(e,t){return new Wd({check:"less_than",...Zu(t),value:e,inclusive:!0})}function tf(e,t){return new Hd({check:"greater_than",...Zu(t),value:e,inclusive:!1})}function nf(e,t){return new Hd({check:"greater_than",...Zu(t),value:e,inclusive:!0})}function rf(e,t){return new Zd({check:"multiple_of",...Zu(t),value:e})}function of(e,t){return new Kd({check:"max_length",...Zu(t),maximum:e})}function af(e,t){return new Gd({check:"min_length",...Zu(t),minimum:e})}function sf(e,t){return new Yd({check:"length_equals",...Zu(t),length:e})}function lf(e,t){return new Xd({check:"string_format",format:"regex",...Zu(t),pattern:e})}function cf(e){return new ep({check:"string_format",format:"lowercase",...Zu(e)})}function uf(e){return new tp({check:"string_format",format:"uppercase",...Zu(e)})}function df(e,t){return new np({check:"string_format",format:"includes",...Zu(t),includes:e})}function pf(e,t){return new rp({check:"string_format",format:"starts_with",...Zu(t),prefix:e})}function hf(e,t){return new op({check:"string_format",format:"ends_with",...Zu(t),suffix:e})}function ff(e){return new ip({check:"overwrite",tx:e})}function mf(e){/* @__PURE__ */
|
|
185
|
+
return ff(t=>t.normalize(e))}function gf(){/* @__PURE__ */
|
|
186
|
+
return ff(e=>e.trim())}function bf(){/* @__PURE__ */
|
|
187
|
+
return ff(e=>e.toLowerCase())}function yf(){/* @__PURE__ */
|
|
188
|
+
return ff(e=>e.toUpperCase())}function vf(){/* @__PURE__ */
|
|
189
|
+
return ff(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e))}function wf(e,t,n){return new e({type:"array",element:t,...Zu(n)})}function xf(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Zu(n)})}function kf(e){const t=/* @__PURE__ */_f(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(ed(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(ed(r))}},e(n.value,n)));return t}function _f(e,t){const n=new qd({check:"custom",...Zu(t)});return n._zod.check=e,n}function Sf(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??vh,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:/* @__PURE__ */new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Cf(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,i=t.processors[o.type];if(!i)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);i(e,t,n,r)}const i=e._zod.parent;i&&(a.ref||(a.ref=i),Cf(i,t,r),t.seen.get(i).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),"input"===t.io&&Af(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Ef(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=/* @__PURE__ */new Map;for(const i of e.seen.entries()){const t=e.metadataRegistry.get(i[0])?.id;if(t){const e=r.get(t);if(e&&e!==i[0])throw new Error(`Duplicate schema id "${t}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(t,i[0])}}const o=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:o,defId:i}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,o=e.external.uri??(e=>e);if(n)return{ref:o(n)};const i=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=i,{defId:i,ref:`${o("__shared")}#/${r}/${i}`}}if(t[1]===n)return{ref:"#"};const o=`#/${r}/`,i=t[1].schema.id??"__schema"+e.counter++;return{defId:i,ref:o+i}})(t);r.def={...r.schema},i&&(r.defId=i);const a=r.schema;for(const e in a)delete a[e];a.$ref=o};if("throw"===e.cycles)for(const i of e.seen.entries()){const e=i[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const n=i[1];if(t===i[0]){o(i);continue}if(e.external){const n=e.external.registry.get(i[0])?.id;if(t!==i[0]&&n){o(i);continue}}const r=e.metadataRegistry.get(i[0])?.id;(r||n.cycle||n.count>1&&"ref"===e.reused)&&o(i)}}function zf(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const o=n.def??n.schema,i={...o},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),s=n.schema;if(!s.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(o,s):(o.allOf=o.allOf??[],o.allOf.push(s)),Object.assign(o,i),t._zod.parent===a)for(const e in o)"$ref"!==e&&"allOf"!==e&&(e in i||delete o[e]);if(s.$ref&&n.def)for(const e in o)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(o[e])===JSON.stringify(n.def[e])&&delete o[e]}const s=t._zod.parent;if(s&&s!==a){r(s);const t=e.seen.get(s);if(t?.schema.$ref&&(o.$ref=t.schema.$ref,t.def))for(const e in o)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(o[e])===JSON.stringify(t.def[e])&&delete o[e]}e.override({zodSchema:t,jsonSchema:o,path:n.path??[]})};for(const s of[...e.seen.entries()].reverse())r(s[0]);const o={};if("draft-2020-12"===e.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?o.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(n)}Object.assign(o,n.def??n.schema);const i=e.external?.defs??{};for(const s of e.seen.entries()){const e=s[1];e.def&&e.defId&&(i[e.defId]=e.def)}e.external||Object.keys(i).length>0&&("draft-2020-12"===e.target?o.$defs=i:o.definitions=i);try{const n=JSON.parse(JSON.stringify(o));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:Nf(t,"input",e.processors),output:Nf(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(a){throw new Error("Error converting schema to JSON.")}}function Af(e,t){const n=t??{seen:/* @__PURE__ */new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return Af(r.element,n);if("set"===r.type)return Af(r.valueType,n);if("lazy"===r.type)return Af(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return Af(r.innerType,n);if("intersection"===r.type)return Af(r.left,n)||Af(r.right,n);if("record"===r.type||"map"===r.type)return Af(r.keyType,n)||Af(r.valueType,n);if("pipe"===r.type)return Af(r.in,n)||Af(r.out,n);if("object"===r.type){for(const e in r.shape)if(Af(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(Af(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(Af(e,n))return!0;return!(!r.rest||!Af(r.rest,n))}return!1}const Nf=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},a=Sf({...o??{},target:i,io:t,processors:n});return Cf(e,a),Ef(a,e),zf(a,e)},Tf={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},If=(e,t,n,r)=>{const o=e._zod.def;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType},Of=/* @__PURE__ */Su("ZodISODateTime",(e,t)=>{kp.init(e,t),Xf.init(e,t)}),Mf=/* @__PURE__ */Su("ZodISODate",(e,t)=>{_p.init(e,t),Xf.init(e,t)}),Pf=/* @__PURE__ */Su("ZodISOTime",(e,t)=>{Sp.init(e,t),Xf.init(e,t)}),Lf=/* @__PURE__ */Su("ZodISODuration",(e,t)=>{Cp.init(e,t),Xf.init(e,t)}),Df=Su("ZodError",(e,t)=>{nd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const o of e.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(e=>r({issues:e}));else if("invalid_key"===o.code)r({issues:o.issues});else if("invalid_element"===o.code)r({issues:o.issues});else if(0===o.path.length)n._errors.push(t(o));else{let e=n,r=0;for(;r<o.path.length;){const n=o.path[r];r===o.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(o))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Tu,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Tu,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),jf=/* @__PURE__ */od(Df),Rf=/* @__PURE__ */id(Df),Ff=/* @__PURE__ */ad(Df),$f=/* @__PURE__ */ld(Df),Bf=/* @__PURE__ */ud(Df),Uf=/* @__PURE__ */dd(Df),qf=/* @__PURE__ */pd(Df),Vf=/* @__PURE__ */hd(Df),Wf=/* @__PURE__ */fd(Df),Hf=/* @__PURE__ */md(Df),Zf=/* @__PURE__ */gd(Df),Jf=/* @__PURE__ */bd(Df),Kf=/* @__PURE__ */Su("ZodType",(e,t)=>(lp.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Nf(e,"input"),output:Nf(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Sf({...n,processors:t});return Cf(e,r),Ef(r,e),zf(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(ju(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>Hu(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>jf(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ff(e,t,n),e.parseAsync=async(t,n)=>Rf(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>$f(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Bf(e,t,n),e.decode=(t,n)=>Uf(e,t,n),e.encodeAsync=async(t,n)=>qf(e,t,n),e.decodeAsync=async(t,n)=>Vf(e,t,n),e.safeEncode=(t,n)=>Wf(e,t,n),e.safeDecode=(t,n)=>Hf(e,t,n),e.safeEncodeAsync=async(t,n)=>Zf(e,t,n),e.safeDecodeAsync=async(t,n)=>Jf(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){/* @__PURE__ */
|
|
190
|
+
return xf(Gm,e,t)}(t,n)),e.superRefine=t=>e.check(/* @__PURE__ */kf(t)),e.overwrite=t=>e.check(/* @__PURE__ */ff(t)),e.optional=()=>Fm(e),e.exactOptional=()=>new $m({type:"optional",innerType:e}),e.nullable=()=>Um(e),e.nullish=()=>Fm(Um(e)),e.nonoptional=t=>function(e,t){return new Wm({type:"nonoptional",innerType:e,...Zu(t)})}(e,t),e.array=()=>Nm(e),e.or=t=>new Om({type:"union",options:[e,t],...Zu(void 0)}),e.and=t=>new Mm({type:"intersection",left:e,right:t}),e.transform=t=>Jm(e,new jm({type:"transform",transform:t})),e.default=t=>{return n=t,new qm({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():qu(n)}});var n},e.prefault=t=>{return n=t,new Vm({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():qu(n)}});var n},e.catch=t=>{return new Hm({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>Jm(e,t),e.readonly=()=>new Km({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return vh.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>vh.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return vh.get(e);const n=e.clone();return vh.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Gf=/* @__PURE__ */Su("_ZodString",(e,t)=>{cp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:o,maximum:i,format:a,patterns:s,contentEncoding:l}=e._zod.bag;if("number"==typeof o&&(r.minLength=o),"number"==typeof i&&(r.maxLength=i),a&&(r.format=Tf[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),l&&(r.contentEncoding=l),s&&s.size>0){const e=[...s];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(/* @__PURE__ */lf(...t)),e.includes=(...t)=>e.check(/* @__PURE__ */df(...t)),e.startsWith=(...t)=>e.check(/* @__PURE__ */pf(...t)),e.endsWith=(...t)=>e.check(/* @__PURE__ */hf(...t)),e.min=(...t)=>e.check(/* @__PURE__ */af(...t)),e.max=(...t)=>e.check(/* @__PURE__ */of(...t)),e.length=(...t)=>e.check(/* @__PURE__ */sf(...t)),e.nonempty=(...t)=>e.check(/* @__PURE__ */af(1,...t)),e.lowercase=t=>e.check(/* @__PURE__ */cf(t)),e.uppercase=t=>e.check(/* @__PURE__ */uf(t)),e.trim=()=>e.check(/* @__PURE__ */gf()),e.normalize=(...t)=>e.check(/* @__PURE__ */mf(...t)),e.toLowerCase=()=>e.check(/* @__PURE__ */bf()),e.toUpperCase=()=>e.check(/* @__PURE__ */yf()),e.slugify=()=>e.check(/* @__PURE__ */vf())}),Yf=/* @__PURE__ */Su("ZodString",(e,t)=>{cp.init(e,t),Gf.init(e,t),e.email=t=>e.check(/* @__PURE__ */xh(em,t)),e.url=t=>e.check(/* @__PURE__ */zh(rm,t)),e.jwt=t=>e.check(/* @__PURE__ */Uh(ym,t)),e.emoji=t=>e.check(/* @__PURE__ */Ah(om,t)),e.guid=t=>e.check(/* @__PURE__ */kh(tm,t)),e.uuid=t=>e.check(/* @__PURE__ */_h(nm,t)),e.uuidv4=t=>e.check(/* @__PURE__ */Sh(nm,t)),e.uuidv6=t=>e.check(/* @__PURE__ */Ch(nm,t)),e.uuidv7=t=>e.check(/* @__PURE__ */Eh(nm,t)),e.nanoid=t=>e.check(/* @__PURE__ */Nh(im,t)),e.guid=t=>e.check(/* @__PURE__ */kh(tm,t)),e.cuid=t=>e.check(/* @__PURE__ */Th(am,t)),e.cuid2=t=>e.check(/* @__PURE__ */Ih(sm,t)),e.ulid=t=>e.check(/* @__PURE__ */Oh(lm,t)),e.base64=t=>e.check(/* @__PURE__ */Fh(mm,t)),e.base64url=t=>e.check(/* @__PURE__ */$h(gm,t)),e.xid=t=>e.check(/* @__PURE__ */Mh(cm,t)),e.ksuid=t=>e.check(/* @__PURE__ */Ph(um,t)),e.ipv4=t=>e.check(/* @__PURE__ */Lh(dm,t)),e.ipv6=t=>e.check(/* @__PURE__ */Dh(pm,t)),e.cidrv4=t=>e.check(/* @__PURE__ */jh(hm,t)),e.cidrv6=t=>e.check(/* @__PURE__ */Rh(fm,t)),e.e164=t=>e.check(/* @__PURE__ */Bh(bm,t)),e.datetime=t=>e.check(function(e){/* @__PURE__ */
|
|
191
|
+
return qh(Of,e)}(t)),e.date=t=>e.check(function(e){/* @__PURE__ */
|
|
192
|
+
return Vh(Mf,e)}(t)),e.time=t=>e.check(function(e){/* @__PURE__ */
|
|
193
|
+
return Wh(Pf,e)}(t)),e.duration=t=>e.check(function(e){/* @__PURE__ */
|
|
194
|
+
return Hh(Lf,e)}(t))});function Qf(e){/* @__PURE__ */
|
|
195
|
+
return wh(Yf,e)}const Xf=/* @__PURE__ */Su("ZodStringFormat",(e,t)=>{up.init(e,t),Gf.init(e,t)}),em=/* @__PURE__ */Su("ZodEmail",(e,t)=>{hp.init(e,t),Xf.init(e,t)}),tm=/* @__PURE__ */Su("ZodGUID",(e,t)=>{dp.init(e,t),Xf.init(e,t)}),nm=/* @__PURE__ */Su("ZodUUID",(e,t)=>{pp.init(e,t),Xf.init(e,t)}),rm=/* @__PURE__ */Su("ZodURL",(e,t)=>{fp.init(e,t),Xf.init(e,t)}),om=/* @__PURE__ */Su("ZodEmoji",(e,t)=>{mp.init(e,t),Xf.init(e,t)}),im=/* @__PURE__ */Su("ZodNanoID",(e,t)=>{gp.init(e,t),Xf.init(e,t)}),am=/* @__PURE__ */Su("ZodCUID",(e,t)=>{bp.init(e,t),Xf.init(e,t)}),sm=/* @__PURE__ */Su("ZodCUID2",(e,t)=>{yp.init(e,t),Xf.init(e,t)}),lm=/* @__PURE__ */Su("ZodULID",(e,t)=>{vp.init(e,t),Xf.init(e,t)}),cm=/* @__PURE__ */Su("ZodXID",(e,t)=>{wp.init(e,t),Xf.init(e,t)}),um=/* @__PURE__ */Su("ZodKSUID",(e,t)=>{xp.init(e,t),Xf.init(e,t)}),dm=/* @__PURE__ */Su("ZodIPv4",(e,t)=>{Ep.init(e,t),Xf.init(e,t)}),pm=/* @__PURE__ */Su("ZodIPv6",(e,t)=>{zp.init(e,t),Xf.init(e,t)}),hm=/* @__PURE__ */Su("ZodCIDRv4",(e,t)=>{Ap.init(e,t),Xf.init(e,t)}),fm=/* @__PURE__ */Su("ZodCIDRv6",(e,t)=>{Np.init(e,t),Xf.init(e,t)}),mm=/* @__PURE__ */Su("ZodBase64",(e,t)=>{Ip.init(e,t),Xf.init(e,t)}),gm=/* @__PURE__ */Su("ZodBase64URL",(e,t)=>{Op.init(e,t),Xf.init(e,t)}),bm=/* @__PURE__ */Su("ZodE164",(e,t)=>{Mp.init(e,t),Xf.init(e,t)}),ym=/* @__PURE__ */Su("ZodJWT",(e,t)=>{Pp.init(e,t),Xf.init(e,t)}),vm=/* @__PURE__ */Su("ZodNumber",(e,t)=>{Lp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:o,maximum:i,format:a,multipleOf:s,exclusiveMaximum:l,exclusiveMinimum:c}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number","number"==typeof c&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),"number"==typeof o&&(r.minimum=o,"number"==typeof c&&"draft-04"!==t.target&&(c>=o?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof l&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),"number"==typeof i&&(r.maximum=i,"number"==typeof l&&"draft-04"!==t.target&&(l<=i?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof s&&(r.multipleOf=s)})(e,t,n),e.gt=(t,n)=>e.check(/* @__PURE__ */tf(t,n)),e.gte=(t,n)=>e.check(/* @__PURE__ */nf(t,n)),e.min=(t,n)=>e.check(/* @__PURE__ */nf(t,n)),e.lt=(t,n)=>e.check(/* @__PURE__ */Xh(t,n)),e.lte=(t,n)=>e.check(/* @__PURE__ */ef(t,n)),e.max=(t,n)=>e.check(/* @__PURE__ */ef(t,n)),e.int=t=>e.check(km(t)),e.safe=t=>e.check(km(t)),e.positive=t=>e.check(/* @__PURE__ */tf(0,t)),e.nonnegative=t=>e.check(/* @__PURE__ */nf(0,t)),e.negative=t=>e.check(/* @__PURE__ */Xh(0,t)),e.nonpositive=t=>e.check(/* @__PURE__ */ef(0,t)),e.multipleOf=(t,n)=>e.check(/* @__PURE__ */rf(t,n)),e.step=(t,n)=>e.check(/* @__PURE__ */rf(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function wm(e){/* @__PURE__ */
|
|
196
|
+
return Zh(vm,e)}const xm=/* @__PURE__ */Su("ZodNumberFormat",(e,t)=>{Dp.init(e,t),vm.init(e,t)});function km(e){/* @__PURE__ */
|
|
197
|
+
return Jh(xm,e)}const _m=/* @__PURE__ */Su("ZodBoolean",(e,t)=>{jp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)}),Sm=/* @__PURE__ */Su("ZodAny",(e,t)=>{Rp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}}),Cm=/* @__PURE__ */Su("ZodUnknown",(e,t)=>{Fp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Em(){/* @__PURE__ */
|
|
198
|
+
return Yh(Cm)}const zm=/* @__PURE__ */Su("ZodNever",(e,t)=>{$p.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),Am=/* @__PURE__ */Su("ZodArray",(e,t)=>{Up.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;"number"==typeof a&&(o.minItems=a),"number"==typeof s&&(o.maxItems=s),o.type="array",o.items=Cf(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */af(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */af(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */of(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */sf(t,n)),e.unwrap=()=>e.element});function Nm(e,t){/* @__PURE__ */
|
|
199
|
+
return wf(Am,e,t)}const Tm=/* @__PURE__ */Su("ZodObject",(e,t)=>{Zp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const a=i.shape;for(const c in a)o.properties[c]=Cf(a[c],t,{...r,path:[...r.path,"properties",c]});const s=new Set(Object.keys(a)),l=new Set([...s].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));l.size>0&&(o.required=Array.from(l)),"never"===i.catchall?._zod.def.type?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Cf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),Lu(e,"shape",()=>t.shape),e.keyof=()=>Dm(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Em()}),e.loose=()=>e.clone({...e._zod.def,catchall:Em()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */Qh(zm,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Uu(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=ju(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Du(this,"shape",n),n}});return Hu(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Uu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ju(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Du(this,"shape",n),n}});return Hu(e,n)}(e,t),e.merge=t=>function(e,t){const n=ju(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Du(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Hu(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return Hu(e,ju(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Du(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=ju(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Du(this,"shape",r),r},checks:[]});return Hu(e,o)}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=ju(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Du(this,"shape",o),o},checks:[]});return Hu(t,o)}(Rm,e,t[0]),e.required=(...t)=>function(e,t,n){const r=ju(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)o[t]=new e({type:"nonoptional",innerType:r[t]});return Du(this,"shape",o),o}});return Hu(t,r)}(Wm,e,t[0])});function Im(e,t){const n={type:"object",shape:e??{},...Zu(t)};return new Tm(n)}const Om=/* @__PURE__ */Su("ZodUnion",(e,t)=>{Kp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=!1===o.inclusive,a=o.options.map((e,n)=>Cf(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options}),Mm=/* @__PURE__ */Su("ZodIntersection",(e,t)=>{Gp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Cf(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=Cf(o.right,t,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length,l=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];n.allOf=l})(e,t,n,r)}),Pm=/* @__PURE__ */Su("ZodRecord",(e,t)=>{Xp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object";const a=i.keyType,s=a._zod.bag,l=s?.patterns;if("loose"===i.mode&&l&&l.size>0){const e=Cf(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const t of l)o.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(o.propertyNames=Cf(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=Cf(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=a._zod.values;if(c){const e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(o.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType}),Lm=/* @__PURE__ */Su("ZodEnum",(e,t)=>{eh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Nu(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);o[i]=t.entries[i]}return new Lm({...t,checks:[],...Zu(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new Lm({...t,checks:[],...Zu(r),entries:o})}});function Dm(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Lm({type:"enum",entries:n,...Zu(t)})}const jm=/* @__PURE__ */Su("ZodTransform",(e,t)=>{th.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Eu(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(ed(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(ed(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),Rm=/* @__PURE__ */Su("ZodOptional",(e,t)=>{rh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>If(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Fm(e){return new Rm({type:"optional",innerType:e})}const $m=/* @__PURE__ */Su("ZodExactOptional",(e,t)=>{oh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>If(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Bm=/* @__PURE__ */Su("ZodNullable",(e,t)=>{ih.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Cf(o.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Um(e){return new Bm({type:"nullable",innerType:e})}const qm=/* @__PURE__ */Su("ZodDefault",(e,t)=>{ah.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Vm=/* @__PURE__ */Su("ZodPrefault",(e,t)=>{lh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Wm=/* @__PURE__ */Su("ZodNonOptional",(e,t)=>{ch.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Hm=/* @__PURE__ */Su("ZodCatch",(e,t)=>{dh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Zm=/* @__PURE__ */Su("ZodPipe",(e,t)=>{ph.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i="input"===t.io?"transform"===o.in._zod.def.type?o.out:o.in:o.out;Cf(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function Jm(e,t){return new Zm({type:"pipe",in:e,out:t})}const Km=/* @__PURE__ */Su("ZodReadonly",(e,t)=>{fh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Gm=/* @__PURE__ */Su("ZodCustom",(e,t)=>{gh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)}),Ym=/* @__PURE__ */Object.create(null);Ym.open="0",Ym.close="1",Ym.ping="2",Ym.pong="3",Ym.message="4",Ym.upgrade="5",Ym.noop="6";const Qm=/* @__PURE__ */Object.create(null);Object.keys(Ym).forEach(e=>{Qm[Ym[e]]=e});const Xm={type:"error",data:"parser error"},eg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),tg="function"==typeof ArrayBuffer,ng=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rg=({type:e,data:t},n,r)=>eg&&t instanceof Blob?n?r(t):og(t,r):tg&&(t instanceof ArrayBuffer||ng(t))?n?r(t):og(new Blob([t]),r):r(Ym[e]+(t||"")),og=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function ig(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ag;const sg="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let ny=0;ny<64;ny++)sg["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(ny)]=ny;const lg="function"==typeof ArrayBuffer,cg=(e,t)=>{if("string"!=typeof e)return{type:"message",data:dg(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:ug(e.substring(1),t)}:Qm[n]?e.length>1?{type:Qm[n],data:e.substring(1)}:{type:Qm[n]}:Xm},ug=(e,t)=>{if(lg){const n=(e=>{let t,n,r,o,i,a=.75*e.length,s=e.length,l=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);const c=new ArrayBuffer(a),u=new Uint8Array(c);for(t=0;t<s;t+=4)n=sg[e.charCodeAt(t)],r=sg[e.charCodeAt(t+1)],o=sg[e.charCodeAt(t+2)],i=sg[e.charCodeAt(t+3)],u[l++]=n<<2|r>>4,u[l++]=(15&r)<<4|o>>2,u[l++]=(3&o)<<6|63&i;return c})(e);return dg(n,t)}return{base64:!0,data:e}},dg=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,pg=String.fromCharCode(30);let hg;function fg(e){return e.reduce((e,t)=>e+t.length,0)}function mg(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;o<t;o++)n[o]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function gg(e){if(e)return function(e){for(var t in gg.prototype)e[t]=gg.prototype[t];return e}(e)}gg.prototype.on=gg.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},gg.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},gg.prototype.off=gg.prototype.removeListener=gg.prototype.removeAllListeners=gg.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<r.length;o++)if((n=r[o])===t||n.fn===t){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},gg.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,t)}return this},gg.prototype.emitReserved=gg.prototype.emit,gg.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},gg.prototype.hasListeners=function(e){return!!this.listeners(e).length};const bg="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),yg="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function vg(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const wg=yg.setTimeout,xg=yg.clearTimeout;function kg(e,t){t.useNativeTimers?(e.setTimeoutFn=wg.bind(yg),e.clearTimeoutFn=xg.bind(yg)):(e.setTimeoutFn=yg.setTimeout.bind(yg),e.clearTimeoutFn=yg.clearTimeout.bind(yg))}function _g(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,o=e.length;r<o;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function Sg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Cg extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Eg extends gg{constructor(e){super(),this.writable=!1,kg(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new Cg(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=cg(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class zg extends Eg{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(pg),r=[];for(let o=0;o<n.length;o++){const e=cg(n[o],t);if(r.push(e),"error"===e.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((e,i)=>{rg(e,!1,e=>{r[i]=e,++o===n&&t(r.join(pg))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Sg()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Ag=!1;try{Ag="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(ty){}const Ng=Ag;function Tg(){}class Ig extends zg{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class Og extends gg{constructor(e,t,n){super(),this.createRequest=e,kg(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=vg(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(r){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(r){}try{n.setRequestHeader("Accept","*/*")}catch(r){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(r){return void this.setTimeoutFn(()=>{this._onError(r)},0)}"undefined"!=typeof document&&(this._index=Og.requestsCount++,Og.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Tg,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Og.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function Mg(){for(let e in Og.requests)Og.requests.hasOwnProperty(e)&&Og.requests[e].abort()}Og.requestsCount=0,Og.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Mg):"function"==typeof addEventListener&&addEventListener("onpagehide"in yg?"pagehide":"unload",Mg,!1));const Pg=function(){const e=Lg({xdomain:!1});return e&&null!==e.responseType}();function Lg(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Ng))return new XMLHttpRequest}catch(n){}if(!t)try{return new(yg[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const Dg="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class jg extends Eg{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Dg?{}:vg(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(ty){return this.emitReserved("error",ty)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;rg(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&bg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Sg()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Rg=yg.WebSocket||yg.MozWebSocket,Fg={websocket:class extends jg{createSocket(e,t,n){return Dg?new Rg(e,t,n):t?new Rg(e,t):new Rg(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Eg{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(ty){return this.emitReserved("error",ty)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){hg||(hg=new TextDecoder);const n=[];let r=0,o=-1,i=!1;return new TransformStream({transform(a,s){for(n.push(a);;){if(0===r){if(fg(n)<1)break;const e=mg(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(fg(n)<2)break;const e=mg(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(fg(n)<8)break;const e=mg(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(Xm);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(fg(n)<o)break;const e=mg(n,o);s.enqueue(cg(i?e:hg.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(Xm);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){eg&&e.data instanceof Blob?e.data.arrayBuffer().then(ig).then(t):tg&&(e.data instanceof ArrayBuffer||ng(e.data))?t(ig(e.data)):rg(e,!1,e=>{ag||(ag=new TextEncoder),t(ag.encode(e))})}(e,n=>{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}});r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const o=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this._writer.write(i).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&bg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Ig{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Pg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Og(Lg,this.uri(),e)}}},$g=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Bg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ug(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=$g.exec(e||""),i={},a=14;for(;a--;)i[Bg[a]]=o[a]||"";return-1!=n&&-1!=r&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,i.path),i.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}(0,i.query),i}const qg="function"==typeof addEventListener&&"function"==typeof removeEventListener,Vg=[];qg&&addEventListener("offline",()=>{Vg.forEach(e=>e())},!1);class Wg extends gg{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=Ug(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Ug(t.host).host);kg(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let r=0,o=n.length;r<o;r++){let e=n[r].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),qg&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Vg.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Wg.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Wg.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=_g(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,bg(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const o={type:e,data:t,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Wg.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),qg&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Vg.indexOf(this._offlineEventListener);-1!==e&&Vg.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Wg.protocol=4;class Hg extends Wg{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Wg.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Wg.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function o(){n||(n=!0,c(),t.close(),t=null)}const i=e=>{const n=new Error("probe error: "+e);n.transport=t.name,o(),this.emitReserved("upgradeError",n)};function a(){i("transport closed")}function s(){i("socket closed")}function l(e){t&&e.name!==t.name&&o()}const c=()=>{t.removeListener("open",r),t.removeListener("error",i),t.removeListener("close",a),this.off("close",s),this.off("upgrading",l)};t.once("open",r),t.once("error",i),t.once("close",a),this.once("close",s),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let Zg=class extends Hg{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>Fg[e]).filter(e=>!!e)),super(e,n)}};const Jg="function"==typeof ArrayBuffer,Kg=Object.prototype.toString,Gg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Kg.call(Blob),Yg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Kg.call(File);function Qg(e){return Jg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Gg&&e instanceof Blob||Yg&&e instanceof File}function Xg(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Xg(e[t]))return!0;return!1}if(Qg(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Xg(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&Xg(e[n]))return!0;return!1}function eb(e){const t=[],n=e.data,r=e;return r.data=tb(n,t),r.attachments=t.length,{packet:r,buffers:t}}function tb(e,t){if(!e)return e;if(Qg(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=tb(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=tb(e[r],t));return n}return e}function nb(e,t){return e.data=rb(e.data,t),delete e.attachments,e}function rb(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=rb(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=rb(e[n],t));return e}const ob=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ib,ab;(ab=ib||(ib={}))[ab.CONNECT=0]="CONNECT",ab[ab.DISCONNECT=1]="DISCONNECT",ab[ab.EVENT=2]="EVENT",ab[ab.ACK=3]="ACK",ab[ab.CONNECT_ERROR=4]="CONNECT_ERROR",ab[ab.BINARY_EVENT=5]="BINARY_EVENT",ab[ab.BINARY_ACK=6]="BINARY_ACK";class sb extends gg{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof e?{reviver:e}:e)}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===ib.BINARY_EVENT;n||t.type===ib.BINARY_ACK?(t.type=n?ib.EVENT:ib.ACK,this.reconstructor=new lb(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Qg(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===ib[n.type])throw new Error("unknown packet type "+n.type);if(n.type===ib.BINARY_EVENT||n.type===ib.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");const i=Number(o);if(!cb(i)||i<0)throw new Error("Illegal attachments");if(i>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=i}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!sb.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(e,t){switch(e){case ib.CONNECT:return ub(t);case ib.DISCONNECT:return void 0===t;case ib.CONNECT_ERROR:return"string"==typeof t||ub(t);case ib.EVENT:case ib.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ob.indexOf(t[0]));case ib.ACK:case ib.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class lb{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=nb(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const cb=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function ub(e){return"[object Object]"===Object.prototype.toString.call(e)}const db=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:sb,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==ib.EVENT&&e.type!==ib.ACK||!Xg(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===ib.EVENT?ib.BINARY_EVENT:ib.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==ib.BINARY_EVENT&&e.type!==ib.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=eb(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return ib}},Symbol.toStringTag,{value:"Module"}));function pb(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const hb=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class fb extends gg{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[pb(e,"open",this.onopen.bind(this)),pb(e,"packet",this.onpacket.bind(this)),pb(e,"error",this.onerror.bind(this)),pb(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,r,o;if(hb.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:ib.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const a=null===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,s=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!a||(s?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),i=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{const o=(e,t)=>e?r(e):n(t);o.withError=!0,t.push(o),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:ib.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case ib.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ib.EVENT:case ib.BINARY_EVENT:this.onevent(e);break;case ib.ACK:case ib.BINARY_ACK:this.onack(e);break;case ib.DISCONNECT:this.ondisconnect();break;case ib.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:ib.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ib.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function mb(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}mb.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},mb.prototype.reset=function(){this.attempts=0},mb.prototype.setMin=function(e){this.ms=e},mb.prototype.setMax=function(e){this.max=e},mb.prototype.setJitter=function(e){this.jitter=e};class gb extends gg{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,kg(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new mb({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||db;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Zg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=pb(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=pb(t,"error",o);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{r(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(pb(e,"ping",this.onping.bind(this)),pb(e,"data",this.ondata.bind(this)),pb(e,"error",this.onerror.bind(this)),pb(e,"close",this.onclose.bind(this)),pb(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){bg(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new fb(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const bb={};function yb(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=Ug(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const o=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port+t,r.href=r.protocol+"://"+o+(n&&n.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=n.source,o=n.id,i=n.path,a=bb[o]&&i in bb[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new gb(r,t):(bb[o]||(bb[o]=new gb(r,t)),s=bb[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(yb,{Manager:gb,Socket:fb,io:yb,connect:yb});const vb=Im({proposalId:Qf().min(1),tool:Qf().min(1),title:Qf().optional(),summary:Qf().optional(),args:(wb=Qf(),xb=Em(),new Pm({type:"record",keyType:wb,valueType:xb,...Zu(void 0)})).optional(),ownerOnly:/* @__PURE__ */Kh(_m,void 0).optional()});var wb,xb;const kb=Im({proposalId:Qf().min(1),status:Dm(["confirmed","cancelled","expired"]).optional()}),_b="chat_device_id";function Sb(){const e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if("function"==typeof e?.randomUUID)return e.randomUUID();if("function"==typeof e?.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=Array.from(t,e=>e.toString(16).padStart(2,"0"));return n.slice(0,4).join("")+"-"+n.slice(4,6).join("")+"-"+n.slice(6,8).join("")+"-"+n.slice(8,10).join("")+"-"+n.slice(10,16).join("")}return Rt("[deviceId] Web Crypto API unavailable, falling back to Math.random()"),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const Cb=Im({id:Qf().optional(),type:Dm(["text","image","audio","location","system"]).default("text"),content:Qf().optional(),imageUrl:Qf().url().optional(),audioUrl:Qf().optional(),latitude:wm().optional(),longitude:wm().optional(),timestamp:Qf().optional(),sender:Dm(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Gh(Sm).optional(),sources:Nm(Qf()).optional()}),Eb=Im({agentId:Qf().optional(),name:Qf().optional(),label:Qf().optional(),avatarUrl:Qf().optional(),variantKey:Qf().optional()}),zb=/USER_IDENTITY_REQUIRED|AUTH_EXPIRED|AUTH_INVALID|AUTH_REQUIRED|unauthorized/i;class Ab{queue=[];endpoint;apiKey;flushInterval=null;isFlushing=!1;isDisabled=!1;MAX_QUEUE_SIZE=100;FLUSH_INTERVAL_MS=3e4;BATCH_SIZE=10;constructor(e,t){this.endpoint=e,this.apiKey=t,this.startAutoFlush()}startAutoFlush(){this.flushInterval=setInterval(()=>{!this.isDisabled&&this.queue.length>0&&this.flush()},this.FLUSH_INTERVAL_MS)}trackOpen(){this.track("chat_opened")}trackClose(){this.track("chat_closed")}trackMessageSent(e){this.track("message_sent",{type:e})}trackMessageReceived(e,t){this.track("message_received",{type:e,latency:t})}trackError(e,t){this.track("error",{error:e,context:t})}trackConnectionStatus(e){this.track("connection_status",{isConnected:e})}trackFeatureUsed(e){this.track("feature_used",{feature:e})}trackTypingStarted(){this.track("typing_started")}trackAttachmentSent(e,t){this.track("attachment_sent",{type:e,size:t})}track(e,t){this.isDisabled||(this.queue.push({event:e,properties:{...t,userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0,url:"undefined"!=typeof window?window.location.href:void 0},timestamp:Date.now()}),this.queue.length>=this.BATCH_SIZE&&this.flush(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE),Rt("Analytics queue overflow, dropping old events")))}async flush(){if(this.isDisabled||0===this.queue.length||this.isFlushing)return;this.isFlushing=!0;const e=[...this.queue];this.queue=[];try{const t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({events:e}),keepalive:!0});t.ok?$t():(this.isDisabled=!0,this.queue=[],$t(t.status))}catch(t){this.isDisabled=!0,this.queue=[],$t()}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}const Nb=e=>{const t=new Date(e.timestamp).getTime();return Number.isFinite(t)?t:0},Tb=e=>`${e.sender}|${(e=>{const t=e.content;return"string"==typeof t?t:""})(e).trim()}`;let Ib=null,Ob=null;function Mb(e){Ib=e}function Pb(e){Ob=e}const Lb=r(null);function Db({children:e,defaultLocale:t,initialState:n,onStateChange:r,...o}){const[a,l]=i(n?.isOpen??!1),[c,u]=i(0),d=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:open"))},[r]),p=s(()=>{l(!1),r?.(!1),window.dispatchEvent(new CustomEvent("botuyo-chat:close"))},[r]),h=s(()=>{l(e=>{const t=!e;return t&&u(0),r?.(t),t}),window.dispatchEvent(new CustomEvent("botuyo-chat:toggle"))},[r]),f=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))},[r]),m=s(e=>{Ib?(Ib(e),$t(0)):Rt("sendMessage called but no handler registered")},[]),g=s(()=>{Ob?(Ob(),$t()):Rt("clearMessages called but no handler registered")},[]),v={isOpen:a,open:d,close:p,toggle:h,startCall:f,sendMessage:m,clearMessages:g,unreadCount:c},w=s((e,t)=>{"message:received"!==e||a||u(e=>e+1),o.onEvent?.(e,t)},[a,o]);/* @__PURE__ */
|
|
200
|
+
return y(Lb.Provider,{value:v,children:[e,
|
|
201
|
+
/* @__PURE__ */b(qb,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:w})]})}function jb(){const e=o(Lb);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const Rb=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function Fb(e){const{apiKey:t,apiBaseUrl:r,agentId:o,pageContext:l,includeSEOMetadata:c=!1,theme:d,userContext:p,onLogin:h,onNavigate:m,onEvent:b,onStateChange:y,getUserToken:v,onAuthRequired:w,onThemeUpdate:x}=e,[k,_]=i(0),S=f(0),{t:C}=D(),E=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Ab(o,t);const i=()=>r.current?.flush(),a=()=>{"hidden"===document.visibilityState&&r.current?.flush()};return window.addEventListener("beforeunload",i),window.addEventListener("visibilitychange",a),()=>{window.removeEventListener("beforeunload",i),window.removeEventListener("visibilitychange",a),r.current?.destroy()}},[e,t,n]),{trackOpen:s(()=>{r.current?.trackOpen()},[]),trackClose:s(()=>{r.current?.trackClose()},[]),trackMessageSent:s(e=>{r.current?.trackMessageSent(e)},[]),trackMessageReceived:s((e,t)=>{r.current?.trackMessageReceived(e,t)},[]),trackError:s((e,t)=>{r.current?.trackError(e,t)},[]),trackConnectionStatus:s(e=>{r.current?.trackConnectionStatus(e)},[]),trackFeatureUsed:s(e=>{r.current?.trackFeatureUsed(e)},[])}}(r,t,!0),z=function({enabled:e=!0,soundEnabled:t=!0,desktopEnabled:n=!0,botName:r="BotUyo",logoUrl:o,notificationSoundUrl:l}={}){const[c,u]=i("default"),d=f(null),p=o||Ut,h=l||qt;a(()=>{t&&"undefined"!=typeof window&&(d.current=new Audio(h),d.current.volume=.3)},[t,h]),a(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return Rt("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),Bt("Notification permission:",e),"granted"===e}catch(e){return Ft("Error requesting notification permission:",e),!1}},[]),g=s(t=>{if(e&&n&&"granted"===c&&("undefined"==typeof document||!document.hasFocus()))try{const e=`Nuevo mensaje de ${r}`;let n="Mensaje recibido";"text"===t.type&&"content"in t?n=t.content?.slice(0,100)||"Mensaje recibido":"image"===t.type?n="📷 Imagen":"audio"===t.type?n="🎵 Audio":"location"===t.type&&(n="📍 Ubicación");const o=new Notification(e,{body:n,icon:p,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(o){Ft("Error showing notification:",o)}},[e,n,c,r,p]),b=s(()=>{if(e&&t&&("undefined"==typeof document||!document.hasFocus()))try{d.current?.play().catch(e=>{$t(0)})}catch(n){Ft("Error playing sound:",n)}},[e,t]),y=s(e=>{g(e),b()},[g,b]);return{permission:c,requestPermission:m,notify:g,playSound:b,notifyWithSound:y}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:d?.botName||"BotUyo",logoUrl:d?.logoUrl}),A=function(e=10,t=6e4){const n=f([]);return{isAllowed:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),!(n.current.length>=e||(n.current.push(r),0))},[e,t]),getRemainingAttempts:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),Math.max(0,e-n.current.length)},[e,t]),getTimeUntilReset:s(()=>{if(0===n.current.length)return 0;const e=Date.now(),r=n.current[0],o=t-(e-r);return Math.max(0,o)},[t]),reset:s(()=>{n.current=[]},[])}}(10,6e4),{state:N,actions:T}=function(e,t="default"){const[r,o]=g(_u,xu),[l,c]=i(!1),u=n.useMemo(()=>function(e,t="default"){return`botuyo_chat_v1_${e}_${t}`}(e,t),[e,t]),d=n.useMemo(()=>((e,t="default")=>{const n=`${e}_${t}`;return wu.has(n)||wu.set(n,new vu(e,t)),wu.get(n)})(e,t),[e,t]);a(()=>{"undefined"==typeof window||l||(async()=>{try{await d.migrateFromLocalStorage(e,t);const n=await d.getMessages(100),r=await d.getMetadata();if(n.length>0||r){const e={messages:n.map(e=>({...e,timestamp:new Date(e.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};o({type:"RESTORE_SESSION",payload:e})}}catch(n){Rt("Chat: Error rehydrating from IndexedDB",n);try{const e=localStorage.getItem(u);if(e){const t=JSON.parse(e);t.messages&&(t.messages=t.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}))),o({type:"RESTORE_SESSION",payload:t})}}catch(r){Ft("Chat: Fallback rehydration failed",r)}}finally{c(!0)}})()},[l]),a(()=>{if(!l)return;const e=setTimeout(async()=>{try{await d.saveMessages(r.messages),await d.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(e){Ft("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){Ft("Chat: Fallback persistence failed",t)}}},500);return()=>clearTimeout(e)},[r.isOpen,r.messages,r.sessionId,l]);const p=s(e=>{o({type:"ADD_MESSAGE",payload:e})},[]),h=s(()=>o({type:"TOGGLE_WINDOW"}),[]),f=s(()=>o({type:"OPEN_WINDOW"}),[]),m=s(()=>o({type:"CLOSE_WINDOW"}),[]),b=s(e=>o({type:"SET_CONNECTED",payload:e}),[]),y=s(e=>o({type:"SET_TYPING",payload:e}),[]),v=s(e=>o({type:"SET_MESSAGES",payload:e}),[]),w=s(e=>o({type:"SET_ERROR",payload:e}),[]),x=s(e=>o({type:"SET_SESSION_ID",payload:e}),[]),k=s(()=>{localStorage.removeItem(u),o({type:"CLEAR_CHAT"})},[]),_=s(()=>{o({type:"SET_MESSAGES",payload:[]})},[]),S=s((e,t)=>o({type:"ANSWER_QUIZ",payload:{messageId:e,buttonId:t}}),[]),C=s((e,t)=>o({type:"RESOLVE_PROPOSAL",payload:{proposalId:e,status:t}}),[]);return{state:r,isHydrated:l,actions:{toggleWindow:h,openWindow:f,closeWindow:m,setConnected:b,setTyping:y,addMessage:p,setMessages:v,setError:w,setSessionId:x,clearChat:k,clearMessages:_,answerQuiz:S,resolveProposal:C}}}(t,o),I=function(e=!1){const t="undefined"!=typeof window?window.location.pathname:"",n=u(()=>t,[t]),[r,o]=i({});return a(()=>{if(!e)return void o({});const t=setTimeout(()=>{const e=function(){if("undefined"==typeof window)return{};const e={};e.title=document.title,document.querySelectorAll("meta").forEach(t=>{const n=t.getAttribute("name"),r=t.getAttribute("property"),o=t.getAttribute("content");if(o){if(n)switch(n){case"description":e.description=o;break;case"keywords":e.keywords=o.split(",").map(e=>e.trim());break;case"author":e.author=o}if(r){if(r.startsWith("og:")){const t=r.replace("og:","og_");e[t]=o}if(r.startsWith("twitter:")){const t=r.replace("twitter:","twitter_");e[t]=o}}}});try{const t=document.querySelectorAll('script[type="application/ld+json"]');if(t.length>0){const n=[];t.forEach(e=>{try{const t=JSON.parse(e.textContent||"");n.push(t)}catch{}}),n.length>0&&(e.structuredData=n)}}catch{}return e}();o(e)},100);return()=>clearTimeout(t)},[n,e]),e&&Object.keys(r).length>0?r:void 0}(c),O=function(e){const{apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,userContext:l}=e,c=f(e);a(()=>{c.current=e},[e]);const d=f(null),[p,h]=i(!1),[m,g]=i(!1),b=f(function(){try{const e=localStorage.getItem(_b);if(e)return e;const t=Sb();return localStorage.setItem(_b,t),t}catch{return Rt("localStorage not available, using session-only device ID"),Sb()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=Cb.safeParse(e),r=t.success&&t.data.id?t.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=t.success&&t.data.sender?t.data.sender:"bot",i=t.success&&t.data.timestamp?new Date(t.data.timestamp):/* @__PURE__ */new Date,a=t.success?t.data:{type:"text"};switch(a.type){case"image":return{id:r,type:"image",sender:o,timestamp:i,imageUrl:a.imageUrl||a.content||"",altText:"Imagen enviada"};case"audio":{const e=a.audioUrl||"";return{id:r,type:"audio",sender:o,timestamp:i,content:e.startsWith("http://")||e.startsWith("https://")?e:e?`${n}/api/voice/audio/${r}`:a.content||"",text:a.content||void 0}}case"location":return{id:r,type:"location",sender:o,timestamp:i,latitude:Number(a.latitude||0),longitude:Number(a.longitude||0),name:a.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:i,content:String(a.content||"")};default:return{id:r,type:"text",sender:o,timestamp:i,content:String(a.content||"Sin contenido"),emotion:a.emotion,...a.sources?.length?{sources:a.sources}:{}}}},[]),w=s(()=>{if(!t||!n)return;if(d.current?.connected)return;h(!0);const e=e=>{const o=yb(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});o.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),o.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),o.on("connect_error",e=>{h(!1);const n=String(e?.data instanceof Object?e?.data?.code:e?.data??e?.message??"");if(zb.test(n)||zb.test(e?.message??"")){c.current.onAuthRequired?.();const e=c.current.getUserToken;e&&e().then(e=>{d.current&&(d.current.auth={apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata})}).catch(e=>Ft("[useChatSocket] Token refresh failed:",e))}c.current.onError(`Error de conexión: ${e.message}`)}),o.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),o.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){Ft("ChatSocket Error processing bot_message:",t)}}),o.on("chat_history",e=>{if(e.messages&&Array.isArray(e.messages))if(c.current.onHistoryLoaded){const t=e.messages.map(e=>{try{return v(e)}catch(t){return $t(),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){$t()}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),o.on("bot_typing",e=>c.current.onTyping(e));const i=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};o.on("onboarding:command",e=>i(e)),o.on("form:command",e=>i(e)),o.on("request_form_state",()=>{i({type:"botuyo-request-form-state"})}),o.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),o.on("custom_event",e=>{if(i({type:"botuyo-custom-event",...e}),"quiz_question"===e?.eventName&&e?.data){const{question:t,buttons:n}=e.data;if(t&&n?.length){const e={id:`quiz-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"buttons",sender:"bot",timestamp:/* @__PURE__ */new Date,content:t,buttons:n};c.current.onMessage(e)}}if("agent_switched"===e?.eventName&&e?.data){const t=Eb.safeParse(e.data);t.success?c.current.onAgentSwitched?.(t.data):$t()}if("tool_proposal"===e?.eventName&&e?.data){const t=vb.safeParse(e.data);if(t.success){const e=t.data,n={id:`proposal-${e.proposalId}`,type:"tool_proposal",sender:"bot",timestamp:/* @__PURE__ */new Date,proposalId:e.proposalId,toolName:e.tool,title:e.title,summary:e.summary,ownerOnly:e.ownerOnly,status:"pending"};c.current.onMessage(n)}else $t()}if(("tool_proposal_resolved"===e?.eventName||"tool_proposal_expired"===e?.eventName)&&e?.data){const t=kb.safeParse(e.data);if(t.success){const n="tool_proposal_expired"===e.eventName?"expired":t.data.status??"confirmed";c.current.onToolProposalResolved?.(t.data.proposalId,n)}else $t()}});const a=e=>{const{type:t}=e.data||{};"botuyo-onboarding-state"!==t&&"botuyo-form-state"!==t||o.emit("form_state",e.data)};window.addEventListener("message",a),d.current=o,o.__formCleanup=()=>window.removeEventListener("message",a)},o=c.current.getUserToken;o?o().then(t=>e(t)).catch(t=>{Ft("[useChatSocket] getUserToken failed:",t),c.current.onAuthRequired?.(),e(l?.token)}):e(l?.token)},[t,n]),x=s(()=>{d.current&&(d.current.disconnect(),d.current=null,g(!1))},[]),k=f(w);k.current=w,a(()=>(k.current(),()=>{d.current&&(d.current.disconnect(),d.current=null)}),[]);const _=f([]),S=f([]),C=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),E=s(()=>{if(d.current?.connected)for(;_.current.length>0;){const e=_.current.shift();d.current.emit("user_message",e)}},[]);a(()=>{m&&E()},[m,E]),a(()=>{if(!m)return;const e=setInterval(()=>{const e=Date.now();S.current=S.current.filter(t=>e<t.nextRetryAt||(t.attempts>=t.maxAttempts?(c.current.onEvent?.("message_failed",{id:t.id,payload:t.payload}),Ft("Message failed after max retries:",t.id),!1):!d.current?.connected||(d.current.emit("user_message",t.payload,e=>{e?.success&&c.current.onEvent?.("message_sent",{id:t.id})}),t.attempts++,t.nextRetryAt=e+1e3*Math.pow(2,t.attempts),t.attempts<t.maxAttempts)))},500);return()=>clearInterval(e)},[m]);const z=s((e,t="text")=>{const n=C(),r={...y.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:b.current},o={id:n,content:e.trim(),type:t,metadata:r};return d.current?.connected?(d.current.emit("user_message",o,e=>{!1!==e?.success&&e?c.current.onEvent?.("message_sent",{id:n}):(S.current.push({id:n,payload:o,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),c.current.onEvent?.("message_retry_queued",{id:n}))}),n):(_.current.push(o),c.current.onEvent?.("queued_message",{id:n,payload:o}),n)},[C]),A=u(()=>ac(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:A,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x,confirmProposal:s(e=>{d.current?.emit("tool_confirm",{proposalId:e})},[]),rejectProposal:s(e=>{d.current?.emit("tool_reject",{proposalId:e})},[])}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>I?{...l||{},seo:{...I||{}}}:l,[l,I]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=S.current>0?t-S.current:void 0;S.current=t,T.addMessage(e),E.trackMessageReceived(e.type,n),N.isOpen||"bot"!==e.sender||(_(e=>e+1),z.notifyWithSound(e))},[T,N.isOpen,E,z]),onConnected:s((e,t)=>{T.setConnected(!0),T.setSessionId(e),E.trackConnectionStatus(!0),t&&x&&x(t),t&&b&&b("backend_config",t)},[T,b,x,E]),onDisconnected:s(()=>{T.setConnected(!1),E.trackConnectionStatus(!1)},[T,E]),onTyping:s(e=>T.setTyping(e),[T]),onError:s(e=>{T.setError(e),E.trackError(e)},[T,E]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:x,onAgentSwitched:s(e=>{const t=function(e,t){const n=(e||"").trim(),r=(t||"").trim();return n&&r&&!n.toLowerCase().includes(r.toLowerCase())?`${n} · ${r}`:n||r}(e.name,e.label);x&&x(n=>({...n||{},...t?{botName:t}:{},...e.avatarUrl?{logoUrl:e.avatarUrl}:{}})),t&&T.addMessage({id:`agent-switched-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"system",sender:"system",timestamp:/* @__PURE__ */new Date,content:C("agent_switched",{name:t})})},[x,T,C]),onHistoryLoaded:s(e=>{0!==e.length&&T.setMessages(function(e,t){if(!t||0===t.length)return e;const n=t.reduce((e,t)=>Math.max(e,Nb(t)),0),r=new Set(t.map(e=>e.id)),o=new Set(t.map(Tb)),i=e.filter(e=>!r.has(e.id)&&Nb(e)>n&&!o.has(Tb(e)));return[...t,...i]}(N.messages,e))},[N.messages,T]),getUserToken:v,onAuthRequired:w,onToolProposalResolved:s((e,t)=>T.resolveProposal(e,t),[T])}),M=u(()=>function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("buttons"===n.type&&!n.answered)return n}return null}(N.messages),[N.messages]),P=f(M);a(()=>{P.current=M},[M]);const L=s(()=>{$t(0,N.isOpen),N.isOpen?(T.closeWindow(),E.trackClose(),y?.(!1),$t()):(T.openWindow(),_(0),E.trackOpen(),y?.(!0),$t())},[N.isOpen,T,y,E]),j=s(e=>{if(!A.isAllowed()){const e=A.getTimeUntilReset(),t=Math.ceil(e/1e3);return void T.setError(C("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};T.addMessage(t),E.trackMessageSent("text"),O.sendMessage(e,"text"),P.current&&T.answerQuiz(P.current.id)},[T,O,A,E,C]),R=s((e,t,n)=>{T.answerQuiz(e.id,n),O.sendMessage(`Answer: ${t}`,"text"),E.trackMessageSent("text")},[T,O,E]),F=s(e=>{T.resolveProposal(e,"confirmed"),O.confirmProposal(e)},[T,O]),$=s(e=>{T.resolveProposal(e,"cancelled"),O.rejectProposal(e)},[T,O]),B=s(async(e,t)=>{let n;n="audio"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(e)}:"image"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(e)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${e.name}`},T.addMessage(n);const r=await Rb(e);O.sendMessage(r,t)},[T,O]),U=s(e=>{const t={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:e.latitude,longitude:e.longitude,name:"Mi ubicación"};T.addMessage(t),O.sendMessage(JSON.stringify(e),"location")},[T,O]);a(()=>{const e=()=>{N.isOpen||T.openWindow()},t=()=>{N.isOpen&&T.closeWindow()},n=()=>{N.isOpen?T.closeWindow():T.openWindow()},r=e=>{e.detail?.message&&j(e.detail.message)},o=()=>{N.isOpen||T.openWindow()};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),window.addEventListener("botuyo-chat:start-call",o),window.addEventListener("botuyo-chat:send-message",r),()=>{window.removeEventListener("botuyo-chat:open",e),window.removeEventListener("botuyo-chat:close",t),window.removeEventListener("botuyo-chat:toggle",n),window.removeEventListener("botuyo-chat:start-call",o),window.removeEventListener("botuyo-chat:send-message",r)}},[N.isOpen,T,j]),a(()=>(Mb(j),()=>Mb(null)),[j]);const q=s(()=>{T.clearMessages(),Bt("Chat history cleared")},[T]);a(()=>(Pb(q),()=>Pb(null)),[q]);const V=u(()=>{if(N.isTyping)return"thinking";const e=[...N.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[N.isTyping,N.messages]);return{state:N,actions:T,unreadCount:k,currentBotEmotion:V,isConnected:O.isConnected,getSocket:O.getSocket,activeQuiz:M,handleToggle:L,handleSendText:j,handleSendAttachment:B,handleSendLocation:U,handleQuizAnswer:R,handleConfirmProposal:F,handleCancelProposal:$}}function $b({children:e}){const t=f(null),n=f(null),[r,o]=i(!1);return a(()=>{if("undefined"==typeof document)return;let e,r,i=document.getElementById("botuyo-chat-widget-root");if(i&&i.shadowRoot)e=i.shadowRoot,r=e.getElementById("botuyo-chat-widget-root")||e.querySelector("div");else{i=document.createElement("div"),i.id="botuyo-chat-widget-root",document.body.appendChild(i),e=i.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=L.replace(/:root/g,":host"),e.appendChild(t),r=document.createElement("div"),r.id="botuyo-chat-widget-root",e.appendChild(r)}return n.current=i,t.current=r,o(!0),$t(),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function Bb(e){const{apiKey:t,apiBaseUrl:n="https://api.botuyo.com",agentId:r,pageContext:o,includeSEOMetadata:l=!1,theme:c,mediaConfig:d,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,initialOpen:k=!1,hideLauncher:_=!1,voiceFirst:S=!1}=e,C=f(null),E=sc(),z=function(e){const[t,n]=i(!1);return a(()=>{let t=null;const r=()=>{if(!e.current)return;const t=!!e.current.parentElement?.closest(".dark"),r=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),o=document.getElementById("botuyo-chat-widget-root"),i=!!o?.parentElement?.closest(".dark"),a=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),l="dark"===document.documentElement.getAttribute("data-theme"),c="dark"===document.body.getAttribute("data-theme"),u=!!e.current.parentElement?.closest('[data-theme="dark"]'),d=window.matchMedia("(prefers-color-scheme: dark)").matches,p=t||r||i||a||s||l||c||u||d;e.current&&(p?e.current.classList.add("dark"):e.current.classList.remove("dark")),n(p)};r();const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r();o.addEventListener("change",i);const a=new MutationObserver(()=>{r()}),s=document.getElementById("botuyo-chat-widget-root");s&&(a.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(a.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=s.parentElement)),a.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),a.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let l=e.current?.parentElement;for(;l;)a.observe(l,{attributes:!0,attributeFilter:["class","data-theme"]}),l=l.parentElement;const c=setInterval(()=>{const e=document.getElementById("botuyo-chat-widget-root");e&&e.parentElement!==t&&(t&&e.parentElement&&(a.observe(e.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=e.parentElement),r())},100);return()=>{a.disconnect(),o.removeEventListener("change",i),clearInterval(c)}},[e]),t}(C),[A,N]=i(),{mergedTheme:T,mergedStyles:I,getContainerStyle:O}=function(e,t){const n=function(){const[e,t]=i(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return a(()=>{const e=window.matchMedia("(prefers-contrast: high)"),n=window.matchMedia("(prefers-contrast: more)"),r=e=>{t(e.matches)};return e.addEventListener("change",r),n.addEventListener("change",r),()=>{e.removeEventListener("change",r),n.removeEventListener("change",r)}},[]),e}(),r=u(()=>{const r=function(e,t){const n={...Nt,...t?.cssVariables||{},...e?.cssVariables||{}};return{botName:e?.botName||t?.botName||"BotUyo",logoUrl:e?.logoUrl||t?.logoUrl||"",position:e?.position||t?.position||"bottom-right",welcomeMessage:e?.welcomeMessage||t?.welcomeMessage||"¡Hola! ¿En qué puedo ayudarte?",inputPlaceholder:e?.inputPlaceholder||t?.inputPlaceholder||"Escribe un mensaje...",cssVariables:n,isHidden:e?.isHidden??t?.isHidden??!1}}(e,t);return n?{...r,cssVariables:{...r.cssVariables,primary:"0 0% 0%",primaryForeground:"0 0% 100%",background:"0 0% 100%",foreground:"0 0% 0%",card:"0 0% 100%",cardForeground:"0 0% 0%",muted:"0 0% 96%",mutedForeground:"0 0% 0%",border:"0 0% 0%"}}:r},[e,t,n]),o=u(()=>({radius:{...Jc,...e?.bubbleStyles?.radius},bot:{...Kc,...e?.bubbleStyles?.bot},user:{...Gc,...e?.bubbleStyles?.user},launcher:{...e?.bubbleStyles?.launcher},mapCard:{...e?.bubbleStyles?.mapCard}}),[e?.bubbleStyles]);return{mergedTheme:r,mergedStyles:o,getContainerStyle:(e,t,n)=>({"--chat-primary":`hsl(${r.cssVariables.primary})`,zIndex:e?2147483647:9999,position:"fixed",top:t&&e?0:"auto",left:t&&e?0:"bottom-left"===n?"24px":"auto",right:t&&e?0:"bottom-right"!==n&&n?"auto":"24px",bottom:t&&e?0:"24px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,A);a(()=>{T.isHidden&&console.warn('[BotUyo] ⚠️ El agente (o Flow) de IA asociado a esta API Key se encuentra pausado o en estado "boceto" (draft). El widget no se mostrará hasta que lo publiques dentro de la plataforma BotUyo.')},[T.isHidden]);const{state:M,actions:P,unreadCount:L,currentBotEmotion:D,isConnected:j,handleToggle:R,handleSendText:F,handleSendAttachment:$,handleSendLocation:B,getSocket:U,activeQuiz:q,handleQuizAnswer:V,handleConfirmProposal:W,handleCancelProposal:H}=Fb({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,onThemeUpdate:N}),Z=f(!1);a(()=>{k&&A&&!Z.current&&(Z.current=!0,M.isOpen||P.openWindow())},[k,A,M.isOpen,P]);const J=u(()=>{const e={...d||{}},t=A;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,A]),K=s(()=>{P.closeWindow()},[P]),G=s(e=>{e.stopPropagation()},[]),Y=O(M.isOpen,E,c?.position),Q=u(()=>{const e={"--background":"0 0% 100%","--foreground":"240 10% 3.9%","--card":"0 0% 100%","--card-foreground":"240 10% 3.9%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 4.8% 95.9%","--muted-foreground":"240 3.8% 46.1%","--border":"240 5.9% 90%","--destructive":"0 84.2% 60.2%","--radius":"0.5rem","--window-border-radius":"24px","--launcher-border-radius":"50%","--window-height":"700px","--window-bottom":"24px","--spacing-1":"0.25rem","--spacing-2":"0.5rem","--spacing-3":"0.75rem","--spacing-4":"1rem","--spacing-5":"0.75rem","--spacing-6":"1.5rem","--spacing-7":"1.75rem","--spacing-8":"2rem"};if(!T.cssVariables)return e;let t={...T.cssVariables};if(z){const e=A?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Tt,...e,...n}}const n={...e};return t.background&&(n["--background"]=t.background),t.foreground&&(n["--foreground"]=t.foreground),t.card&&(n["--card"]=t.card),t.cardForeground&&(n["--card-foreground"]=t.cardForeground),t.primary&&(n["--primary"]=t.primary),t.primaryForeground&&(n["--primary-foreground"]=t.primaryForeground),t.muted&&(n["--muted"]=t.muted),t.mutedForeground&&(n["--muted-foreground"]=t.mutedForeground),t.border&&(n["--border"]=t.border),t.destructive&&(n["--destructive"]=t.destructive),t.radius&&(n["--radius"]=t.radius),t.windowBorderRadius&&(n["--window-border-radius"]=t.windowBorderRadius),t.launcherBorderRadius&&(n["--launcher-border-radius"]=t.launcherBorderRadius),t.windowHeight&&(n["--window-height"]=t.windowHeight),t.windowBottom&&(n["--window-bottom"]=t.windowBottom),t.spacing1&&(n["--spacing-1"]=t.spacing1),t.spacing2&&(n["--spacing-2"]=t.spacing2),t.spacing3&&(n["--spacing-3"]=t.spacing3),t.spacing4&&(n["--spacing-4"]=t.spacing4),t.spacing5&&(n["--spacing-5"]=t.spacing5),t.spacing6&&(n["--spacing-6"]=t.spacing6),t.spacing7&&(n["--spacing-7"]=t.spacing7),t.spacing8&&(n["--spacing-8"]=t.spacing8),n},[T.cssVariables,z,A,c?.darkCssVariables]),X=c?.voiceNoiseGate??A?.voiceNoiseGate,ee=u(()=>({noiseGate:X}),[X]),[te,ne]=i(!1);return a(()=>{S&&j&&ne(!0)},[S,j]),T.isHidden?null:A?S?/* @__PURE__ */b("div",{ref:C,id:"botuyo-chat-widget-root",className:"botuyo-chat-widget",style:{position:"fixed",inset:0,zIndex:2147483e3,...Q},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,children:/* @__PURE__ */b(Zc,{children:/* @__PURE__ */b(Wc,{isOpen:te,onClose:()=>g?.("voice_first_ended",{}),onCallEnded:e=>g?.("voice_call_ended",{reason:e}),primaryColor:It(T),avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},logoUrl:T.logoUrl,avatar3dUrl:c?.avatar3dUrl||A?.avatar3dUrl,voiceConfig:ee,getSocket:U})})}):/* @__PURE__ */y("div",{ref:C,id:"botuyo-chat-widget-root",className:At("botuyo-chat-widget flex flex-col",!E&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...Y,...Q,pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===c?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===c?.effects?.softShadows?"false":void 0,children:[
|
|
202
|
+
/* @__PURE__ */b("div",{className:At("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",E?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",M.isOpen?"opacity-100 scale-100 h-full w-full translate-y-0 pointer-events-auto":"opacity-0 scale-[0.85] pointer-events-none translate-y-8 h-0 w-0"),style:{pointerEvents:M.isOpen?"auto":"none"},onMouseDown:G,onTouchStart:G,children:/* @__PURE__ */b(Zc,{children:/* @__PURE__ */b(Hc,{isOpen:M.isOpen,isConnected:j,isTyping:M.isTyping,messages:M.messages,onClose:K,onSendMessage:F,onSendAttachment:$,onSendLocation:B,botName:T.botName,logoUrl:T.logoUrl,welcomeMessage:T.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||A?.inputPlaceholder,position:c?.position,bubbleStyles:I,avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},mediaConfig:J,theme:T,avatar3dUrl:c?.avatar3dUrl||A?.avatar3dUrl,voiceConfig:ee,getSocket:U,suggestedQuestions:A?.suggestedQuestions,activeQuiz:q,onQuizAnswer:V,onProposalAction:(e,t)=>"confirm"===t?W(e):H(e)})})}),!_&&/* @__PURE__ */b("div",{className:At(M.isOpen?"hidden":"block",!E&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:G,onTouchStart:G,children:/* @__PURE__ */b(Wt,{isOpen:M.isOpen,onClick:R,unreadCount:L,position:c?.position||"bottom-right",primaryColor:It(T),logoUrl:T.logoUrl,starterPrompt:c?.starterPrompt||A?.starterPrompt,avatars:c?.avatars||A?.avatars||A?.avatarAnimations||{},emotion:D,styles:I,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??A?.avatarScale,showPromptAvatar:c?.showPromptAvatar??A?.showPromptAvatar})})]}):null}function Ub(e){/* @__PURE__ */
|
|
203
|
+
return b(Dt,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(Bb,{...e})})}function qb(e){/* @__PURE__ */
|
|
204
|
+
return b(M,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b($b,{children:/* @__PURE__ */b(Ub,{...e})})})}const Vb=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:qb,ChatWidgetInner:Bb,ChatWidgetWithProviders:Ub},Symbol.toStringTag,{value:"Module"}));function Wb({apiKey:e,apiBaseUrl:t="https://api.botuyo.com",sessionKey:n,locale:r="es",onReady:o}){const i=u(()=>({apiKey:e,apiBaseUrl:t,initialOpen:!0,hideLauncher:!0,theme:{position:"bottom-right",defaultLocale:r,cssVariables:{windowBorderRadius:"0px",windowHeight:"100%",windowBottom:"0px"}},onEvent:e=>{"connected"===e&&o&&o()}}),[e,t,r,o]);/* @__PURE__ */
|
|
205
|
+
return b("div",{style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:/* @__PURE__ */b(M,{defaultLocale:r,children:/* @__PURE__ */b(Ub,{...i})})},n)}function Hb({url:e,autoRotate:t,hasCustomCamera:n}){const r=f(null),o=f(null),i=f(null),s=f(0),l=f(0),c=f(0),{scene:u,camera:d}=_();return a(()=>{const t=new z;return t.register(e=>new C(e)),t.load(e,e=>{const t=e.userData?.vrm;if(t){r.current=t,t.scene.rotation.y=Math.PI;const e=(new E.Box3).setFromObject(t.scene).getSize(new E.Vector3);if(c.current=0,l.current=Math.PI,u.add(t.scene),!n){const t=.75*e.y,n=d.fov*(Math.PI/180),r=.55*e.y*.5/Math.tan(n/2)*1.3;d.position.set(0,t,r),d.lookAt(0,t,0)}t.lookAt&&(t.lookAt.target=d)}else{const t=e.scene;t.updateMatrixWorld(!0);const r=(new E.Box3).setFromObject(t),a=r.getCenter(new E.Vector3),s=r.getSize(new E.Vector3),p=new E.Group;if(t.position.sub(a),p.add(t),o.current=p,c.current=0,l.current=0,u.add(p),!n){const e=d.fov*(Math.PI/180),t=.3*s.y,n=.5*s.y/Math.tan(e/2)*1.2;d.position.set(0,t,n),d.lookAt(0,t,0)}if(e.animations.length>0){const n=new E.AnimationMixer(t);i.current=n,e.animations.forEach(e=>{n.clipAction(e).play()})}}},void 0,e=>{console.error("[Avatar3DPreview] Failed to load model:",e)}),()=>{r.current&&(u.remove(r.current.scene),r.current=null),o.current&&(u.remove(o.current),o.current=null),i.current&&(i.current.stopAllAction(),i.current=null)}},[e,u,d,t]),S((e,n)=>{const a=Math.min(n,.1);s.current+=1.2*a;const u=t?.5*a:0;if(o.current){i.current&&i.current.update(a);const e=o.current,n=.003*Math.sin(s.current);e.position.y=c.current+n,t&&(l.current-=u);const r=.02*Math.sin(.3*s.current);return void(e.rotation.y=l.current+r)}const d=r.current;if(d){const e=.003*Math.sin(s.current);if(d.scene.position.y=c.current+e,t&&(l.current-=u,d.scene.rotation.y=l.current),d.humanoid){const e=d.humanoid.getNormalizedBoneNode("spine");if(e){const t=.008*Math.sin(.4*s.current),n=.005*Math.cos(.25*s.current);e.rotation.z=E.MathUtils.lerp(e.rotation.z,t,2*a),e.rotation.x=E.MathUtils.lerp(e.rotation.x,n,2*a)}}d.update(a)}}),null}function Zb({position:e,target:t}){const{camera:n}=_();return a(()=>{e&&t&&(n.position.set(...e),n.lookAt(...t))},[n,e,t]),null}function Jb({url:e,className:t="",cameraPosition:n,targetPosition:r,autoRotate:o=!0}){return e?/* @__PURE__ */b("div",{className:`relative w-full h-full ${t}`,children:/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"w-full h-full flex items-center justify-center text-gray-400 text-xs",children:"Loading 3D Model..."}),children:/* @__PURE__ */y(k,{style:{width:"100%",height:"100%",background:"transparent"},gl:{alpha:!0,antialias:!0,preserveDrawingBuffer:!1},camera:{fov:30,near:.01,far:10},dpr:[1,2],children:[
|
|
206
|
+
/* @__PURE__ */b(Zb,{position:n,target:r}),
|
|
205
207
|
/* @__PURE__ */b("ambientLight",{intensity:.6}),
|
|
206
208
|
/* @__PURE__ */b("directionalLight",{position:[1,2,3],intensity:.8,color:"#ffffff"}),
|
|
207
209
|
/* @__PURE__ */b("directionalLight",{position:[-1,1,-1],intensity:.3,color:"#b4c6e7"}),
|
|
208
210
|
/* @__PURE__ */b("pointLight",{position:[0,.5,-.5],intensity:.5,distance:3}),
|
|
209
|
-
/* @__PURE__ */b(
|
|
210
|
-
//# sourceMappingURL=standalone-
|
|
211
|
+
/* @__PURE__ */b(Hb,{url:e,autoRotate:o,hasCustomCamera:!(!n||!r)})]})})}):null}const Kb="https://api.botuyo.com";class Gb extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error("[BotUyoChat] Widget error:",e,t)}render(){return this.state.hasError?null:this.props.children}}const Yb={"--background":"240 10% 3.9%","--foreground":"0 0% 98%","--card":"240 10% 3.9%","--card-foreground":"0 0% 98%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 3.7% 15.9%","--muted-foreground":"240 5% 64.9%","--border":"240 3.7% 15.9%"},Qb=p(()=>Promise.resolve().then(()=>Vb).then(e=>({default:e.ChatWidgetWithProviders})));class Xb{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||Kb},this.render(),this.setupDarkModeDetection(),this}render(){if(!this.config)return void console.error("[BotUyoChat] No configuration provided");if(!this.container){this.container=document.createElement("div"),this.container.id="botuyo-chat-widget-root",document.body.appendChild(this.container),this.shadowRoot=this.container.attachShadow({mode:"open"});const e=document.createElement("style");e.textContent=L.replace(/:root/g,":host"),this.shadowRoot.appendChild(e),this.mountPoint=document.createElement("div"),this.mountPoint.id="botuyo-chat-widget-root",this.shadowRoot.appendChild(this.mountPoint)}if(this.config.theme?.cssVariables&&this.mountPoint){const e=this.config.theme.cssVariables;[["--background",e.background],["--foreground",e.foreground],["--card",e.card],["--card-foreground",e.cardForeground],["--primary",e.primary],["--primary-foreground",e.primaryForeground],["--muted",e.muted],["--muted-foreground",e.mutedForeground],["--border",e.border],["--destructive",e.destructive],["--radius",e.radius],["--window-border-radius",e.windowBorderRadius],["--launcher-border-radius",e.launcherBorderRadius],["--window-height",e.windowHeight],["--window-bottom",e.windowBottom],["--spacing-1",e.spacing1],["--spacing-2",e.spacing2],["--spacing-3",e.spacing3],["--spacing-4",e.spacing4],["--spacing-5",e.spacing5],["--spacing-6",e.spacing6],["--spacing-7",e.spacing7],["--spacing-8",e.spacing8]].forEach(([e,t])=>{void 0!==t&&this.mountPoint.style.setProperty(e,t)})}this.mountPoint&&!this.config.theme?.cssVariables&&(!function(){const e=document.documentElement.getAttribute("data-theme");return"dark"===e||"light"!==e&&window.matchMedia("(prefers-color-scheme: dark)").matches}()?Object.keys(Yb).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(Yb).forEach(([e,t])=>{this.mountPoint.style.setProperty(e,t)})),!this.root&&this.mountPoint&&(this.root=e(this.mountPoint));const t={apiKey:this.config.apiKey,apiBaseUrl:this.config.apiBaseUrl||Kb,agentId:this.config.agentId,theme:{botName:"Asistente Virtual",position:"bottom-right",welcomeMessage:"¡Hola! 👋 ¿En qué puedo ayudarte?",inputPlaceholder:"Escribe tu mensaje...",cssVariables:{primary:"160 84% 39%",windowBorderRadius:"24px",launcherBorderRadius:"50%"},...this.config.theme},userContext:this.config.userContext,pageContext:this.config.pageContext,includeSEOMetadata:this.config.includeSEOMetadata??!1,mediaConfig:this.config.mediaConfig,onNavigate:this.config.onNavigate,onLogin:this.config.onLogin,onEvent:this.config.onEvent,onStateChange:this.config.onStateChange},r=n.createElement(h,{fallback:n.createElement("div",{style:{position:"fixed",bottom:"24px",right:"24px",width:"60px",height:"60px",borderRadius:"50%",backgroundColor:"#10b981",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",cursor:"wait"}},n.createElement("div",{style:{width:"24px",height:"24px",border:"3px solid rgba(255, 255, 255, 0.3)",borderTopColor:"#fff",borderRadius:"50%",animation:"spin 1s linear infinite"}}))},n.createElement(Qb,t));this.root.render(n.createElement(Gb,null,n.createElement(M,{defaultLocale:this.config.theme?.defaultLocale,children:r}))),console.log("[BotUyoChat] Widget initialized",t)}update(e){this.config?(this.config={...this.config,...e,theme:{...this.config.theme,...e.theme}},this.render()):console.error("[BotUyoChat] Widget not initialized")}destroy(){this.darkModeObserver&&(this.darkModeObserver.disconnect(),this.darkModeObserver=null),this.darkModeMediaQuery&&(this.darkModeMediaQuery.removeEventListener("change",this.handleDarkModeChange),this.darkModeMediaQuery=null),this.root&&(this.root.unmount(),this.root=null),this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null,this.shadowRoot=null,this.mountPoint=null),this.config=null,console.log("[BotUyoChat] Widget destroyed")}setupDarkModeDetection(){this.config?.theme?.cssVariables||(this.handleDarkModeChange=()=>this.render(),this.darkModeObserver=new MutationObserver(this.handleDarkModeChange),this.darkModeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),this.darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.darkModeMediaQuery.addEventListener("change",this.handleDarkModeChange))}handleDarkModeChange=()=>{};open(){window.dispatchEvent(new CustomEvent("botuyo-chat:open"))}close(){window.dispatchEvent(new CustomEvent("botuyo-chat:close"))}startCall(){window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))}sendMessage(e){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:e}}))}getState(){return null}}const ey=new Xb;window.BotUyoChat=ey;export{Jb as A,Xb as B,qb as C,G as L,Wb as P,ce as X,At as a,Db as b,$ as c,Ub as d,M as e,jb as f,It as g,P as h,ey as i,D as u};
|
|
212
|
+
//# sourceMappingURL=standalone-D5pCeR_m.js.map
|