@botuyo/chat-widget-standalone 1.2.0 → 1.2.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.
@@ -15,7 +15,7 @@ return y("div",{className:Et("flex items-center w-fit transition-all duration-50
15
15
  /* @__PURE__ */b(W,{size:10}),
16
16
  /* @__PURE__ */y("span",{children:[e.length," fuente",e.length>1?"s":""]}),
17
17
  /* @__PURE__ */b("span",{className:"transition-transform duration-200",style:{transform:t?"rotate(180deg)":"rotate(0)"},children:"▾"})]}),t&&/* @__PURE__ */b("div",{className:"flex flex-wrap gap-1 mt-1 animate-in fade-in slide-in-from-top-1 duration-200",children:e.map((e,t)=>/* @__PURE__ */y("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-medium rounded-md",style:{backgroundColor:"hsl(var(--muted) / 0.4)",color:"hsl(var(--muted-foreground))"},children:[
18
- /* @__PURE__ */b(W,{size:9}),e]},`${e}-${t}`))})]}):null}),Ul=p(()=>import("./AudioPlayer-DIlXMvwJ.js").then(e=>({default:e.AudioPlayer}))),Vl=p(()=>import("./Gallery-DN-Mwpjv.js").then(e=>({default:e.Gallery}))),ql=d(function({message:e,primaryColor:t,botAvatar:n,botName:r="BotUyo",avatars:a,isFirst:s=!0,isLast:l=!0,index:c=0,onButtonClick:d}){const{t:p}=D("extracted"),f="user"===e.sender,m="system"===e.type||"system"===e.sender,g=!f&&!m,w=Ot({primaryColor:t}),x=function(){const e=o(Tt);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&&a?.[t.emotion])return a[t.emotion]}return n},[e,a,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"),o=e.includes("maps.google")||e.includes("goo.gl")||e.includes("google.com/maps");let i=!1;try{i=new URL(e,window.location.origin).hostname===window.location.hostname}catch{}const a=i?t=>{t.preventDefault(),window.location.href=e}:void 0,s=i?void 0:"_blank",l=i?void 0:"noopener noreferrer";return o?/* @__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:[
18
+ /* @__PURE__ */b(W,{size:9}),e]},`${e}-${t}`))})]}):null}),Ul=p(()=>import("./AudioPlayer-CQvimMFg.js").then(e=>({default:e.AudioPlayer}))),Vl=p(()=>import("./Gallery-DCdvcEMc.js").then(e=>({default:e.Gallery}))),ql=d(function({message:e,primaryColor:t,botAvatar:n,botName:r="BotUyo",avatars:a,isFirst:s=!0,isLast:l=!0,index:c=0,onButtonClick:d}){const{t:p}=D("extracted"),f="user"===e.sender,m="system"===e.type||"system"===e.sender,g=!f&&!m,w=Ot({primaryColor:t}),x=function(){const e=o(Tt);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&&a?.[t.emotion])return a[t.emotion]}return n},[e,a,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"),o=e.includes("maps.google")||e.includes("goo.gl")||e.includes("google.com/maps");let i=!1;try{i=new URL(e,window.location.origin).hostname===window.location.hostname}catch{}const a=i?t=>{t.preventDefault(),window.location.href=e}:void 0,s=i?void 0:"_blank",l=i?void 0:"noopener noreferrer";return o?/* @__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:[
19
19
  /* @__PURE__ */b("span",{className:"flex-shrink-0 p-2 rounded-full",style:{backgroundColor:`${w}1a`,color:w},children:/* @__PURE__ */b(G,{size:16,strokeWidth:2.5})}),
20
20
  /* @__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")}),
21
21
  /* @__PURE__ */b(q,{size:12,className:"text-muted-foreground/40 group-hover:text-primary"})]})}):r?/* @__PURE__ */y("a",{href:e,target:s,rel:l,onClick:a,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," ",
@@ -87,17 +87,17 @@ return y("div",{className:"relative",children:[(_||C)&&/* @__PURE__ */b("div",{c
87
87
  /* @__PURE__ */b("textarea",{ref:O,rows:1,value:d,onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||e.ctrlKey||e.metaKey?"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),R()):(e.preventDefault(),R())},onChange:e=>{const t=e.target.value.slice(0,Yl);p(t),O.current&&(O.current.style.height="40px",O.current.style.height=`${Math.min(O.current.scrollHeight,120)}px`)},onFocus:()=>m(!1),placeholder:t,"aria-label":c("accessibility.typeMessage"),"aria-describedby":"send-message-hint","aria-invalid":d.length>Yl,disabled:!e,className:"w-full bg-transparent text-sm py-2.5 outline-none resize-none overflow-hidden leading-tight pr-8 scrollbar-none disabled:opacity-50",style:{scrollbarWidth:"none",msOverflowStyle:"none",color:"hsl(var(--foreground))"}}),
88
88
  /* @__PURE__ */b("span",{id:"send-message-hint",className:"sr-only",children:c("accessibility.sendMessageHint")}),d.length>800&&/* @__PURE__ */b("span",{className:Et("absolute right-0 text-[9px] font-bold tabular-nums",d.length>=Yl?"text-destructive":"text-muted-foreground/40"),children:Yl-d.length})]})}),!g&&/* @__PURE__ */b(v,{children:d.trim()||_?/* @__PURE__ */b("button",{onClick:R,disabled:!e||C&&!!_,className:"h-10 w-10 rounded-full flex items-center justify-center transition-all active:scale-90 shadow-md shadow-primary/20 shrink-0 disabled:opacity-30 disabled:grayscale",style:{backgroundColor:L},children:/* @__PURE__ */b(re,{size:18,className:"text-white ml-0.5 fill-current"})}):j.enableAudio&&a?/* @__PURE__ */b("button",{onClick:async()=>{if(e)try{const e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e);T.current=t,M.current=[],t.ondataavailable=e=>M.current.push(e.data),t.onstop=()=>{const e=new File([new Blob(M.current)],"voice.webm",{type:"audio/webm"});a?.(e,"audio")},t.start(),w(!0),P.current=setInterval(()=>k(e=>e+1),1e3)}catch{alert("Micrófono denegado o no disponible")}},disabled:!e,className:"h-10 w-10 rounded-full flex items-center justify-center transition-all active:scale-90 shadow-md shadow-primary/20 shrink-0 disabled:opacity-30 disabled:grayscale",style:{backgroundColor:L},children:/* @__PURE__ */b(X,{size:20,strokeWidth:2.5,className:"text-white"})}):/* @__PURE__ */b("button",{onClick:R,disabled:!e,className:"h-10 w-10 rounded-full flex items-center justify-center transition-all active:scale-90 shadow-md shadow-primary/20 shrink-0 disabled:opacity-30 disabled:grayscale",style:{backgroundColor:L},children:/* @__PURE__ */b(re,{size:18,className:"text-white ml-0.5 fill-current"})})})]})]})}const ec=d(function({questions:e,onSelect:t}){const n=s(e=>{t(e)},[t]);return e&&0!==e.length?/* @__PURE__ */y("div",{className:"px-4 pb-2 pt-1 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[
89
89
  /* @__PURE__ */b("p",{className:"text-[10px] font-bold uppercase tracking-widest mb-2 opacity-50",style:{color:"hsl(var(--muted-foreground))"},children:"Preguntas frecuentes"}),
90
- /* @__PURE__ */b("div",{className:"flex flex-wrap gap-1.5",children:e.map((e,t)=>/* @__PURE__ */b("button",{onClick:()=>n(e),className:"px-3 py-1.5 text-[11px] font-semibold rounded-xl border transition-all duration-200 hover:scale-[1.02] active:scale-95 text-left leading-tight",style:{color:"hsl(var(--foreground))",backgroundColor:"hsl(var(--muted) / 0.3)",borderColor:"hsl(var(--border) / 0.6)"},children:e},`sq-${t}`))})]}):null});function tc(e,t){let n=0,r=null;return function(...o){const i=Date.now(),a=i-n,s=()=>{n=i,e(...o)};a>=t?(r&&(clearTimeout(r),r=null),s()):r||(r=setTimeout(()=>{s(),r=null},t-a))}}function nc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=tc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const rc="24px",oc={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},ic=85,ac=.7,sc=7500,lc=.7,cc=-24,uc=12,dc=4,pc=.003,hc=.15,fc=p(()=>import("./Avatar3D-CoXzuLgX.js")),mc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},gc={idle:"Llamada de voz",connecting:"Conectando...",listening:"Escuchando...",thinking:"Pensando...",speaking:"Hablando..."},bc={tagNames:["p","a","img","strong","em","ul","ol","li","br","span","code","hr"],attributes:{a:["href","target","rel"],img:["src","alt"],span:["className"],code:["className"]},protocols:{a:{href:["http","https","mailto","tel"]},img:{src:["http","https","data"]}}},yc=24e3;class vc extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.warn("[Avatar3D] Three.js failed, falling back to 2D orb:",e.message),this.props.onError()}render(){return this.state.hasError?null:this.props.children}}function wc({avatars:e,logoUrl:t,avatar3dUrl:n,emotion:r,callState:o,audioLevel:a,config:s}){const l=e&&Object.keys(e).length>0,c=!!t,[d,p]=i(!1),f=u(()=>l||c?l?e[r||"default"]||e.default||t||$t:t||$t:null,[l,c,e,r,t]),m="listening"===o||"speaking"===o,g="speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:"listening"===o?s.listeningColor:"#ffffff20",v="speaking"===o?s.speakingScale:"thinking"===o?s.thinkingScale:1,w=s.orbSize;/* @__PURE__ */
90
+ /* @__PURE__ */b("div",{className:"flex flex-wrap gap-1.5",children:e.map((e,t)=>/* @__PURE__ */b("button",{onClick:()=>n(e),className:"px-3 py-1.5 text-[11px] font-semibold rounded-xl border transition-all duration-200 hover:scale-[1.02] active:scale-95 text-left leading-tight",style:{color:"hsl(var(--foreground))",backgroundColor:"hsl(var(--muted) / 0.3)",borderColor:"hsl(var(--border) / 0.6)"},children:e},`sq-${t}`))})]}):null});function tc(e,t){let n=0,r=null;return function(...o){const i=Date.now(),a=i-n,s=()=>{n=i,e(...o)};a>=t?(r&&(clearTimeout(r),r=null),s()):r||(r=setTimeout(()=>{s(),r=null},t-a))}}function nc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=tc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const rc="24px",oc={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},ic=85,ac=.7,sc=200,lc=.5,cc=3e3,uc=1,dc=6,pc=7500,hc=.7,fc=-20,mc=8,gc=6,bc=.002,yc=.12,vc=p(()=>import("./Avatar3D-CoXzuLgX.js")),wc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},xc={idle:"Llamada de voz",connecting:"Conectando...",listening:"Escuchando...",thinking:"Pensando...",speaking:"Hablando..."},kc={tagNames:["p","a","img","strong","em","ul","ol","li","br","span","code","hr"],attributes:{a:["href","target","rel"],img:["src","alt"],span:["className"],code:["className"]},protocols:{a:{href:["http","https","mailto","tel"]},img:{src:["http","https","data"]}}},_c=24e3;class Sc extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.warn("[Avatar3D] Three.js failed, falling back to 2D orb:",e.message),this.props.onError()}render(){return this.state.hasError?null:this.props.children}}function Cc({avatars:e,logoUrl:t,avatar3dUrl:n,emotion:r,callState:o,audioLevel:a,config:s}){const l=e&&Object.keys(e).length>0,c=!!t,[d,p]=i(!1),f=u(()=>l||c?l?e[r||"default"]||e.default||t||$t:t||$t:null,[l,c,e,r,t]),m="listening"===o||"speaking"===o,g="speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:"listening"===o?s.listeningColor:"#ffffff20",v="speaking"===o?s.speakingScale:"thinking"===o?s.thinkingScale:1,w=s.orbSize;/* @__PURE__ */
91
91
  return y("div",n&&!d?{className:"relative flex flex-col items-center gap-4",children:[
92
- /* @__PURE__ */b(vc,{onError:()=>p(!0),children:/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"rounded-full flex items-center justify-center animate-pulse",style:{width:`${s.orbSize}px`,height:`${s.orbSize}px`,background:`radial-gradient(circle at 35% 35%, ${s.speakingColor}40, ${s.speakingColor}10 60%, transparent 80%)`,boxShadow:`0 0 30px ${s.speakingColor}15`}}),children:/* @__PURE__ */b(fc,{modelUrl:n,emotion:r,callState:o,audioLevel:a,primaryColor:s.speakingColor,size:s.orbSize})})}),s.showWaveform&&/* @__PURE__ */b(xc,{isActive:"listening"===o||"speaking"===o,audioLevel:a,color:"speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:s.listeningColor})]}:f?{className:"relative flex flex-col items-center gap-4",children:[
92
+ /* @__PURE__ */b(Sc,{onError:()=>p(!0),children:/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"rounded-full flex items-center justify-center animate-pulse",style:{width:`${s.orbSize}px`,height:`${s.orbSize}px`,background:`radial-gradient(circle at 35% 35%, ${s.speakingColor}40, ${s.speakingColor}10 60%, transparent 80%)`,boxShadow:`0 0 30px ${s.speakingColor}15`}}),children:/* @__PURE__ */b(vc,{modelUrl:n,emotion:r,callState:o,audioLevel:a,primaryColor:s.speakingColor,size:s.orbSize})})}),s.showWaveform&&/* @__PURE__ */b(Ec,{isActive:"listening"===o||"speaking"===o,audioLevel:a,color:"speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:s.listeningColor})]}:f?{className:"relative flex flex-col items-center gap-4",children:[
93
93
  /* @__PURE__ */y("div",{className:Et("relative rounded-full flex items-center justify-center","transition-all duration-500 ease-out"),style:{width:`${w}px`,height:`${w}px`,boxShadow:m?`0 0 0 4px ${g}40, 0 0 30px ${g}30, 0 0 60px ${g}15`:`0 0 0 2px ${g}20`,transform:`scale(${v})`},children:[
94
- /* @__PURE__ */b("img",{src:f,alt:"Bot avatar",className:Et("h-full w-full rounded-full object-cover","transition-all duration-300","thinking"===o&&"opacity-80"),style:{boxShadow:"listening"===o?`0 0 0 2px ${s.listeningColor}80`:"speaking"===o?`0 0 0 2px ${s.speakingColor}80`:"none"}}),s.showEmotionLabel&&r&&/* @__PURE__ */y("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full bg-black/70 backdrop-blur-sm text-[10px] font-bold text-white whitespace-nowrap",children:[s.showEmojis&&(s.emotionEmojis[r]||"💬")," ",r]})]}),s.showWaveform&&/* @__PURE__ */b(xc,{isActive:m,audioLevel:a,color:g})]}:{className:"relative flex flex-col items-center gap-6",children:[
94
+ /* @__PURE__ */b("img",{src:f,alt:"Bot avatar",className:Et("h-full w-full rounded-full object-cover","transition-all duration-300","thinking"===o&&"opacity-80"),style:{boxShadow:"listening"===o?`0 0 0 2px ${s.listeningColor}80`:"speaking"===o?`0 0 0 2px ${s.speakingColor}80`:"none"}}),s.showEmotionLabel&&r&&/* @__PURE__ */y("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full bg-black/70 backdrop-blur-sm text-[10px] font-bold text-white whitespace-nowrap",children:[s.showEmojis&&(s.emotionEmojis[r]||"💬")," ",r]})]}),s.showWaveform&&/* @__PURE__ */b(Ec,{isActive:m,audioLevel:a,color:g})]}:{className:"relative flex flex-col items-center gap-6",children:[
95
95
  /* @__PURE__ */y("div",{className:"relative",style:{width:`${w+48}px`,height:`${w+48}px`},children:[
96
96
  /* @__PURE__ */b("div",{className:"absolute inset-0 rounded-full",style:{border:`1.5px solid ${g}20`,animation:m?"spin 8s linear infinite":"none"}}),
97
97
  /* @__PURE__ */b("div",{className:"absolute rounded-full",style:{inset:"12px",border:`1px solid ${g}15`,animation:m?"spin 12s linear infinite reverse":"none"}}),
98
- /* @__PURE__ */b("div",{className:"absolute rounded-full flex items-center justify-center",style:{inset:"24px",background:`radial-gradient(circle at 35% 35%, ${g}40, ${g}10 60%, transparent 80%)`,boxShadow:m?`0 0 60px ${g}35, 0 0 120px ${g}15, inset 0 0 40px ${g}10`:`0 0 30px ${g}15`,transform:`scale(${v})`,transition:"all 0.5s cubic-bezier(0.4, 0, 0.2, 1)"},children:/* @__PURE__ */b("div",{className:"rounded-full",style:{width:.35*w+"px",height:.35*w+"px",background:`radial-gradient(circle, ${g}90, ${g}40)`,boxShadow:`0 0 20px ${g}60`,animation:m?"pulse 2s ease-in-out infinite":"none"}})}),m&&[0,1,2].map(e=>/* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"4px",height:"4px",backgroundColor:g,opacity:.6,top:"50%",left:"50%",transform:`rotate(${120*e}deg) translateX(${(w+48)/2}px)`,animation:`spin ${6+2*e}s linear infinite`,boxShadow:`0 0 6px ${g}`}},e))]}),s.showWaveform&&/* @__PURE__ */b(xc,{isActive:m,audioLevel:a,color:g})]})}function xc({isActive:e,audioLevel:t,color:n}){/* @__PURE__ */
98
+ /* @__PURE__ */b("div",{className:"absolute rounded-full flex items-center justify-center",style:{inset:"24px",background:`radial-gradient(circle at 35% 35%, ${g}40, ${g}10 60%, transparent 80%)`,boxShadow:m?`0 0 60px ${g}35, 0 0 120px ${g}15, inset 0 0 40px ${g}10`:`0 0 30px ${g}15`,transform:`scale(${v})`,transition:"all 0.5s cubic-bezier(0.4, 0, 0.2, 1)"},children:/* @__PURE__ */b("div",{className:"rounded-full",style:{width:.35*w+"px",height:.35*w+"px",background:`radial-gradient(circle, ${g}90, ${g}40)`,boxShadow:`0 0 20px ${g}60`,animation:m?"pulse 2s ease-in-out infinite":"none"}})}),m&&[0,1,2].map(e=>/* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"4px",height:"4px",backgroundColor:g,opacity:.6,top:"50%",left:"50%",transform:`rotate(${120*e}deg) translateX(${(w+48)/2}px)`,animation:`spin ${6+2*e}s linear infinite`,boxShadow:`0 0 6px ${g}`}},e))]}),s.showWaveform&&/* @__PURE__ */b(Ec,{isActive:m,audioLevel:a,color:g})]})}function Ec({isActive:e,audioLevel:t,color:n}){/* @__PURE__ */
99
99
  return b("div",{className:"flex items-center gap-[3px] h-10",children:Array.from({length:12}).map((r,o)=>{const i=Math.abs(o-5.5)/5.5,a=e?Math.max(4,40*t*(1-.5*i)*(.5+.5*Math.sin(.8*o))):4;/* @__PURE__ */
100
- return b("div",{className:"rounded-full transition-all duration-100",style:{width:"3px",height:`${a}px`,backgroundColor:n,opacity:e?.7-.3*i:.2}},o)})})}function kc({isOpen:e,onClose:t,primaryColor:n="#10b981",getSocket:r,avatars:o,logoUrl:l,avatar3dUrl:c,voiceConfig:d,onAddMessage:p}){const h=u(()=>function(e,t="#10b981"){return{backgroundColor:e?.backgroundColor??"#0a0a0a",listeningColor:e?.listeningColor??"#10b981",speakingColor:e?.speakingColor??t,thinkingColor:e?.thinkingColor??"#a855f7",showEmojis:e?.showEmojis??!0,showEmotionLabel:e?.showEmotionLabel??!0,showWaveform:e?.showWaveform??!0,showBadge:e?.showBadge??!1,badgeText:e?.badgeText??"",emotionEmojis:{...mc,...e?.emotionEmojis},statusLabels:{...gc,...e?.statusLabels},orbSize:e?.orbSize??128,speakingScale:e?.speakingScale??1.08,thinkingScale:e?.thinkingScale??.95,avatar3dUrl:e?.avatar3dUrl}}(d,n),[d,n]),[m,g]=i("idle"),[w,x]=i(0),[k,_]=i(!1),[S,C]=i(0),[E,z]=i(null),[N,O]=i([]),[A,I]=i(!1),[T,M]=i(""),[P,L]=i(!1),D=f(null),j=f(null),F=f(null),R=f(null),$=f(null),B=f(0),U=f(!1),V=f(null),q=f(null),W=f(()=>{}),H=f(null),Z=f(0),K=f(null),G=f([]),Y=f(!1),te=f(0),ne=f([]),oe=s(e=>`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`,[]),ie=s(()=>{if(0===G.current.length)return;K.current&&"closed"!==K.current.state||(K.current=new AudioContext({sampleRate:yc})),"suspended"===K.current.state&&K.current.resume().catch(()=>{});const e=K.current;Y.current=!0,g("speaking");const t=e.currentTime;for(te.current<t&&(te.current=t);G.current.length>0;){const t=G.current.shift(),n=e.createBuffer(1,t.length,yc);n.getChannelData(0).set(t);const r=e.createBufferSource();r.buffer=n,r.connect(e.destination),r.start(te.current),ne.current.push(r),r.onended=()=>{ne.current=ne.current.filter(e=>e!==r),0===ne.current.length&&0===G.current.length&&(Y.current=!1,g(e=>"speaking"===e?"listening":e))},te.current+=t.length/yc}},[]),se=f({}),le=s(()=>{const e=r?.();if(!e||U.current)return;const n=()=>{g("listening")},o=e=>{if(!e?.data)return;const t=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);const r=new Int16Array(n.buffer),o=new Float32Array(r.length);for(let i=0;i<r.length;i++)o[i]=r[i]/32768;return o}(e.data);G.current.push(t),ie(),fe()},i=()=>{ne.current.forEach(e=>{try{e.stop()}catch{}}),ne.current=[],G.current.length=0,te.current=0,Y.current=!1,g("listening")},a=()=>{},s=e=>{console.error("[VoiceCall] Voice error:",e)},l=e=>{e?.emotion&&(z(e.emotion),setTimeout(()=>z(t=>t===e.emotion?null:t),4e3))},c=e=>{e?.text&&(fe(),O(t=>{if(t.length>0&&"user"===t[t.length-1].role){const n=[...t],r=n[n.length-1].text,o=r.length>0&&!r.endsWith(" ")&&!e.text.startsWith(" ");return n[n.length-1]={...n[n.length-1],text:r+(o?" ":"")+e.text},n}return[...t,{role:"user",text:e.text}]}))},u=e=>{e?.text&&O(t=>{const n=t.map(e=>e.role).lastIndexOf("user");if(n>=0){const r=[...t];return r[n]={...r[n],text:e.text},r}return[...t,{role:"user",text:e.text}]})},d=e=>{e?.text&&O(t=>{const n=[...t];for(let o=n.length-1;o>=0;o--)if("user"===n[o].role&&n[o].text===e.original)return n[o]={...n[o],text:e.text},n;const r=n.map(e=>e.role).lastIndexOf("user");return r>=0?(n[r]={...n[r],text:e.text},n):t})},p=e=>{e?.text&&(fe(),O(t=>{if(t.length>0&&"bot"===t[t.length-1].role){const n=[...t],r=n[n.length-1].text,o=r.length>0&&!r.endsWith(" ")&&!e.text.startsWith(" ");return n[n.length-1]={...n[n.length-1],text:r+(o?" ":"")+e.text},n}return[...t,{role:"bot",text:e.text}]}))},h=()=>{g("thinking"),fe()},f=e=>{if(!e?.items?.length)return;if(fe(),"show_content"===e.tool){const t=e.items.map(e=>"link"===e.type?`[${e.label||e.url}](${e.url})`:"image"===e.type?`![${e.label||""}](${e.url})`:e.label||"").filter(Boolean).join("\n");return void(t&&O(e=>[...e,{role:"bot",text:t}]))}const t=e.items.map(t=>{if("search_accommodations"===e.tool){const e=t.options?.[0],n=e?`${e.totalPrice} ${e.currency}`:"",r=(t.features||[]).slice(0,3).join(" • "),o=t.cover?`![${t.title}](${t.cover})`:"",i=e?.link?`[Ver detalles](${e.link})`:"";return`${o}\n**${t.index}. ${t.title}**\n📍 ${t.location} ${t.rating?`⭐ ${t.rating}`:""}\n💰 ${n}\n${r}\n${i}`}if("get_accommodation_details"===e.tool){const e=(t.images||[]).slice(0,4).map(e=>`![](${e})`).join("\n"),n=t.specs?Object.entries(t.specs).map(([e,t])=>`${e}: ${t}`).join(" • "):"",r=(t.rooms||[]).map(e=>`• ${e.name}: ${e.price}`).join("\n"),o=t.rules?`🕐 Check-in: ${t.rules.checkIn||"-"} | Check-out: ${t.rules.checkOut||"-"} | Mascotas: ${t.rules.pets||"-"}`:"",i=t.seeMoreLink?`[Ver más detalles](${t.seeMoreLink})`:"";return`${e}\n**${t.title||t.name}**\n${t.description||""}\n${n}\n${r}\n${o}\n${i}`}if("card"===t.type&&t.content)return t.content;if("link"===t.type&&t.url)return`🔗 [${t.label||t.url}](${t.url})`;if("image"===t.type&&t.url)return`![${t.label||""}](${t.url})`;if(t.systemInstruction&&"string"==typeof t.systemInstruction)return t.systemInstruction;const n=t.signupUrl||t.url||t.link||t.redirectUrl||t.actionPayload?.signupUrl||t.actionPayload?.url;return n?`🔗 [${t.label||t.title||e.tool.replace(/_/g," ")}](${n})`:"error"===t.status?t.error||"Error al ejecutar la acción":""}).filter(Boolean).join("\n\n---\n\n");t&&O(e=>[...e,{role:"bot",text:t}])};se.current={voiceReady:n,voiceAudioChunk:o,voiceInterrupted:i,voiceTurnComplete:a,voiceError:s,voiceEmotion:l,voiceUserTranscript:c,voiceUserTranscriptFinal:u,voiceUserTranscriptCorrected:d,voiceModelTranscript:p,voiceModelThinking:h,voiceToolVisual:f},e.on("voice_ready",n),e.on("voice_audio_chunk",o),e.on("voice_interrupted",i),e.on("voice_turn_complete",a),e.on("voice_error",s),e.on("voice_emotion",l),e.on("voice_user_transcript",c),e.on("voice_user_transcript_final",u),e.on("voice_user_transcript_corrected",d),e.on("voice_model_transcript",p),e.on("voice_model_thinking",h),e.on("voice_tool_visual",f),e.on("voice_timeout",()=>{W.current()});const m=e=>{O(e=>[...e,{role:"bot",text:"📞 Llamada finalizada."}]),setTimeout(()=>{t()},2500)};e.on("voice_call_ended",m),se.current.voiceCallEnded=m,U.current=!0},[r,ie]),ce=s(()=>{const e=r?.();if(!e||!U.current)return;const t=se.current;t.voiceReady&&e.off("voice_ready",t.voiceReady),t.voiceAudioChunk&&e.off("voice_audio_chunk",t.voiceAudioChunk),t.voiceInterrupted&&e.off("voice_interrupted",t.voiceInterrupted),t.voiceTurnComplete&&e.off("voice_turn_complete",t.voiceTurnComplete),t.voiceError&&e.off("voice_error",t.voiceError),t.voiceEmotion&&e.off("voice_emotion",t.voiceEmotion),t.voiceUserTranscript&&e.off("voice_user_transcript",t.voiceUserTranscript),t.voiceUserTranscriptFinal&&e.off("voice_user_transcript_final",t.voiceUserTranscriptFinal),t.voiceUserTranscriptCorrected&&e.off("voice_user_transcript_corrected",t.voiceUserTranscriptCorrected),t.voiceModelTranscript&&e.off("voice_model_transcript",t.voiceModelTranscript),t.voiceModelThinking&&e.off("voice_model_thinking",t.voiceModelThinking),t.voiceToolVisual&&e.off("voice_tool_visual",t.voiceToolVisual),t.voiceCallEnded&&e.off("voice_call_ended",t.voiceCallEnded),e.off("voice_timeout"),se.current={},U.current=!1},[r]),ue=s(async()=>{const e=r?.();if(!e)return;const t=await navigator.mediaDevices.getUserMedia({audio:oc});F.current=t;const n=new AudioContext({sampleRate:16e3});R.current=n,"suspended"===n.state&&await n.resume();const o=n.createMediaStreamSource(t),i=function(e,t){const n=e.createBiquadFilter();n.type="highpass",n.frequency.value=ic,n.Q.value=ac;const r=e.createBiquadFilter();r.type="lowpass",r.frequency.value=sc,r.Q.value=lc;const o=e.createDynamicsCompressor();return o.threshold.value=cc,o.knee.value=uc,o.ratio.value=dc,o.attack.value=pc,o.release.value=hc,t.connect(n),n.connect(r),r.connect(o),o}(n,o),a=n.createAnalyser();if(a.fftSize=256,i.connect(a),j.current=a,!V.current){const e=new Blob(["\nclass VoicePCMProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(1600); // 100ms at 16kHz\n this.bufferIndex = 0;\n }\n process(inputs) {\n const input = inputs[0]?.[0];\n if (!input) return true;\n for (let i = 0; i < input.length; i++) {\n this.buffer[this.bufferIndex++] = input[i];\n if (this.bufferIndex >= 1600) {\n // Convert Float32 → Int16 PCM\n const int16 = new Int16Array(1600);\n for (let j = 0; j < 1600; j++) {\n const s = Math.max(-1, Math.min(1, this.buffer[j]));\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n\n // Send ALL chunks — Gemini server-side VAD handles activity detection\n this.port.postMessage(int16.buffer, [int16.buffer]);\n\n this.buffer = new Float32Array(1600);\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('voice-pcm-processor', VoicePCMProcessor);\n"],{type:"application/javascript"});V.current=URL.createObjectURL(e)}await n.audioWorklet.addModule(V.current);const s=new AudioWorkletNode(n,"voice-pcm-processor");$.current=s,s.port.onmessage=t=>{if(e.connected&&!k){const n=function(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++)n+=String.fromCharCode(t[r]);return btoa(n)}(t.data);e.emit("voice_audio_chunk",{data:n})}},i.connect(s);const l=()=>{if(!j.current)return;const e=new Uint8Array(j.current.frequencyBinCount);j.current.getByteFrequencyData(e);const t=e.reduce((e,t)=>e+t,0)/e.length;C(t/255),B.current=requestAnimationFrame(l)};l()},[r,k]),de=s(()=>{cancelAnimationFrame(B.current),$.current?.disconnect(),$.current=null,F.current?.getTracks().forEach(e=>e.stop()),F.current=null,R.current?.close(),R.current=null,j.current=null,C(0)},[]),pe=s(async()=>{const e=r?.();if(e?.connected){g("connecting"),x(0),O([]),z(null),G.current=[],le(),K.current&&"closed"!==K.current.state||(K.current=new AudioContext({sampleRate:yc})),K.current.resume().catch(()=>{});try{await ue()}catch(t){return console.error("[VoiceCall] Mic error:",t),void g("idle")}e.emit("voice_start",{language:"es-AR",voice:"Kore"}),D.current=setInterval(()=>{x(e=>e+1)},1e3),me()}else console.error("[VoiceCall] Socket not connected")},[r,le,ue]),he=s(()=>{de(),ne.current.forEach(e=>{try{e.stop()}catch{}}),ne.current=[],G.current=[],te.current=0,Y.current=!1,K.current?.close(),K.current=null,D.current&&(clearInterval(D.current),D.current=null),H.current&&(clearInterval(H.current),H.current=null);const e=r?.();if(e?.connected&&e.emit("voice_stop"),p&&N.length>0){const e=Date.now()-1e3*N.length;N.forEach((t,n)=>{p({sender:"user"===t.role?"user":"bot",content:t.text,timestamp:new Date(e+1e3*n)})})}ce(),g("idle"),C(0),x(0),_(!1),O([]),L(!1),t()},[r,de,ce,t,p,N]);a(()=>{W.current=he},[he]);const fe=s(()=>{Z.current=0,L(!1)},[]),me=s(()=>{Z.current=0,H.current&&clearInterval(H.current),H.current=setInterval(()=>{Z.current+=1;const e=Z.current;e>=90&&e<120&&L(!0),e>=120&&W.current()},1e3)},[]),ge=s(()=>{_(e=>!e)},[]),be=s(()=>{const e=T.trim();if(!e)return;const t=r?.();t?.connected&&(t.emit("voice_text_input",{text:e}),M(""),I(!1))},[T,r]);if(a(()=>{e&&"idle"===m&&pe()},[e]),a(()=>{q.current?.scrollIntoView({behavior:"smooth"})},[N]),a(()=>()=>{de(),D.current&&clearInterval(D.current),ce()},[]),!e)return null;const ye="speaking"===m?h.speakingColor:"thinking"===m?h.thinkingColor:"listening"===m?h.listeningColor:n;/* @__PURE__ */
100
+ return b("div",{className:"rounded-full transition-all duration-100",style:{width:"3px",height:`${a}px`,backgroundColor:n,opacity:e?.7-.3*i:.2}},o)})})}function zc({isOpen:e,onClose:t,primaryColor:n="#10b981",getSocket:r,avatars:o,logoUrl:l,avatar3dUrl:c,voiceConfig:d,onAddMessage:p}){const h=u(()=>function(e,t="#10b981"){return{backgroundColor:e?.backgroundColor??"#0a0a0a",listeningColor:e?.listeningColor??"#10b981",speakingColor:e?.speakingColor??t,thinkingColor:e?.thinkingColor??"#a855f7",showEmojis:e?.showEmojis??!0,showEmotionLabel:e?.showEmotionLabel??!0,showWaveform:e?.showWaveform??!0,showBadge:e?.showBadge??!1,badgeText:e?.badgeText??"",emotionEmojis:{...wc,...e?.emotionEmojis},statusLabels:{...xc,...e?.statusLabels},orbSize:e?.orbSize??128,speakingScale:e?.speakingScale??1.08,thinkingScale:e?.thinkingScale??.95,avatar3dUrl:e?.avatar3dUrl}}(d,n),[d,n]),[m,g]=i("idle"),[w,x]=i(0),[k,_]=i(!1),[S,C]=i(0),[E,z]=i(null),[N,O]=i([]),[A,I]=i(!1),[T,M]=i(""),[P,L]=i(!1),D=f(null),j=f(null),F=f(null),R=f(null),$=f(null),B=f(0),U=f(!1),V=f(null),q=f(null),W=f(()=>{}),H=f(null),Z=f(0),K=f(null),G=f([]),Y=f(!1),te=f(0),ne=f([]),oe=s(e=>`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`,[]),ie=s(()=>{if(0===G.current.length)return;K.current&&"closed"!==K.current.state||(K.current=new AudioContext({sampleRate:_c})),"suspended"===K.current.state&&K.current.resume().catch(()=>{});const e=K.current;Y.current=!0,g("speaking");const t=e.currentTime;for(te.current<t&&(te.current=t);G.current.length>0;){const t=G.current.shift(),n=e.createBuffer(1,t.length,_c);n.getChannelData(0).set(t);const r=e.createBufferSource();r.buffer=n,r.connect(e.destination),r.start(te.current),ne.current.push(r),r.onended=()=>{ne.current=ne.current.filter(e=>e!==r),0===ne.current.length&&0===G.current.length&&(Y.current=!1,g(e=>"speaking"===e?"listening":e))},te.current+=t.length/_c}},[]),se=f({}),le=s(()=>{const e=r?.();if(!e||U.current)return;const n=()=>{g("listening")},o=e=>{if(!e?.data)return;const t=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);const r=new Int16Array(n.buffer),o=new Float32Array(r.length);for(let i=0;i<r.length;i++)o[i]=r[i]/32768;return o}(e.data);G.current.push(t),ie(),fe()},i=()=>{ne.current.forEach(e=>{try{e.stop()}catch{}}),ne.current=[],G.current.length=0,te.current=0,Y.current=!1,g("listening")},a=()=>{},s=e=>{console.error("[VoiceCall] Voice error:",e)},l=e=>{e?.emotion&&(z(e.emotion),setTimeout(()=>z(t=>t===e.emotion?null:t),4e3))},c=e=>{e?.text&&(fe(),O(t=>{if(t.length>0&&"user"===t[t.length-1].role){const n=[...t],r=n[n.length-1].text,o=r.length>0&&!r.endsWith(" ")&&!e.text.startsWith(" ");return n[n.length-1]={...n[n.length-1],text:r+(o?" ":"")+e.text},n}return[...t,{role:"user",text:e.text}]}))},u=e=>{e?.text&&O(t=>{const n=t.map(e=>e.role).lastIndexOf("user");if(n>=0){const r=[...t];return r[n]={...r[n],text:e.text},r}return[...t,{role:"user",text:e.text}]})},d=e=>{e?.text&&O(t=>{const n=[...t];for(let o=n.length-1;o>=0;o--)if("user"===n[o].role&&n[o].text===e.original)return n[o]={...n[o],text:e.text},n;const r=n.map(e=>e.role).lastIndexOf("user");return r>=0?(n[r]={...n[r],text:e.text},n):t})},p=e=>{e?.text&&(fe(),O(t=>{if(t.length>0&&"bot"===t[t.length-1].role){const n=[...t],r=n[n.length-1].text,o=r.length>0&&!r.endsWith(" ")&&!e.text.startsWith(" ");return n[n.length-1]={...n[n.length-1],text:r+(o?" ":"")+e.text},n}return[...t,{role:"bot",text:e.text}]}))},h=()=>{g("thinking"),fe()},f=e=>{if(!e?.items?.length)return;if(fe(),"show_content"===e.tool){const t=e.items.map(e=>"link"===e.type?`[${e.label||e.url}](${e.url})`:"image"===e.type?`![${e.label||""}](${e.url})`:e.label||"").filter(Boolean).join("\n");return void(t&&O(e=>[...e,{role:"bot",text:t}]))}const t=e.items.map(t=>{if("search_accommodations"===e.tool){const e=t.options?.[0],n=e?`${e.totalPrice} ${e.currency}`:"",r=(t.features||[]).slice(0,3).join(" • "),o=t.cover?`![${t.title}](${t.cover})`:"",i=e?.link?`[Ver detalles](${e.link})`:"";return`${o}\n**${t.index}. ${t.title}**\n📍 ${t.location} ${t.rating?`⭐ ${t.rating}`:""}\n💰 ${n}\n${r}\n${i}`}if("get_accommodation_details"===e.tool){const e=(t.images||[]).slice(0,4).map(e=>`![](${e})`).join("\n"),n=t.specs?Object.entries(t.specs).map(([e,t])=>`${e}: ${t}`).join(" • "):"",r=(t.rooms||[]).map(e=>`• ${e.name}: ${e.price}`).join("\n"),o=t.rules?`🕐 Check-in: ${t.rules.checkIn||"-"} | Check-out: ${t.rules.checkOut||"-"} | Mascotas: ${t.rules.pets||"-"}`:"",i=t.seeMoreLink?`[Ver más detalles](${t.seeMoreLink})`:"";return`${e}\n**${t.title||t.name}**\n${t.description||""}\n${n}\n${r}\n${o}\n${i}`}if("card"===t.type&&t.content)return t.content;if("link"===t.type&&t.url)return`🔗 [${t.label||t.url}](${t.url})`;if("image"===t.type&&t.url)return`![${t.label||""}](${t.url})`;if(t.systemInstruction&&"string"==typeof t.systemInstruction)return t.systemInstruction;const n=t.signupUrl||t.url||t.link||t.redirectUrl||t.actionPayload?.signupUrl||t.actionPayload?.url;return n?`🔗 [${t.label||t.title||e.tool.replace(/_/g," ")}](${n})`:"error"===t.status?t.error||"Error al ejecutar la acción":""}).filter(Boolean).join("\n\n---\n\n");t&&O(e=>[...e,{role:"bot",text:t}])};se.current={voiceReady:n,voiceAudioChunk:o,voiceInterrupted:i,voiceTurnComplete:a,voiceError:s,voiceEmotion:l,voiceUserTranscript:c,voiceUserTranscriptFinal:u,voiceUserTranscriptCorrected:d,voiceModelTranscript:p,voiceModelThinking:h,voiceToolVisual:f},e.on("voice_ready",n),e.on("voice_audio_chunk",o),e.on("voice_interrupted",i),e.on("voice_turn_complete",a),e.on("voice_error",s),e.on("voice_emotion",l),e.on("voice_user_transcript",c),e.on("voice_user_transcript_final",u),e.on("voice_user_transcript_corrected",d),e.on("voice_model_transcript",p),e.on("voice_model_thinking",h),e.on("voice_tool_visual",f),e.on("voice_timeout",()=>{W.current()});const m=e=>{O(e=>[...e,{role:"bot",text:"📞 Llamada finalizada."}]),setTimeout(()=>{t()},2500)};e.on("voice_call_ended",m),se.current.voiceCallEnded=m,U.current=!0},[r,ie]),ce=s(()=>{const e=r?.();if(!e||!U.current)return;const t=se.current;t.voiceReady&&e.off("voice_ready",t.voiceReady),t.voiceAudioChunk&&e.off("voice_audio_chunk",t.voiceAudioChunk),t.voiceInterrupted&&e.off("voice_interrupted",t.voiceInterrupted),t.voiceTurnComplete&&e.off("voice_turn_complete",t.voiceTurnComplete),t.voiceError&&e.off("voice_error",t.voiceError),t.voiceEmotion&&e.off("voice_emotion",t.voiceEmotion),t.voiceUserTranscript&&e.off("voice_user_transcript",t.voiceUserTranscript),t.voiceUserTranscriptFinal&&e.off("voice_user_transcript_final",t.voiceUserTranscriptFinal),t.voiceUserTranscriptCorrected&&e.off("voice_user_transcript_corrected",t.voiceUserTranscriptCorrected),t.voiceModelTranscript&&e.off("voice_model_transcript",t.voiceModelTranscript),t.voiceModelThinking&&e.off("voice_model_thinking",t.voiceModelThinking),t.voiceToolVisual&&e.off("voice_tool_visual",t.voiceToolVisual),t.voiceCallEnded&&e.off("voice_call_ended",t.voiceCallEnded),e.off("voice_timeout"),se.current={},U.current=!1},[r]),ue=s(async()=>{const e=r?.();if(!e)return;const t=await navigator.mediaDevices.getUserMedia({audio:oc});F.current=t;const n=new AudioContext({sampleRate:16e3});R.current=n,"suspended"===n.state&&await n.resume();const o=n.createMediaStreamSource(t),i=function(e,t){const n=e.createBiquadFilter();n.type="highpass",n.frequency.value=ic,n.Q.value=ac;const r=e.createBiquadFilter();r.type="highpass",r.frequency.value=sc,r.Q.value=lc;const o=e.createBiquadFilter();o.type="peaking",o.frequency.value=cc,o.Q.value=uc,o.gain.value=dc;const i=e.createBiquadFilter();i.type="lowpass",i.frequency.value=pc,i.Q.value=hc;const a=e.createDynamicsCompressor();return a.threshold.value=fc,a.knee.value=mc,a.ratio.value=gc,a.attack.value=bc,a.release.value=yc,t.connect(n),n.connect(r),r.connect(o),o.connect(i),i.connect(a),a}(n,o),a=n.createAnalyser();if(a.fftSize=256,i.connect(a),j.current=a,!V.current){const e=new Blob(["\nclass VoicePCMProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(1600); // 100ms at 16kHz\n this.bufferIndex = 0;\n }\n process(inputs) {\n const input = inputs[0]?.[0];\n if (!input) return true;\n for (let i = 0; i < input.length; i++) {\n this.buffer[this.bufferIndex++] = input[i];\n if (this.bufferIndex >= 1600) {\n // Convert Float32 → Int16 PCM\n const int16 = new Int16Array(1600);\n for (let j = 0; j < 1600; j++) {\n const s = Math.max(-1, Math.min(1, this.buffer[j]));\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n\n // Send ALL chunks — Gemini server-side VAD handles activity detection\n this.port.postMessage(int16.buffer, [int16.buffer]);\n\n this.buffer = new Float32Array(1600);\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('voice-pcm-processor', VoicePCMProcessor);\n"],{type:"application/javascript"});V.current=URL.createObjectURL(e)}await n.audioWorklet.addModule(V.current);const s=new AudioWorkletNode(n,"voice-pcm-processor");$.current=s,s.port.onmessage=t=>{if(e.connected&&!k){const n=function(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++)n+=String.fromCharCode(t[r]);return btoa(n)}(t.data);e.emit("voice_audio_chunk",{data:n})}},i.connect(s);const l=()=>{if(!j.current)return;const e=new Uint8Array(j.current.frequencyBinCount);j.current.getByteFrequencyData(e);const t=e.reduce((e,t)=>e+t,0)/e.length;C(t/255),B.current=requestAnimationFrame(l)};l()},[r,k]),de=s(()=>{cancelAnimationFrame(B.current),$.current?.disconnect(),$.current=null,F.current?.getTracks().forEach(e=>e.stop()),F.current=null,R.current?.close(),R.current=null,j.current=null,C(0)},[]),pe=s(async()=>{const e=r?.();if(e?.connected){g("connecting"),x(0),O([]),z(null),G.current=[],le(),K.current&&"closed"!==K.current.state||(K.current=new AudioContext({sampleRate:_c})),K.current.resume().catch(()=>{});try{await ue()}catch(t){return console.error("[VoiceCall] Mic error:",t),void g("idle")}e.emit("voice_start",{language:"es-AR",voice:"Kore"}),D.current=setInterval(()=>{x(e=>e+1)},1e3),me()}else console.error("[VoiceCall] Socket not connected")},[r,le,ue]),he=s(()=>{de(),ne.current.forEach(e=>{try{e.stop()}catch{}}),ne.current=[],G.current=[],te.current=0,Y.current=!1,K.current?.close(),K.current=null,D.current&&(clearInterval(D.current),D.current=null),H.current&&(clearInterval(H.current),H.current=null);const e=r?.();if(e?.connected&&e.emit("voice_stop"),p&&N.length>0){const e=Date.now()-1e3*N.length;N.forEach((t,n)=>{p({sender:"user"===t.role?"user":"bot",content:t.text,timestamp:new Date(e+1e3*n)})})}ce(),g("idle"),C(0),x(0),_(!1),O([]),L(!1),t()},[r,de,ce,t,p,N]);a(()=>{W.current=he},[he]);const fe=s(()=>{Z.current=0,L(!1)},[]),me=s(()=>{Z.current=0,H.current&&clearInterval(H.current),H.current=setInterval(()=>{Z.current+=1;const e=Z.current;e>=90&&e<120&&L(!0),e>=120&&W.current()},1e3)},[]),ge=s(()=>{_(e=>!e)},[]),be=s(()=>{const e=T.trim();if(!e)return;const t=r?.();t?.connected&&(t.emit("voice_text_input",{text:e}),M(""),I(!1))},[T,r]);if(a(()=>{e&&"idle"===m&&pe()},[e]),a(()=>{q.current?.scrollIntoView({behavior:"smooth"})},[N]),a(()=>()=>{de(),D.current&&clearInterval(D.current),ce()},[]),!e)return null;const ye="speaking"===m?h.speakingColor:"thinking"===m?h.thinkingColor:"listening"===m?h.listeningColor:n;/* @__PURE__ */
101
101
  return y("div",{className:Et("absolute inset-0 z-50 flex flex-col overflow-hidden","animate-in fade-in duration-300"),style:{backgroundColor:"#0a0a0f",borderRadius:"inherit"},children:[
102
102
  /* @__PURE__ */y("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"hidden"},children:[
103
103
  /* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"300px",height:"300px",top:"-80px",right:"-60px",background:`radial-gradient(circle, ${ye}18 0%, transparent 70%)`,transition:"background 1.5s ease",filter:"blur(40px)"}}),
@@ -110,8 +110,8 @@ return y("div",{className:Et("absolute inset-0 z-50 flex flex-col overflow-hidde
110
110
  /* @__PURE__ */y("div",{className:"flex items-center gap-3",children:[h.showEmotionLabel&&E&&/* @__PURE__ */y("span",{style:{fontSize:"11px",padding:"2px 10px",borderRadius:"20px",background:`${ye}15`,border:`1px solid ${ye}25`,color:ye,fontWeight:600},children:[h.showEmojis&&(h.emotionEmojis[E]||"💬")," ",E]}),
111
111
  /* @__PURE__ */b("span",{style:{fontSize:"13px",fontFamily:"ui-monospace, monospace",color:"rgba(255,255,255,0.4)",fontVariantNumeric:"tabular-nums"},children:oe(w)}),P&&(()=>{const e=120-Z.current,t=e<=15;/* @__PURE__ */
112
112
  return y("span",{style:{fontSize:"10px",padding:"2px 8px",borderRadius:"12px",backgroundColor:t?"rgba(239,68,68,0.2)":"rgba(245,158,11,0.15)",color:t?"#ef4444":"#f59e0b",fontWeight:700,fontVariantNumeric:"tabular-nums",animation:t?"pulse 1s ease-in-out infinite":"none"},children:["⏸ Inactivo — ",e>0?e:0,"s"]})})()]})]}),h.showBadge&&h.badgeText&&/* @__PURE__ */b("div",{style:{display:"flex",justifyContent:"center",padding:"8px 0"},children:/* @__PURE__ */b("span",{style:{padding:"4px 14px",borderRadius:"20px",fontSize:"11px",fontWeight:700,background:`linear-gradient(135deg, ${n}, ${h.thinkingColor})`,color:"white"},children:h.badgeText})}),
113
- /* @__PURE__ */b("div",{className:"relative shrink-0 flex justify-center",style:{padding:"16px 20px 8px"},children:/* @__PURE__ */b(wc,{avatars:o,logoUrl:l,avatar3dUrl:c||h.avatar3dUrl,emotion:E,callState:m,audioLevel:S,config:h})}),
114
- /* @__PURE__ */b("div",{className:"relative flex-1 overflow-y-auto px-5 pb-4",style:{scrollbarWidth:"none"},children:/* @__PURE__ */b("div",{className:"flex flex-col gap-4 w-full",children:N.length>0&&/* @__PURE__ */y("div",{style:{display:"flex",flexDirection:"column",gap:"8px",width:"100%"},children:[N.map((e,t)=>/* @__PURE__ */b("div",{style:{maxWidth:"85%",padding:"10px 14px",borderRadius:"user"===e.role?"16px 16px 4px 16px":"16px 16px 16px 4px",fontSize:"13.5px",lineHeight:1.5,color:"white",marginLeft:"user"===e.role?"auto":"0",marginRight:"user"===e.role?"0":"auto",backgroundColor:"user"===e.role?"rgba(255,255,255,0.08)":`${n}25`,backdropFilter:"blur(8px)",border:"user"===e.role?"1px solid rgba(255,255,255,0.08)":`1px solid ${n}20`},children:/* @__PURE__ */b("div",{className:"prose prose-sm prose-invert max-w-none break-words leading-relaxed",style:{fontSize:"13.5px"},children:/* @__PURE__ */b(ja,{remarkPlugins:[Al],rehypePlugins:[[$l,bc]],components:{p:({children:e})=>/* @__PURE__ */b("p",{style:{margin:"0 0 4px"},children:e}),a:({href:e,children:t})=>{if(!e)return null;const r=String(t).toLowerCase(),o=r.includes("reservar")||r.includes("ver")||r.includes("pagar");return e.includes("maps.google")||e.includes("goo.gl")||e.includes("google.com/maps")?/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",margin:"6px 0",borderRadius:"10px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",color:n,textDecoration:"none",fontSize:"12px",fontWeight:700},children:"📍 Ver ubicación"}):o?/* @__PURE__ */y("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"6px",padding:"8px 16px",margin:"6px 0",borderRadius:"10px",background:n,color:"white",textDecoration:"none",fontSize:"11px",fontWeight:800,letterSpacing:"0.05em",textTransform:"uppercase",width:"100%",textAlign:"center"},children:[t," →"]}):/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:n,textDecoration:"underline",fontWeight:600},children:t})},strong:({children:e})=>/* @__PURE__ */b("strong",{style:{fontWeight:700,color:"rgba(255,255,255,0.95)"},children:e}),em:({children:e})=>/* @__PURE__ */b("em",{style:{color:"rgba(255,255,255,0.8)"},children:e}),ul:({children:e})=>/* @__PURE__ */b("ul",{style:{margin:"4px 0",paddingLeft:"18px"},children:e}),ol:({children:e})=>/* @__PURE__ */b("ol",{style:{margin:"4px 0",paddingLeft:"18px"},children:e}),li:({children:e})=>/* @__PURE__ */b("li",{style:{marginBottom:"2px"},children:e}),hr:()=>/* @__PURE__ */b("hr",{style:{border:"none",borderTop:"1px solid rgba(255,255,255,0.1)",margin:"8px 0"}}),img:({src:e,alt:t})=>/* @__PURE__ */b("img",{src:e,alt:t||"",style:{maxWidth:"100%",borderRadius:"8px",margin:"6px 0"}}),code:({children:e})=>/* @__PURE__ */b("code",{style:{background:"rgba(255,255,255,0.1)",padding:"1px 5px",borderRadius:"4px",fontSize:"12px"},children:e})},children:e.text})})},t)),
113
+ /* @__PURE__ */b("div",{className:"relative shrink-0 flex justify-center",style:{padding:"16px 20px 8px"},children:/* @__PURE__ */b(Cc,{avatars:o,logoUrl:l,avatar3dUrl:c||h.avatar3dUrl,emotion:E,callState:m,audioLevel:S,config:h})}),
114
+ /* @__PURE__ */b("div",{className:"relative flex-1 overflow-y-auto px-5 pb-4",style:{scrollbarWidth:"none"},children:/* @__PURE__ */b("div",{className:"flex flex-col gap-4 w-full",children:N.length>0&&/* @__PURE__ */y("div",{style:{display:"flex",flexDirection:"column",gap:"8px",width:"100%"},children:[N.map((e,t)=>/* @__PURE__ */b("div",{style:{maxWidth:"85%",padding:"10px 14px",borderRadius:"user"===e.role?"16px 16px 4px 16px":"16px 16px 16px 4px",fontSize:"13.5px",lineHeight:1.5,color:"white",marginLeft:"user"===e.role?"auto":"0",marginRight:"user"===e.role?"0":"auto",backgroundColor:"user"===e.role?"rgba(255,255,255,0.08)":`${n}25`,backdropFilter:"blur(8px)",border:"user"===e.role?"1px solid rgba(255,255,255,0.08)":`1px solid ${n}20`},children:/* @__PURE__ */b("div",{className:"prose prose-sm prose-invert max-w-none break-words leading-relaxed",style:{fontSize:"13.5px"},children:/* @__PURE__ */b(ja,{remarkPlugins:[Al],rehypePlugins:[[$l,kc]],components:{p:({children:e})=>/* @__PURE__ */b("p",{style:{margin:"0 0 4px"},children:e}),a:({href:e,children:t})=>{if(!e)return null;const r=String(t).toLowerCase(),o=r.includes("reservar")||r.includes("ver")||r.includes("pagar");return e.includes("maps.google")||e.includes("goo.gl")||e.includes("google.com/maps")?/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",margin:"6px 0",borderRadius:"10px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",color:n,textDecoration:"none",fontSize:"12px",fontWeight:700},children:"📍 Ver ubicación"}):o?/* @__PURE__ */y("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"6px",padding:"8px 16px",margin:"6px 0",borderRadius:"10px",background:n,color:"white",textDecoration:"none",fontSize:"11px",fontWeight:800,letterSpacing:"0.05em",textTransform:"uppercase",width:"100%",textAlign:"center"},children:[t," →"]}):/* @__PURE__ */b("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:n,textDecoration:"underline",fontWeight:600},children:t})},strong:({children:e})=>/* @__PURE__ */b("strong",{style:{fontWeight:700,color:"rgba(255,255,255,0.95)"},children:e}),em:({children:e})=>/* @__PURE__ */b("em",{style:{color:"rgba(255,255,255,0.8)"},children:e}),ul:({children:e})=>/* @__PURE__ */b("ul",{style:{margin:"4px 0",paddingLeft:"18px"},children:e}),ol:({children:e})=>/* @__PURE__ */b("ol",{style:{margin:"4px 0",paddingLeft:"18px"},children:e}),li:({children:e})=>/* @__PURE__ */b("li",{style:{marginBottom:"2px"},children:e}),hr:()=>/* @__PURE__ */b("hr",{style:{border:"none",borderTop:"1px solid rgba(255,255,255,0.1)",margin:"8px 0"}}),img:({src:e,alt:t})=>/* @__PURE__ */b("img",{src:e,alt:t||"",style:{maxWidth:"100%",borderRadius:"8px",margin:"6px 0"}}),code:({children:e})=>/* @__PURE__ */b("code",{style:{background:"rgba(255,255,255,0.1)",padding:"1px 5px",borderRadius:"4px",fontSize:"12px"},children:e})},children:e.text})})},t)),
115
115
  /* @__PURE__ */b("div",{ref:q})]})})}),
116
116
  /* @__PURE__ */b("div",{style:{textAlign:"center",paddingBottom:"12px"},children:/* @__PURE__ */b("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"4px 16px",borderRadius:"20px",fontSize:"11px",fontWeight:500,color:"rgba(255,255,255,0.35)",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.06)",letterSpacing:"0.02em"},children:k?/* @__PURE__ */y(v,{children:[
117
117
  /* @__PURE__ */b(Q,{style:{width:"12px",height:"12px"}})," Micrófono silenciado"]}):"thinking"===m?"Procesando...":"speaking"===m?/* @__PURE__ */y(v,{children:[
@@ -123,7 +123,7 @@ return y("span",{style:{fontSize:"10px",padding:"2px 8px",borderRadius:"12px",ba
123
123
  /* @__PURE__ */b("button",{onClick:()=>I(e=>!e),style:{width:"52px",height:"52px",borderRadius:"50%",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.2s",backgroundColor:A?`${n}20`:"rgba(255,255,255,0.08)",color:A?n:"rgba(255,255,255,0.5)",border:"1px solid "+(A?`${n}30`:"rgba(255,255,255,0.08)")},"aria-label":"Escribir texto",children:/* @__PURE__ */b(J,{style:{width:"20px",height:"20px"}})})]}),A&&/* @__PURE__ */y("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 20px 20px"},children:[
124
124
  /* @__PURE__ */b("input",{type:"text",value:T,onChange:e=>M(e.target.value),onKeyDown:e=>"Enter"===e.key&&be(),placeholder:"Escribí email, teléfono, etc.",autoFocus:!0,style:{flex:1,padding:"10px 14px",borderRadius:"12px",border:"1px solid rgba(255,255,255,0.12)",background:"rgba(255,255,255,0.06)",color:"white",fontSize:"13px",outline:"none",backdropFilter:"blur(8px)"}}),
125
125
  /* @__PURE__ */b("button",{onClick:be,disabled:!T.trim(),style:{width:"40px",height:"40px",borderRadius:"50%",border:"none",cursor:T.trim()?"pointer":"default",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:T.trim()?n:"rgba(255,255,255,0.06)",color:T.trim()?"white":"rgba(255,255,255,0.2)",transition:"all 0.2s"},"aria-label":"Enviar texto",children:/* @__PURE__ */b(re,{style:{width:"16px",height:"16px"}})})]}),
126
- /* @__PURE__ */b("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes pulse {\n 0%, 100% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(0.95); }\n }\n "})]})}function _c({isOpen:e,isConnected:t,isTyping:n,messages:r,botName:o="BotUyo",logoUrl:l,welcomeMessage:c,inputPlaceholder:u,mediaConfig:d,onClose:p,onSendMessage:h,bubbleStyles:m,avatars:g,onSendAttachment:w,onSendLocation:x,getSocket:k,onAddVoiceMessage:_,avatar3dUrl:S,theme:C,suggestedQuestions:E}){const[z,N]=i(!1),[O,A]=i(!1),[I,T]=i(!1),{t:M}=D(),P=nc(),L=Ot({cssVariables:C?.cssVariables}),j=function({isOpen:e,height:t,bottom:n}){const r=nc(),[o,l]=i({}),c=s(()=>{if(r){const e=()=>{window.visualViewport?l({height:`${window.visualViewport.height}px`,transform:`translateY(${window.visualViewport.offsetTop}px)`}):l({height:"100dvh",transform:"none"})};return e(),window.visualViewport?.addEventListener("resize",e),window.visualViewport?.addEventListener("scroll",e),()=>{window.visualViewport?.removeEventListener("resize",e),window.visualViewport?.removeEventListener("scroll",e)}}{const e=parseFloat(n||rc)||24,r=window.innerHeight-64-e;if(t){const e=parseFloat(t)||700,o=Math.min(e,r);l({height:`${o}px`,maxHeight:`${r}px`,bottom:n||rc})}else{const e=Math.min(700,Math.max(500,r));l({height:`${e}px`,maxHeight:`${r}px`,bottom:n||rc})}}},[r,t,n]);return a(()=>{if(!e)return;const t=c();return window.addEventListener("resize",c),()=>{window.removeEventListener("resize",c),t&&t()}},[e,c]),o}({isOpen:e,height:C?.cssVariables?.windowHeight,bottom:C?.cssVariables?.windowBottom}),F=function({enabled:e,returnFocusRef:t,onEscape:n}){const r=f(null),o=f(null),i=f(n);i.current=n;const l=s(e=>{const t=r.current;if(t)if("Escape"!==e.key){if("Tab"===e.key){const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const r=n[0],o=n[n.length-1];e.shiftKey&&document.activeElement===r?(e.preventDefault(),o.focus()):e.shiftKey||document.activeElement!==o||(e.preventDefault(),r.focus())}}else i.current?.()},[]);return a(()=>{if(!e)return;o.current=document.activeElement;const n=t?.current,i=r.current;if(!i)return;const a=setTimeout(()=>{const e=i.querySelector('textarea, input[type="text"]');if(e)e.focus();else{const e=i.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');e.length>0?e[0].focus():i.focus()}},100);return document.addEventListener("keydown",l),()=>{clearTimeout(a),document.removeEventListener("keydown",l);const e=n||o.current;e&&"function"==typeof e.focus&&e.focus()}},[e,t,l]),r}({enabled:e,onEscape:p});if(a(()=>{if(e)return P&&(document.body.style.overflow="hidden"),()=>{document.body.style.overflow=""}},[e,P]),!e)return null;const R="bottom-left"===C?.position;/* @__PURE__ */
126
+ /* @__PURE__ */b("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes pulse {\n 0%, 100% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(0.95); }\n }\n "})]})}function Nc({isOpen:e,isConnected:t,isTyping:n,messages:r,botName:o="BotUyo",logoUrl:l,welcomeMessage:c,inputPlaceholder:u,mediaConfig:d,onClose:p,onSendMessage:h,bubbleStyles:m,avatars:g,onSendAttachment:w,onSendLocation:x,getSocket:k,onAddVoiceMessage:_,avatar3dUrl:S,theme:C,suggestedQuestions:E}){const[z,N]=i(!1),[O,A]=i(!1),[I,T]=i(!1),{t:M}=D(),P=nc(),L=Ot({cssVariables:C?.cssVariables}),j=function({isOpen:e,height:t,bottom:n}){const r=nc(),[o,l]=i({}),c=s(()=>{if(r){const e=()=>{window.visualViewport?l({height:`${window.visualViewport.height}px`,transform:`translateY(${window.visualViewport.offsetTop}px)`}):l({height:"100dvh",transform:"none"})};return e(),window.visualViewport?.addEventListener("resize",e),window.visualViewport?.addEventListener("scroll",e),()=>{window.visualViewport?.removeEventListener("resize",e),window.visualViewport?.removeEventListener("scroll",e)}}{const e=parseFloat(n||rc)||24,r=window.innerHeight-64-e;if(t){const e=parseFloat(t)||700,o=Math.min(e,r);l({height:`${o}px`,maxHeight:`${r}px`,bottom:n||rc})}else{const e=Math.min(700,Math.max(500,r));l({height:`${e}px`,maxHeight:`${r}px`,bottom:n||rc})}}},[r,t,n]);return a(()=>{if(!e)return;const t=c();return window.addEventListener("resize",c),()=>{window.removeEventListener("resize",c),t&&t()}},[e,c]),o}({isOpen:e,height:C?.cssVariables?.windowHeight,bottom:C?.cssVariables?.windowBottom}),F=function({enabled:e,returnFocusRef:t,onEscape:n}){const r=f(null),o=f(null),i=f(n);i.current=n;const l=s(e=>{const t=r.current;if(t)if("Escape"!==e.key){if("Tab"===e.key){const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const r=n[0],o=n[n.length-1];e.shiftKey&&document.activeElement===r?(e.preventDefault(),o.focus()):e.shiftKey||document.activeElement!==o||(e.preventDefault(),r.focus())}}else i.current?.()},[]);return a(()=>{if(!e)return;o.current=document.activeElement;const n=t?.current,i=r.current;if(!i)return;const a=setTimeout(()=>{const e=i.querySelector('textarea, input[type="text"]');if(e)e.focus();else{const e=i.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');e.length>0?e[0].focus():i.focus()}},100);return document.addEventListener("keydown",l),()=>{clearTimeout(a),document.removeEventListener("keydown",l);const e=n||o.current;e&&"function"==typeof e.focus&&e.focus()}},[e,t,l]),r}({enabled:e,onEscape:p});if(a(()=>{if(e)return P&&(document.body.style.overflow="hidden"),()=>{document.body.style.overflow=""}},[e,P]),!e)return null;const R="bottom-left"===C?.position;/* @__PURE__ */
127
127
  return y(v,{children:[
128
128
  /* @__PURE__ */b("div",{id:"chat-dialog-description",className:"sr-only",children:M("accessibility.dialogDescription",{botName:o??"BotUyo"})}),
129
129
  /* @__PURE__ */y("div",{ref:F,role:"dialog","aria-modal":"true","aria-labelledby":"chat-window-title","aria-describedby":"chat-dialog-description",tabIndex:-1,className:Et("flex flex-col overflow-hidden transition-all duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]","text-foreground z-[9999]",!P&&["fixed",R?"left-6":"right-6","border","animate-in fade-in zoom-in-95","slide-in-from-bottom-10"],P&&["fixed inset-0 w-full"]),style:{...j,...P?{}:{width:"350px",minWidth:"350px",maxWidth:"350px",borderRadius:"32px",boxShadow:"0 25px 65px -5px rgba(0, 0, 0, 0.15), 0 8px 20px -8px rgba(0, 0, 0, 0.1)"},backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))",color:"hsl(var(--foreground))"},children:[
@@ -154,36 +154,36 @@ return y(v,{children:[
154
154
  /* @__PURE__ */y("div",{className:"flex items-center justify-center gap-1 opacity-25 select-none",style:{marginTop:"var(--spacing-2)",paddingBottom:"var(--spacing-1)"},children:[
155
155
  /* @__PURE__ */b(H,{className:"h-2 w-2 text-primary fill-primary"}),
156
156
  /* @__PURE__ */b("span",{className:"text-[7px] font-bold uppercase tracking-[0.2em]",children:M("con_amor_paseo_libre")})]})]}),
157
- /* @__PURE__ */b(kc,{isOpen:O,onClose:()=>A(!1),primaryColor:L,avatars:g,logoUrl:l,avatar3dUrl:S,getSocket:k,onAddMessage:_})]})]})}class Sc extends m{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){jt("ErrorBoundary caught error:",e,t),this.props.onError?.(e,t)}handleReset=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:/* @__PURE__ */y("div",{className:"flex flex-col items-center justify-center p-8 bg-background text-center",children:[
157
+ /* @__PURE__ */b(zc,{isOpen:O,onClose:()=>A(!1),primaryColor:L,avatars:g,logoUrl:l,avatar3dUrl:S,getSocket:k,onAddMessage:_})]})]})}class Oc extends m{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){jt("ErrorBoundary caught error:",e,t),this.props.onError?.(e,t)}handleReset=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:/* @__PURE__ */y("div",{className:"flex flex-col items-center justify-center p-8 bg-background text-center",children:[
158
158
  /* @__PURE__ */b("div",{className:"text-6xl mb-4",children:"⚠️"}),
159
159
  /* @__PURE__ */b("h2",{className:"text-xl font-bold text-foreground mb-2",children:"Algo salió mal"}),
160
160
  /* @__PURE__ */b("p",{className:"text-sm text-muted-foreground mb-6 max-w-md",children:this.state.error?.message||"Ocurrió un error inesperado"}),
161
- /* @__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 Cc={bubble:"rounded-2xl",image:"rounded-xl",button:"rounded-xl",card:"rounded-2xl"},Ec={bg:"bg-muted/50 dark:bg-muted/20",text:"text-foreground",border:"border-border/50"},zc={text:"text-primary-foreground"};const Nc=(e,t)=>t.some(t=>e instanceof t);let Oc,Ac;const Ic=/* @__PURE__ */new WeakMap,Tc=/* @__PURE__ */new WeakMap,Mc=/* @__PURE__ */new WeakMap;let Pc={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Ic.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return jc(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Lc(e){Pc=e(Pc)}function Dc(e){return"function"==typeof e?(t=e,(Ac||(Ac=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(Fc(this),e),jc(this.request)}:function(...e){return jc(t.apply(Fc(this),e))}):(e instanceof IDBTransaction&&function(e){if(Ic.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)});Ic.set(e,t)}(e),Nc(e,Oc||(Oc=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Pc):e);var t}function jc(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(jc(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)});return Mc.set(t,e),t}(e);if(Tc.has(e))return Tc.get(e);const t=Dc(e);return t!==e&&(Tc.set(e,t),Mc.set(t,e)),t}const Fc=e=>Mc.get(e),Rc=["get","getKey","getAll","getAllKeys","count"],$c=["put","add","delete","clear"],Bc=/* @__PURE__ */new Map;function Uc(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Bc.get(t))return Bc.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=$c.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!Rc.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 Bc.set(t,i),i}Lc(e=>({...e,get:(t,n,r)=>Uc(t,n)||e.get(t,n,r),has:(t,n)=>!!Uc(t,n)||e.has(t,n)}));const Vc=["continue","continuePrimaryKey","advance"],qc={},Wc=/* @__PURE__ */new WeakMap,Hc=/* @__PURE__ */new WeakMap,Zc={get(e,t){if(!Vc.includes(t))return e[t];let n=qc[t];return n||(n=qc[t]=function(...e){Wc.set(this,Hc.get(this)[t](...e))}),n}};async function*Jc(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,Zc);for(Hc.set(n,t),Mc.set(n,Fc(t));t;)yield n,t=await(Wc.get(n)||t.continue()),Wc.delete(n)}function Kc(e,t){return t===Symbol.asyncIterator&&Nc(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&Nc(e,[IDBIndex,IDBObjectStore])}Lc(e=>({...e,get:(t,n,r)=>Kc(t,n)?Jc:e.get(t,n,r),has:(t,n)=>Kc(t,n)||e.has(t,n)}));class Gc{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=jc(a);return r&&a.addEventListener("upgradeneeded",e=>{r(jc(a.result),e.oldVersion,e.newVersion,jc(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")}}),Rt("IndexedDB initialized")}catch(e){throw jt("Failed to initialize IndexedDB:",e),e}}async saveMessage(e){this.db||await this.init();try{await this.db.put("messages",e)}catch(t){jt("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){jt("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 jt("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 jt("Failed to get message:",t)}}async deleteMessage(e){this.db||await this.init();try{await this.db.delete("messages",e)}catch(t){jt("Failed to delete message:",t)}}async clearMessages(){this.db||await this.init();try{await this.db.clear("messages"),Rt("Messages cleared from IndexedDB")}catch(e){jt("Failed to clear messages:",e)}}async setMetadata(e){this.db||await this.init();try{await this.db.put("metadata",e,"chat-metadata")}catch(t){jt("Failed to set metadata:",t)}}async getMetadata(){this.db||await this.init();try{return await this.db.get("metadata","chat-metadata")}catch(e){return jt("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")]),Rt("All data cleared from IndexedDB")}catch(e){jt("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),Rt(`Migrated ${e.length} messages from localStorage`)}o.sessionId&&await this.setMetadata({sessionId:o.sessionId}),localStorage.removeItem(n),Rt("Migration from localStorage completed")}catch(n){jt("Failed to migrate from localStorage:",n)}}}const Yc=/* @__PURE__ */new Map,Qc={isOpen:!1,isConnected:!1,isTyping:!1,messages:[],error:null,sessionId:null};function Xc(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"CLEAR_CHAT":return{...Qc,isOpen:e.isOpen};case"RESTORE_SESSION":return{...e,...t.payload,isConnected:!1,isTyping:!1,error:null};default:return e}}function eu(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 tu extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class nu extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const ru={};function ou(e){return ru}function iu(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 au(e,t){return"bigint"==typeof t?t.toString():t}function su(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function lu(e){return null==e}function cu(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const uu=/* @__PURE__ */Symbol("evaluating");function du(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==uu)return void 0===r&&(r=uu,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function pu(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function hu(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function fu(e){return JSON.stringify(e)}const mu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function gu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const bu=su(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function yu(e){if(!1===gu(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!==gu(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function vu(e){return yu(e)?{...e}:Array.isArray(e)?[...e]:e}const wu=/* @__PURE__ */new Set(["string","number","symbol"]);function xu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ku(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function _u(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 Su={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 Cu(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 Eu(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function zu(e){return"string"==typeof e?e:e?.message}function Nu(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=zu(e.inst?._zod.def?.error?.(e))??zu(t?.error?.(e))??zu(n.customError?.(e))??zu(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Ou(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Au(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Iu=(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,au,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Tu=eu("$ZodError",Iu),Mu=eu("$ZodError",Iu,{Parent:Error}),Pu=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 tu;if(a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Nu(e,i,ou())));throw mu(t,o?.callee),t}return a.value},Lu=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=>Nu(e,i,ou())));throw mu(t,o?.callee),t}return a.value},Du=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 tu;return i.issues.length?{success:!1,error:new(e??Tu)(i.issues.map(e=>Nu(e,o,ou())))}:{success:!0,data:i.value}},ju=/* @__PURE__ */Du(Mu),Fu=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=>Nu(e,o,ou())))}:{success:!0,data:i.value}},Ru=/* @__PURE__ */Fu(Mu),$u=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Pu(e)(t,n,o)},Bu=e=>(t,n,r)=>Pu(e)(t,n,r),Uu=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Lu(e)(t,n,o)},Vu=e=>async(t,n,r)=>Lu(e)(t,n,r),qu=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Du(e)(t,n,o)},Wu=e=>(t,n,r)=>Du(e)(t,n,r),Hu=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Fu(e)(t,n,o)},Zu=e=>async(t,n,r)=>Fu(e)(t,n,r),Ju=/^[cC][^\s-]{8,}$/,Ku=/^[0-9a-z]+$/,Gu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yu=/^[0-9a-vA-V]{20}$/,Qu=/^[A-Za-z0-9]{27}$/,Xu=/^[a-zA-Z0-9_-]{21}$/,ed=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,td=/^([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})$/,nd=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)$/,rd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,od=/^(?:(?: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])$/,id=/^(([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}|:))$/,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])\/([0-9]|[1-2][0-9]|3[0-2])$/,sd=/^(([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])$/,ld=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cd=/^[A-Za-z0-9_-]*$/,ud=/^\+[1-9]\d{6,14}$/,dd="(?:(?:\\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])))",pd=/* @__PURE__ */new RegExp(`^${dd}$`);function hd(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 fd=/^-?\d+$/,md=/^-?\d+(?:\.\d+)?$/,gd=/^[^A-Z]*$/,bd=/^[^a-z]*$/,yd=/* @__PURE__ */eu("$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__ */eu("$ZodCheckLessThan",(e,t)=>{yd.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})}}),xd=/* @__PURE__ */eu("$ZodCheckGreaterThan",(e,t)=>{yd.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})}}),kd=/* @__PURE__ */eu("$ZodCheckMultipleOf",(e,t)=>{yd.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})}}),_d=/* @__PURE__ */eu("$ZodCheckNumberFormat",(e,t)=>{yd.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Su[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=fd)}),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})}}),Sd=/* @__PURE__ */eu("$ZodCheckMaxLength",(e,t)=>{var n;yd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!lu(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=Ou(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Cd=/* @__PURE__ */eu("$ZodCheckMinLength",(e,t)=>{var n;yd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!lu(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=Ou(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ed=/* @__PURE__ */eu("$ZodCheckLengthEquals",(e,t)=>{var n;yd.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!lu(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=Ou(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})}}),zd=/* @__PURE__ */eu("$ZodCheckStringFormat",(e,t)=>{var n,r;yd.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=()=>{})}),Nd=/* @__PURE__ */eu("$ZodCheckRegex",(e,t)=>{zd.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})}}),Od=/* @__PURE__ */eu("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=gd),zd.init(e,t)}),Ad=/* @__PURE__ */eu("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=bd),zd.init(e,t)}),Id=/* @__PURE__ */eu("$ZodCheckIncludes",(e,t)=>{yd.init(e,t);const n=xu(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})}}),Td=/* @__PURE__ */eu("$ZodCheckStartsWith",(e,t)=>{yd.init(e,t);const n=new RegExp(`^${xu(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})}}),Md=/* @__PURE__ */eu("$ZodCheckEndsWith",(e,t)=>{yd.init(e,t);const n=new RegExp(`.*${xu(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})}}),Pd=/* @__PURE__ */eu("$ZodCheckOverwrite",(e,t)=>{yd.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Ld{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 Dd={major:4,minor:3,patch:6},jd=/* @__PURE__ */eu("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Dd;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=Cu(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 tu;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(o||(o=Cu(e,t)))});else{if(e.issues.length===t)continue;o||(o=Cu(e,t))}}return r?r.then(()=>e):e},n=(n,o,i)=>{if(Cu(n))return n.aborted=!0,n;const a=t(o,r,i);if(a instanceof Promise){if(!1===i.async)throw new tu;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 tu;return a.then(e=>t(e,r,i))}return t(a,r,i)}}du(e,"~standard",()=>({validate:t=>{try{const n=ju(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return Ru(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Fd=/* @__PURE__ */eu("$ZodString",(e,t)=>{var n;jd.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}}),Rd=/* @__PURE__ */eu("$ZodStringFormat",(e,t)=>{zd.init(e,t),Fd.init(e,t)}),$d=/* @__PURE__ */eu("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=td),Rd.init(e,t)}),Bd=/* @__PURE__ */eu("$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=nd(e))}else t.pattern??(t.pattern=nd());Rd.init(e,t)}),Ud=/* @__PURE__ */eu("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=rd),Rd.init(e,t)}),Vd=/* @__PURE__ */eu("$ZodURL",(e,t)=>{Rd.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})}}}),qd=/* @__PURE__ */eu("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Rd.init(e,t)}),Wd=/* @__PURE__ */eu("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Xu),Rd.init(e,t)}),Hd=/* @__PURE__ */eu("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ju),Rd.init(e,t)}),Zd=/* @__PURE__ */eu("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ku),Rd.init(e,t)}),Jd=/* @__PURE__ */eu("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Gu),Rd.init(e,t)}),Kd=/* @__PURE__ */eu("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Yu),Rd.init(e,t)}),Gd=/* @__PURE__ */eu("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Qu),Rd.init(e,t)}),Yd=/* @__PURE__ */eu("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=hd({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(`^${dd}T(?:${r})$`)}(t)),Rd.init(e,t)}),Qd=/* @__PURE__ */eu("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=pd),Rd.init(e,t)}),Xd=/* @__PURE__ */eu("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${hd(t)}$`)),Rd.init(e,t)}),ep=/* @__PURE__ */eu("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ed),Rd.init(e,t)}),tp=/* @__PURE__ */eu("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=od),Rd.init(e,t),e._zod.bag.format="ipv4"}),np=/* @__PURE__ */eu("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=id),Rd.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})}}}),rp=/* @__PURE__ */eu("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ad),Rd.init(e,t)}),op=/* @__PURE__ */eu("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=sd),Rd.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 ip(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const ap=/* @__PURE__ */eu("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ld),Rd.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ip(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),sp=/* @__PURE__ */eu("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=cd),Rd.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!cd.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ip(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})}}),lp=/* @__PURE__ */eu("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ud),Rd.init(e,t)}),cp=/* @__PURE__ */eu("$ZodJWT",(e,t)=>{Rd.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})}}),up=/* @__PURE__ */eu("$ZodNumber",(e,t)=>{jd.init(e,t),e._zod.pattern=e._zod.bag.pattern??md,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__ */eu("$ZodNumberFormat",(e,t)=>{_d.init(e,t),up.init(e,t)}),pp=/* @__PURE__ */eu("$ZodAny",(e,t)=>{jd.init(e,t),e._zod.parse=e=>e}),hp=/* @__PURE__ */eu("$ZodUnknown",(e,t)=>{jd.init(e,t),e._zod.parse=e=>e}),fp=/* @__PURE__ */eu("$ZodNever",(e,t)=>{jd.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function mp(e,t,n){e.issues.length&&t.issues.push(...Eu(n,e.issues)),t.value[n]=e.value}const gp=/* @__PURE__ */eu("$ZodArray",(e,t)=>{jd.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=>mp(t,n,e))):mp(s,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function bp(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...Eu(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function yp(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=>bp(e,n,d,t,u))):bp(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__ */eu("$ZodObject",(e,t)=>{jd.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=su(()=>yp(t));du(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=gu,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=>bp(n,t,e,s,o))):bp(i,t,e,s,o)}return i?vp(l,s,t,n,r.value,e):l.length?Promise.all(l).then(()=>t):t}}),xp=/* @__PURE__ */eu("$ZodObjectJIT",(e,t)=>{wp.init(e,t);const n=e._zod.parse,r=su(()=>yp(t));let o;const i=gu,a=!ru.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 Ld(["shape","payload","ctx"]),n=r.value,o=e=>{const t=fu(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=fu(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 kp(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=>!Cu(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=>Nu(e,r,ou())))}),t)}const _p=/* @__PURE__ */eu("$ZodUnion",(e,t)=>{jd.init(e,t),du(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),du(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),du(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),du(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=>cu(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=>kp(t,o,e,i)):kp(s,o,e,i)}}),Sp=/* @__PURE__ */eu("$ZodIntersection",(e,t)=>{jd.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])=>Ep(e,t,n)):Ep(e,o,i)}});function Cp(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(yu(e)&&yu(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=Cp(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=Cp(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 Ep(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}),Cu(e))return e;const a=Cp(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 zp=/* @__PURE__ */eu("$ZodEnum",(e,t)=>{jd.init(e,t);const n=iu(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>wu.has(typeof e)).map(e=>"string"==typeof e?xu(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}}),Np=/* @__PURE__ */eu("$ZodTransform",(e,t)=>{jd.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new nu(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 tu;return n.value=o,n}});function Op(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Ap=/* @__PURE__ */eu("$ZodOptional",(e,t)=>{jd.init(e,t),e._zod.optin="optional",e._zod.optout="optional",du(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,void 0]):void 0),du(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cu(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=>Op(t,e.value)):Op(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Ip=/* @__PURE__ */eu("$ZodExactOptional",(e,t)=>{Ap.init(e,t),du(e._zod,"values",()=>t.innerType._zod.values),du(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Tp=/* @__PURE__ */eu("$ZodNullable",(e,t)=>{jd.init(e,t),du(e._zod,"optin",()=>t.innerType._zod.optin),du(e._zod,"optout",()=>t.innerType._zod.optout),du(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cu(e.source)}|null)$`):void 0}),du(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)}),Mp=/* @__PURE__ */eu("$ZodDefault",(e,t)=>{jd.init(e,t),e._zod.optin="optional",du(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=>Pp(e,t)):Pp(r,t)}});function Pp(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Lp=/* @__PURE__ */eu("$ZodPrefault",(e,t)=>{jd.init(e,t),e._zod.optin="optional",du(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))}),Dp=/* @__PURE__ */eu("$ZodNonOptional",(e,t)=>{jd.init(e,t),du(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=>jp(t,e)):jp(o,e)}});function jp(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 Fp=/* @__PURE__ */eu("$ZodCatch",(e,t)=>{jd.init(e,t),du(e._zod,"optin",()=>t.innerType._zod.optin),du(e._zod,"optout",()=>t.innerType._zod.optout),du(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=>Nu(e,n,ou()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Nu(e,n,ou()))},input:e.value}),e.issues=[]),e)}}),Rp=/* @__PURE__ */eu("$ZodPipe",(e,t)=>{jd.init(e,t),du(e._zod,"values",()=>t.in._zod.values),du(e._zod,"optin",()=>t.in._zod.optin),du(e._zod,"optout",()=>t.out._zod.optout),du(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=>$p(e,t.in,n)):$p(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>$p(e,t.out,n)):$p(r,t.out,n)}});function $p(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Bp=/* @__PURE__ */eu("$ZodReadonly",(e,t)=>{jd.init(e,t),du(e._zod,"propValues",()=>t.innerType._zod.propValues),du(e._zod,"values",()=>t.innerType._zod.values),du(e._zod,"optin",()=>t.innerType?._zod?.optin),du(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(Up):Up(r)}});function Up(e){return e.value=Object.freeze(e.value),e}const Vp=/* @__PURE__ */eu("$ZodCustom",(e,t)=>{yd.init(e,t),jd.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=>qp(t,n,r,e));qp(o,n,r,e)}});function qp(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(Au(e))}}var Wp;(Wp=globalThis).__zod_globalRegistry??(Wp.__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 Hp=globalThis.__zod_globalRegistry;function Zp(e,t){return new e({type:"string",..._u(t)})}function Jp(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,..._u(t)})}function Kp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,..._u(t)})}function Gp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,..._u(t)})}function Yp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._u(t)})}function Qp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._u(t)})}function Xp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._u(t)})}function eh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,..._u(t)})}function th(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,..._u(t)})}function nh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,..._u(t)})}function rh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,..._u(t)})}function oh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,..._u(t)})}function ih(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,..._u(t)})}function ah(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,..._u(t)})}function sh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,..._u(t)})}function lh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,..._u(t)})}function ch(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,..._u(t)})}function uh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._u(t)})}function dh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._u(t)})}function ph(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,..._u(t)})}function hh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,..._u(t)})}function fh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,..._u(t)})}function mh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,..._u(t)})}function gh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._u(t)})}function bh(e,t){return new e({type:"string",format:"date",check:"string_format",..._u(t)})}function yh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,..._u(t)})}function vh(e,t){return new e({type:"string",format:"duration",check:"string_format",..._u(t)})}function wh(e,t){return new e({type:"number",checks:[],..._u(t)})}function xh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",..._u(t)})}function kh(e){return new e({type:"any"})}function _h(e){return new e({type:"unknown"})}function Sh(e,t){return new e({type:"never",..._u(t)})}function Ch(e,t){return new wd({check:"less_than",..._u(t),value:e,inclusive:!1})}function Eh(e,t){return new wd({check:"less_than",..._u(t),value:e,inclusive:!0})}function zh(e,t){return new xd({check:"greater_than",..._u(t),value:e,inclusive:!1})}function Nh(e,t){return new xd({check:"greater_than",..._u(t),value:e,inclusive:!0})}function Oh(e,t){return new kd({check:"multiple_of",..._u(t),value:e})}function Ah(e,t){return new Sd({check:"max_length",..._u(t),maximum:e})}function Ih(e,t){return new Cd({check:"min_length",..._u(t),minimum:e})}function Th(e,t){return new Ed({check:"length_equals",..._u(t),length:e})}function Mh(e,t){return new Nd({check:"string_format",format:"regex",..._u(t),pattern:e})}function Ph(e){return new Od({check:"string_format",format:"lowercase",..._u(e)})}function Lh(e){return new Ad({check:"string_format",format:"uppercase",..._u(e)})}function Dh(e,t){return new Id({check:"string_format",format:"includes",..._u(t),includes:e})}function jh(e,t){return new Td({check:"string_format",format:"starts_with",..._u(t),prefix:e})}function Fh(e,t){return new Md({check:"string_format",format:"ends_with",..._u(t),suffix:e})}function Rh(e){return new Pd({check:"overwrite",tx:e})}function $h(e){/* @__PURE__ */
162
- return Rh(t=>t.normalize(e))}function Bh(){/* @__PURE__ */
163
- return Rh(e=>e.trim())}function Uh(){/* @__PURE__ */
164
- return Rh(e=>e.toLowerCase())}function Vh(){/* @__PURE__ */
165
- return Rh(e=>e.toUpperCase())}function qh(){/* @__PURE__ */
166
- return Rh(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e))}function Wh(e,t,n){return new e({type:"array",element:t,..._u(n)})}function Hh(e,t,n){return new e({type:"custom",check:"custom",fn:t,..._u(n)})}function Zh(e){const t=/* @__PURE__ */Jh(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Au(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(Au(r))}},e(n.value,n)));return t}function Jh(e,t){const n=new yd({check:"custom",..._u(t)});return n._zod.check=e,n}function Kh(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??Hp,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 Gh(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),Gh(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&&Xh(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 Yh(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 Qh(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:ef(t,"input",e.processors),output:ef(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(a){throw new Error("Error converting schema to JSON.")}}function Xh(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 Xh(r.element,n);if("set"===r.type)return Xh(r.valueType,n);if("lazy"===r.type)return Xh(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 Xh(r.innerType,n);if("intersection"===r.type)return Xh(r.left,n)||Xh(r.right,n);if("record"===r.type||"map"===r.type)return Xh(r.keyType,n)||Xh(r.valueType,n);if("pipe"===r.type)return Xh(r.in,n)||Xh(r.out,n);if("object"===r.type){for(const e in r.shape)if(Xh(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(Xh(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(Xh(e,n))return!0;return!(!r.rest||!Xh(r.rest,n))}return!1}const ef=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},a=Kh({...o??{},target:i,io:t,processors:n});return Gh(e,a),Yh(a,e),Qh(a,e)},tf={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},nf=(e,t,n,r)=>{const o=e._zod.def;Gh(o.innerType,t,r),t.seen.get(e).ref=o.innerType},rf=/* @__PURE__ */eu("ZodISODateTime",(e,t)=>{Yd.init(e,t),Cf.init(e,t)}),of=/* @__PURE__ */eu("ZodISODate",(e,t)=>{Qd.init(e,t),Cf.init(e,t)}),af=/* @__PURE__ */eu("ZodISOTime",(e,t)=>{Xd.init(e,t),Cf.init(e,t)}),sf=/* @__PURE__ */eu("ZodISODuration",(e,t)=>{ep.init(e,t),Cf.init(e,t)}),lf=eu("ZodError",(e,t)=>{Tu.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,au,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,au,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),cf=/* @__PURE__ */Pu(lf),uf=/* @__PURE__ */Lu(lf),df=/* @__PURE__ */Du(lf),pf=/* @__PURE__ */Fu(lf),hf=/* @__PURE__ */$u(lf),ff=/* @__PURE__ */Bu(lf),mf=/* @__PURE__ */Uu(lf),gf=/* @__PURE__ */Vu(lf),bf=/* @__PURE__ */qu(lf),yf=/* @__PURE__ */Wu(lf),vf=/* @__PURE__ */Hu(lf),wf=/* @__PURE__ */Zu(lf),xf=/* @__PURE__ */eu("ZodType",(e,t)=>(jd.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ef(e,"input"),output:ef(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Kh({...n,processors:t});return Gh(e,r),Yh(r,e),Qh(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(hu(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)=>ku(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>cf(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>df(e,t,n),e.parseAsync=async(t,n)=>uf(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>pf(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>hf(e,t,n),e.decode=(t,n)=>ff(e,t,n),e.encodeAsync=async(t,n)=>mf(e,t,n),e.decodeAsync=async(t,n)=>gf(e,t,n),e.safeEncode=(t,n)=>bf(e,t,n),e.safeDecode=(t,n)=>yf(e,t,n),e.safeEncodeAsync=async(t,n)=>vf(e,t,n),e.safeDecodeAsync=async(t,n)=>wf(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){/* @__PURE__ */
167
- return Hh(vm,e,t)}(t,n)),e.superRefine=t=>e.check(/* @__PURE__ */Zh(t)),e.overwrite=t=>e.check(/* @__PURE__ */Rh(t)),e.optional=()=>lm(e),e.exactOptional=()=>new cm({type:"optional",innerType:e}),e.nullable=()=>dm(e),e.nullish=()=>lm(dm(e)),e.nonoptional=t=>function(e,t){return new fm({type:"nonoptional",innerType:e,..._u(t)})}(e,t),e.array=()=>em(e),e.or=t=>new nm({type:"union",options:[e,t],..._u(void 0)}),e.and=t=>new rm({type:"intersection",left:e,right:t}),e.transform=t=>bm(e,new am({type:"transform",transform:t})),e.default=t=>{return n=t,new pm({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():vu(n)}});var n},e.prefault=t=>{return n=t,new hm({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():vu(n)}});var n},e.catch=t=>{return new mm({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>bm(e,t),e.readonly=()=>new ym({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return Hp.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>Hp.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Hp.get(e);const n=e.clone();return Hp.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),kf=/* @__PURE__ */eu("_ZodString",(e,t)=>{Fd.init(e,t),xf.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__ */Mh(...t)),e.includes=(...t)=>e.check(/* @__PURE__ */Dh(...t)),e.startsWith=(...t)=>e.check(/* @__PURE__ */jh(...t)),e.endsWith=(...t)=>e.check(/* @__PURE__ */Fh(...t)),e.min=(...t)=>e.check(/* @__PURE__ */Ih(...t)),e.max=(...t)=>e.check(/* @__PURE__ */Ah(...t)),e.length=(...t)=>e.check(/* @__PURE__ */Th(...t)),e.nonempty=(...t)=>e.check(/* @__PURE__ */Ih(1,...t)),e.lowercase=t=>e.check(/* @__PURE__ */Ph(t)),e.uppercase=t=>e.check(/* @__PURE__ */Lh(t)),e.trim=()=>e.check(/* @__PURE__ */Bh()),e.normalize=(...t)=>e.check(/* @__PURE__ */$h(...t)),e.toLowerCase=()=>e.check(/* @__PURE__ */Uh()),e.toUpperCase=()=>e.check(/* @__PURE__ */Vh()),e.slugify=()=>e.check(/* @__PURE__ */qh())}),_f=/* @__PURE__ */eu("ZodString",(e,t)=>{Fd.init(e,t),kf.init(e,t),e.email=t=>e.check(/* @__PURE__ */Jp(Ef,t)),e.url=t=>e.check(/* @__PURE__ */eh(Of,t)),e.jwt=t=>e.check(/* @__PURE__ */mh(qf,t)),e.emoji=t=>e.check(/* @__PURE__ */th(Af,t)),e.guid=t=>e.check(/* @__PURE__ */Kp(zf,t)),e.uuid=t=>e.check(/* @__PURE__ */Gp(Nf,t)),e.uuidv4=t=>e.check(/* @__PURE__ */Yp(Nf,t)),e.uuidv6=t=>e.check(/* @__PURE__ */Qp(Nf,t)),e.uuidv7=t=>e.check(/* @__PURE__ */Xp(Nf,t)),e.nanoid=t=>e.check(/* @__PURE__ */nh(If,t)),e.guid=t=>e.check(/* @__PURE__ */Kp(zf,t)),e.cuid=t=>e.check(/* @__PURE__ */rh(Tf,t)),e.cuid2=t=>e.check(/* @__PURE__ */oh(Mf,t)),e.ulid=t=>e.check(/* @__PURE__ */ih(Pf,t)),e.base64=t=>e.check(/* @__PURE__ */ph(Bf,t)),e.base64url=t=>e.check(/* @__PURE__ */hh(Uf,t)),e.xid=t=>e.check(/* @__PURE__ */ah(Lf,t)),e.ksuid=t=>e.check(/* @__PURE__ */sh(Df,t)),e.ipv4=t=>e.check(/* @__PURE__ */lh(jf,t)),e.ipv6=t=>e.check(/* @__PURE__ */ch(Ff,t)),e.cidrv4=t=>e.check(/* @__PURE__ */uh(Rf,t)),e.cidrv6=t=>e.check(/* @__PURE__ */dh($f,t)),e.e164=t=>e.check(/* @__PURE__ */fh(Vf,t)),e.datetime=t=>e.check(function(e){/* @__PURE__ */
168
- return gh(rf,e)}(t)),e.date=t=>e.check(function(e){/* @__PURE__ */
169
- return bh(of,e)}(t)),e.time=t=>e.check(function(e){/* @__PURE__ */
170
- return yh(af,e)}(t)),e.duration=t=>e.check(function(e){/* @__PURE__ */
171
- return vh(sf,e)}(t))});function Sf(e){/* @__PURE__ */
172
- return Zp(_f,e)}const Cf=/* @__PURE__ */eu("ZodStringFormat",(e,t)=>{Rd.init(e,t),kf.init(e,t)}),Ef=/* @__PURE__ */eu("ZodEmail",(e,t)=>{Ud.init(e,t),Cf.init(e,t)}),zf=/* @__PURE__ */eu("ZodGUID",(e,t)=>{$d.init(e,t),Cf.init(e,t)}),Nf=/* @__PURE__ */eu("ZodUUID",(e,t)=>{Bd.init(e,t),Cf.init(e,t)}),Of=/* @__PURE__ */eu("ZodURL",(e,t)=>{Vd.init(e,t),Cf.init(e,t)}),Af=/* @__PURE__ */eu("ZodEmoji",(e,t)=>{qd.init(e,t),Cf.init(e,t)}),If=/* @__PURE__ */eu("ZodNanoID",(e,t)=>{Wd.init(e,t),Cf.init(e,t)}),Tf=/* @__PURE__ */eu("ZodCUID",(e,t)=>{Hd.init(e,t),Cf.init(e,t)}),Mf=/* @__PURE__ */eu("ZodCUID2",(e,t)=>{Zd.init(e,t),Cf.init(e,t)}),Pf=/* @__PURE__ */eu("ZodULID",(e,t)=>{Jd.init(e,t),Cf.init(e,t)}),Lf=/* @__PURE__ */eu("ZodXID",(e,t)=>{Kd.init(e,t),Cf.init(e,t)}),Df=/* @__PURE__ */eu("ZodKSUID",(e,t)=>{Gd.init(e,t),Cf.init(e,t)}),jf=/* @__PURE__ */eu("ZodIPv4",(e,t)=>{tp.init(e,t),Cf.init(e,t)}),Ff=/* @__PURE__ */eu("ZodIPv6",(e,t)=>{np.init(e,t),Cf.init(e,t)}),Rf=/* @__PURE__ */eu("ZodCIDRv4",(e,t)=>{rp.init(e,t),Cf.init(e,t)}),$f=/* @__PURE__ */eu("ZodCIDRv6",(e,t)=>{op.init(e,t),Cf.init(e,t)}),Bf=/* @__PURE__ */eu("ZodBase64",(e,t)=>{ap.init(e,t),Cf.init(e,t)}),Uf=/* @__PURE__ */eu("ZodBase64URL",(e,t)=>{sp.init(e,t),Cf.init(e,t)}),Vf=/* @__PURE__ */eu("ZodE164",(e,t)=>{lp.init(e,t),Cf.init(e,t)}),qf=/* @__PURE__ */eu("ZodJWT",(e,t)=>{cp.init(e,t),Cf.init(e,t)}),Wf=/* @__PURE__ */eu("ZodNumber",(e,t)=>{up.init(e,t),xf.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__ */zh(t,n)),e.gte=(t,n)=>e.check(/* @__PURE__ */Nh(t,n)),e.min=(t,n)=>e.check(/* @__PURE__ */Nh(t,n)),e.lt=(t,n)=>e.check(/* @__PURE__ */Ch(t,n)),e.lte=(t,n)=>e.check(/* @__PURE__ */Eh(t,n)),e.max=(t,n)=>e.check(/* @__PURE__ */Eh(t,n)),e.int=t=>e.check(Jf(t)),e.safe=t=>e.check(Jf(t)),e.positive=t=>e.check(/* @__PURE__ */zh(0,t)),e.nonnegative=t=>e.check(/* @__PURE__ */Nh(0,t)),e.negative=t=>e.check(/* @__PURE__ */Ch(0,t)),e.nonpositive=t=>e.check(/* @__PURE__ */Eh(0,t)),e.multipleOf=(t,n)=>e.check(/* @__PURE__ */Oh(t,n)),e.step=(t,n)=>e.check(/* @__PURE__ */Oh(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 Hf(e){/* @__PURE__ */
173
- return wh(Wf,e)}const Zf=/* @__PURE__ */eu("ZodNumberFormat",(e,t)=>{dp.init(e,t),Wf.init(e,t)});function Jf(e){/* @__PURE__ */
174
- return xh(Zf,e)}const Kf=/* @__PURE__ */eu("ZodAny",(e,t)=>{pp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}}),Gf=/* @__PURE__ */eu("ZodUnknown",(e,t)=>{hp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Yf(){/* @__PURE__ */
175
- return _h(Gf)}const Qf=/* @__PURE__ */eu("ZodNever",(e,t)=>{fp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),Xf=/* @__PURE__ */eu("ZodArray",(e,t)=>{gp.init(e,t),xf.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=Gh(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */Ih(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */Ih(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */Ah(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */Th(t,n)),e.unwrap=()=>e.element});function em(e,t){/* @__PURE__ */
176
- return Wh(Xf,e,t)}const tm=/* @__PURE__ */eu("ZodObject",(e,t)=>{xp.init(e,t),xf.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]=Gh(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=Gh(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),du(e,"shape",()=>t.shape),e.keyof=()=>im(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Yf()}),e.loose=()=>e.clone({...e._zod.def,catchall:Yf()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */Sh(Qf,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!yu(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=hu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return pu(this,"shape",n),n}});return ku(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!yu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=hu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return pu(this,"shape",n),n}});return ku(e,n)}(e,t),e.merge=t=>function(e,t){const n=hu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return pu(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return ku(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 ku(e,hu(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 pu(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=hu(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 pu(this,"shape",r),r},checks:[]});return ku(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=hu(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 pu(this,"shape",o),o},checks:[]});return ku(t,o)}(sm,e,t[0]),e.required=(...t)=>function(e,t,n){const r=hu(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 pu(this,"shape",o),o}});return ku(t,r)}(fm,e,t[0])}),nm=/* @__PURE__ */eu("ZodUnion",(e,t)=>{_p.init(e,t),xf.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)=>Gh(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}),rm=/* @__PURE__ */eu("ZodIntersection",(e,t)=>{Sp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Gh(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=Gh(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)}),om=/* @__PURE__ */eu("ZodEnum",(e,t)=>{zp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=iu(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 om({...t,checks:[],..._u(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 om({...t,checks:[],..._u(r),entries:o})}});function im(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new om({type:"enum",entries:n,..._u(t)})}const am=/* @__PURE__ */eu("ZodTransform",(e,t)=>{Np.init(e,t),xf.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 nu(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Au(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(Au(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),sm=/* @__PURE__ */eu("ZodOptional",(e,t)=>{Ap.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function lm(e){return new sm({type:"optional",innerType:e})}const cm=/* @__PURE__ */eu("ZodExactOptional",(e,t)=>{Ip.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),um=/* @__PURE__ */eu("ZodNullable",(e,t)=>{Tp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Gh(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 dm(e){return new um({type:"nullable",innerType:e})}const pm=/* @__PURE__ */eu("ZodDefault",(e,t)=>{Mp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Gh(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}),hm=/* @__PURE__ */eu("ZodPrefault",(e,t)=>{Lp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Gh(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}),fm=/* @__PURE__ */eu("ZodNonOptional",(e,t)=>{Dp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Gh(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),mm=/* @__PURE__ */eu("ZodCatch",(e,t)=>{Fp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;Gh(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}),gm=/* @__PURE__ */eu("ZodPipe",(e,t)=>{Rp.init(e,t),xf.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;Gh(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function bm(e,t){return new gm({type:"pipe",in:e,out:t})}const ym=/* @__PURE__ */eu("ZodReadonly",(e,t)=>{Bp.init(e,t),xf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Gh(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),vm=/* @__PURE__ */eu("ZodCustom",(e,t)=>{Vp.init(e,t),xf.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)}),wm=/* @__PURE__ */Object.create(null);wm.open="0",wm.close="1",wm.ping="2",wm.pong="3",wm.message="4",wm.upgrade="5",wm.noop="6";const xm=/* @__PURE__ */Object.create(null);Object.keys(wm).forEach(e=>{xm[wm[e]]=e});const km={type:"error",data:"parser error"},_m="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Sm="function"==typeof ArrayBuffer,Cm=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Em=({type:e,data:t},n,r)=>_m&&t instanceof Blob?n?r(t):zm(t,r):Sm&&(t instanceof ArrayBuffer||Cm(t))?n?r(t):zm(new Blob([t]),r):r(wm[e]+(t||"")),zm=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function Nm(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Om;const Am="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let bb=0;bb<64;bb++)Am["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(bb)]=bb;const Im="function"==typeof ArrayBuffer,Tm=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Pm(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:Mm(e.substring(1),t)}:xm[n]?e.length>1?{type:xm[n],data:e.substring(1)}:{type:xm[n]}:km},Mm=(e,t)=>{if(Im){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=Am[e.charCodeAt(t)],r=Am[e.charCodeAt(t+1)],o=Am[e.charCodeAt(t+2)],i=Am[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 Pm(n,t)}return{base64:!0,data:e}},Pm=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,Lm=String.fromCharCode(30);let Dm;function jm(e){return e.reduce((e,t)=>e+t.length,0)}function Fm(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 Rm(e){if(e)return function(e){for(var t in Rm.prototype)e[t]=Rm.prototype[t];return e}(e)}Rm.prototype.on=Rm.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Rm.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},Rm.prototype.off=Rm.prototype.removeListener=Rm.prototype.removeAllListeners=Rm.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},Rm.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},Rm.prototype.emitReserved=Rm.prototype.emit,Rm.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Rm.prototype.hasListeners=function(e){return!!this.listeners(e).length};const $m="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Bm="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Um(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const Vm=Bm.setTimeout,qm=Bm.clearTimeout;function Wm(e,t){t.useNativeTimers?(e.setTimeoutFn=Vm.bind(Bm),e.clearTimeoutFn=qm.bind(Bm)):(e.setTimeoutFn=Bm.setTimeout.bind(Bm),e.clearTimeoutFn=Bm.clearTimeout.bind(Bm))}function Hm(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 Zm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Jm extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Km extends Rm{constructor(e){super(),this.writable=!1,Wm(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 Jm(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=Tm(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 Gm extends Km{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(Lm),r=[];for(let o=0;o<n.length;o++){const e=Tm(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)=>{Em(e,!1,e=>{r[i]=e,++o===n&&t(r.join(Lm))})})})(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]=Zm()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Ym=!1;try{Ym="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(gb){}const Qm=Ym;function Xm(){}class eg extends Gm{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 tg extends Rm{constructor(e,t,n){super(),this.createRequest=e,Wm(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=Um(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=tg.requestsCount++,tg.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=Xm,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete tg.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 ng(){for(let e in tg.requests)tg.requests.hasOwnProperty(e)&&tg.requests[e].abort()}tg.requestsCount=0,tg.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",ng):"function"==typeof addEventListener&&addEventListener("onpagehide"in Bm?"pagehide":"unload",ng,!1));const rg=function(){const e=og({xdomain:!1});return e&&null!==e.responseType}();function og(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Qm))return new XMLHttpRequest}catch(n){}if(!t)try{return new(Bm[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const ig="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class ag extends Km{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=ig?{}:Um(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(gb){return this.emitReserved("error",gb)}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;Em(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&$m(()=>{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]=Zm()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const sg=Bm.WebSocket||Bm.MozWebSocket,lg={websocket:class extends ag{createSocket(e,t,n){return ig?new sg(e,t,n):t?new sg(e,t):new sg(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Km{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(gb){return this.emitReserved("error",gb)}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){Dm||(Dm=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(jm(n)<1)break;const e=Fm(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(jm(n)<2)break;const e=Fm(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(jm(n)<8)break;const e=Fm(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(km);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(jm(n)<o)break;const e=Fm(n,o);s.enqueue(Tm(i?e:Dm.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(km);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){_m&&e.data instanceof Blob?e.data.arrayBuffer().then(Nm).then(t):Sm&&(e.data instanceof ArrayBuffer||Cm(e.data))?t(Nm(e.data)):Em(e,!1,e=>{Om||(Om=new TextEncoder),t(Om.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&&$m(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends eg{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=rg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new tg(og,this.uri(),e)}}},cg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ug=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function dg(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=cg.exec(e||""),i={},a=14;for(;a--;)i[ug[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 pg="function"==typeof addEventListener&&"function"==typeof removeEventListener,hg=[];pg&&addEventListener("offline",()=>{hg.forEach(e=>e())},!1);class fg extends Rm{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=dg(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=dg(t.host).host);Wm(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)),pg&&(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"})},hg.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&&fg.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",fg.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+=Hm(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,$m(()=>{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(fg.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(),pg&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=hg.indexOf(this._offlineEventListener);-1!==e&&hg.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}fg.protocol=4;class mg extends fg{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;fg.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;fg.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 gg=class extends mg{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=>lg[e]).filter(e=>!!e)),super(e,n)}};const bg="function"==typeof ArrayBuffer,yg=Object.prototype.toString,vg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===yg.call(Blob),wg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===yg.call(File);function xg(e){return bg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||vg&&e instanceof Blob||wg&&e instanceof File}function kg(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(kg(e[t]))return!0;return!1}if(xg(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return kg(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&kg(e[n]))return!0;return!1}function _g(e){const t=[],n=e.data,r=e;return r.data=Sg(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Sg(e,t){if(!e)return e;if(xg(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]=Sg(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]=Sg(e[r],t));return n}return e}function Cg(e,t){return e.data=Eg(e.data,t),delete e.attachments,e}function Eg(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]=Eg(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Eg(e[n],t));return e}const zg=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Ng,Og;(Og=Ng||(Ng={}))[Og.CONNECT=0]="CONNECT",Og[Og.DISCONNECT=1]="DISCONNECT",Og[Og.EVENT=2]="EVENT",Og[Og.ACK=3]="ACK",Og[Og.CONNECT_ERROR=4]="CONNECT_ERROR",Og[Og.BINARY_EVENT=5]="BINARY_EVENT",Og[Og.BINARY_ACK=6]="BINARY_ACK";class Ag extends Rm{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===Ng.BINARY_EVENT;n||t.type===Ng.BINARY_ACK?(t.type=n?Ng.EVENT:Ng.ACK,this.reconstructor=new Ig(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!xg(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===Ng[n.type])throw new Error("unknown packet type "+n.type);if(n.type===Ng.BINARY_EVENT||n.type===Ng.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(!Tg(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(!Ag.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 Ng.CONNECT:return Mg(t);case Ng.DISCONNECT:return void 0===t;case Ng.CONNECT_ERROR:return"string"==typeof t||Mg(t);case Ng.EVENT:case Ng.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===zg.indexOf(t[0]));case Ng.ACK:case Ng.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ig{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=Cg(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Tg=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function Mg(e){return"[object Object]"===Object.prototype.toString.call(e)}const Pg=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:Ag,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Ng.EVENT&&e.type!==Ng.ACK||!kg(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Ng.EVENT?Ng.BINARY_EVENT:Ng.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Ng.BINARY_EVENT&&e.type!==Ng.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=_g(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return Ng}},Symbol.toStringTag,{value:"Module"}));function Lg(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const Dg=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class jg extends Rm{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=[Lg(e,"open",this.onopen.bind(this)),Lg(e,"packet",this.onpacket.bind(this)),Lg(e,"error",this.onerror.bind(this)),Lg(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(Dg.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:Ng.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:Ng.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 Ng.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 Ng.EVENT:case Ng.BINARY_EVENT:this.onevent(e);break;case Ng.ACK:case Ng.BINARY_ACK:this.onack(e);break;case Ng.DISCONNECT:this.ondisconnect();break;case Ng.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:Ng.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:Ng.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 Fg(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}Fg.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)},Fg.prototype.reset=function(){this.attempts=0},Fg.prototype.setMin=function(e){this.ms=e},Fg.prototype.setMax=function(e){this.max=e},Fg.prototype.setJitter=function(e){this.jitter=e};class Rg extends Rm{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,Wm(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 Fg({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||Pg;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 gg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=Lg(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=Lg(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(Lg(e,"ping",this.onping.bind(this)),Lg(e,"data",this.ondata.bind(this)),Lg(e,"error",this.onerror.bind(this)),Lg(e,"close",this.onclose.bind(this)),Lg(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){$m(()=>{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 jg(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 $g={};function Bg(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=dg(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=$g[o]&&i in $g[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new Rg(r,t):($g[o]||($g[o]=new Rg(r,t)),s=$g[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(Bg,{Manager:Rg,Socket:jg,io:Bg,connect:Bg});const Ug="chat_device_id";function Vg(){return"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 qg=function(){const e={type:"object",shape:{id:Sf().optional(),type:im(["text","image","audio","location","system"]).default("text"),content:Sf().optional(),imageUrl:Sf().url().optional(),audioUrl:Sf().optional(),latitude:Hf().optional(),longitude:Hf().optional(),timestamp:Sf().optional(),sender:im(["bot","user","system"]).optional(),emotion:/* @__PURE__ */kh(Kf).optional(),sources:em(Sf()).optional()}??{},..._u(void 0)};return new tm(e)}();class Wg{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),Dt("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?Ft():(this.isDisabled=!0,this.queue=[],Ft(t.status))}catch(t){this.isDisabled=!0,this.queue=[],Ft()}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}let Hg=null,Zg=null;function Jg(e){Hg=e}function Kg(e){Zg=e}const Gg=r(null);function Yg({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(e=>{Hg?(Hg(e),Ft(0)):Dt("sendMessage called but no handler registered")},[]),m=s(()=>{Zg?(Zg(),Ft()):Dt("clearMessages called but no handler registered")},[]),g={isOpen:a,open:d,close:p,toggle:h,sendMessage:f,clearMessages:m,unreadCount:c},v=s((e,t)=>{"message:received"!==e||a||u(e=>e+1),o.onEvent?.(e,t)},[a,o]);/* @__PURE__ */
177
- return y(Gg.Provider,{value:g,children:[e,
178
- /* @__PURE__ */b(ob,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:v})]})}function Qg(){const e=o(Gg);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const Xg=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function eb(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,onThemeUpdate:v}=e,[w,x]=i(0),k=f(0),{t:_}=D(),S=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Wg(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),C=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||$t,h=l||Bt;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 Dt("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),Rt("Notification permission:",e),"granted"===e}catch(e){return jt("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){jt("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=>{Ft(0)})}catch(n){jt("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}),E=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:z,actions:N}=function(e,t="default"){const[r,o]=g(Xc,Qc),[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 Yc.has(n)||Yc.set(n,new Gc(e,t)),Yc.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){Dt("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){jt("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){jt("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){jt("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:[]})},[]);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:_}}}(t,o),O=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),A=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(Ug);if(e)return e;const t=Vg();return localStorage.setItem(Ug,t),t}catch{return Dt("localStorage not available, using session-only device ID"),Vg()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=qg.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=Bg(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:l?.token,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});e.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),e.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),e.on("connect_error",e=>{h(!1),c.current.onError(`Error de conexión: ${e.message}`)}),e.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),e.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){jt("ChatSocket Error processing bot_message:",t)}}),e.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 Ft(),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){Ft()}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),e.on("bot_typing",e=>c.current.onTyping(e));const o=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};e.on("onboarding:command",e=>o(e)),e.on("form:command",e=>o(e)),e.on("request_form_state",()=>{o({type:"botuyo-request-form-state"})}),e.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),e.on("custom_event",e=>{if("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)}}});const i=t=>{const{type:n}=t.data||{};"botuyo-onboarding-state"!==n&&"botuyo-form-state"!==n||e.emit("form_state",t.data)};window.addEventListener("message",i),d.current=e,e.__formCleanup=()=>window.removeEventListener("message",i)},[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}),jt("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]),N=u(()=>tc(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:N,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>O?{...l||{},seo:{...O||{}}}:l,[l,O]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=k.current>0?t-k.current:void 0;k.current=t,N.addMessage(e),S.trackMessageReceived(e.type,n),z.isOpen||"bot"!==e.sender||(x(e=>e+1),C.notifyWithSound(e))},[N,z.isOpen,S,C]),onConnected:s((e,t)=>{N.setConnected(!0),N.setSessionId(e),S.trackConnectionStatus(!0),t&&v&&v(t),t&&b&&b("backend_config",t)},[N,b,v,S]),onDisconnected:s(()=>{N.setConnected(!1),S.trackConnectionStatus(!1)},[N,S]),onTyping:s(e=>N.setTyping(e),[N]),onError:s(e=>{N.setError(e),S.trackError(e)},[N,S]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:v,onHistoryLoaded:s(e=>{const t=new Set(z.messages.map(e=>e.id)),n=e.filter(e=>!t.has(e.id));n.length>0&&(0===z.messages.length?N.setMessages(e):n.forEach(e=>N.addMessage(e)))},[z.messages,N])}),I=s(()=>{Ft(0,z.isOpen),z.isOpen?(N.closeWindow(),S.trackClose(),y?.(!1),Ft()):(N.openWindow(),x(0),S.trackOpen(),y?.(!0),Ft())},[z.isOpen,N,y,S]),T=s(e=>{if(!E.isAllowed()){const e=E.getTimeUntilReset(),t=Math.ceil(e/1e3);return void N.setError(_("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};N.addMessage(t),S.trackMessageSent("text"),A.sendMessage(e,"text")},[N,A,E,S,_]),M=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}`},N.addMessage(n);const r=await Xg(e);A.sendMessage(r,t)},[N,A]),P=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"};N.addMessage(t),A.sendMessage(JSON.stringify(e),"location")},[N,A]);a(()=>{const e=()=>{z.isOpen||N.openWindow()},t=()=>{z.isOpen&&N.closeWindow()},n=()=>{z.isOpen?N.closeWindow():N.openWindow()},r=e=>{e.detail?.message&&T(e.detail.message)};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),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:send-message",r)}},[z.isOpen,N,T]),a(()=>(Jg(T),()=>Jg(null)),[T]);const L=s(()=>{N.clearMessages(),Rt("Chat history cleared")},[N]);a(()=>(Kg(L),()=>Kg(null)),[L]);const j=u(()=>{if(z.isTyping)return"thinking";const e=[...z.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[z.isTyping,z.messages]);return{state:z,actions:N,unreadCount:w,currentBotEmotion:j,isConnected:A.isConnected,getSocket:A.getSocket,handleToggle:I,handleSendText:T,handleSendAttachment:M,handleSendLocation:P}}function tb({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),Ft(),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function nb(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,initialOpen:w=!1,hideLauncher:x=!1}=e,k=f(null),_=nc(),S=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}(k),[C,E]=i(),{mergedTheme:z,mergedStyles:N,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={...zt,...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:{...Cc,...e?.bubbleStyles?.radius},bot:{...Ec,...e?.bubbleStyles?.bot},user:{...zc,...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,C);a(()=>{z.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.')},[z.isHidden]);const{state:A,actions:I,unreadCount:T,currentBotEmotion:M,isConnected:P,handleToggle:L,handleSendText:D,handleSendAttachment:j,handleSendLocation:F,getSocket:R}=eb({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,onThemeUpdate:E}),$=f(!1);a(()=>{w&&C&&!$.current&&($.current=!0,A.isOpen||I.openWindow())},[w,C,A.isOpen,I]);const B=s(e=>{I.addMessage({id:`voice-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"text",sender:e.sender,timestamp:e.timestamp||/* @__PURE__ */new Date,content:e.content})},[I]),U=u(()=>{const e={...d||{}},t=C;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,C]),V=s(()=>{I.closeWindow()},[I]),q=s(e=>{e.stopPropagation()},[]),W=O(A.isOpen,_,c?.position),H=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(!z.cssVariables)return e;let t={...z.cssVariables};if(S){const e=C?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Nt,...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},[z.cssVariables,S,C,c?.darkCssVariables]);return z.isHidden?null:C?/* @__PURE__ */y("div",{ref:k,id:"botuyo-chat-widget-root",className:Et("botuyo-chat-widget flex flex-col",!_&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...W,...H,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:[
179
- /* @__PURE__ */b("div",{className:Et("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",_?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",A.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:A.isOpen?"auto":"none"},onMouseDown:q,onTouchStart:q,children:/* @__PURE__ */b(Sc,{children:/* @__PURE__ */b(_c,{isOpen:A.isOpen,isConnected:P,isTyping:A.isTyping,messages:A.messages,onClose:V,onSendMessage:D,onSendAttachment:j,onSendLocation:F,botName:z.botName,logoUrl:z.logoUrl,welcomeMessage:z.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||C?.inputPlaceholder,position:c?.position,bubbleStyles:N,avatars:c?.avatars||C?.avatars||C?.avatarAnimations||{},mediaConfig:U,theme:z,avatar3dUrl:c?.avatar3dUrl||C?.avatar3dUrl,getSocket:R,onAddVoiceMessage:B,suggestedQuestions:C?.suggestedQuestions})})}),!x&&/* @__PURE__ */b("div",{className:Et(A.isOpen?"hidden":"block",!_&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:q,onTouchStart:q,children:/* @__PURE__ */b(Vt,{isOpen:A.isOpen,onClick:L,unreadCount:T,position:c?.position||"bottom-right",primaryColor:Ot(z),logoUrl:z.logoUrl,starterPrompt:c?.starterPrompt||C?.starterPrompt,avatars:c?.avatars||C?.avatars||C?.avatarAnimations||{},emotion:M,styles:N,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??C?.avatarScale,showPromptAvatar:c?.showPromptAvatar??C?.showPromptAvatar})})]}):null}function rb(e){/* @__PURE__ */
180
- return b(Pt,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(nb,{...e})})}function ob(e){/* @__PURE__ */
181
- return b(M,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b(tb,{children:/* @__PURE__ */b(rb,{...e})})})}const ib=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:ob,ChatWidgetInner:nb,ChatWidgetWithProviders:rb},Symbol.toStringTag,{value:"Module"}));function ab({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__ */
182
- return b("div",{style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:/* @__PURE__ */b(M,{defaultLocale:r,children:/* @__PURE__ */b(rb,{...i})})},n)}function sb({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 lb({position:e,target:t}){const{camera:n}=_();return a(()=>{e&&t&&(n.position.set(...e),n.lookAt(...t))},[n,e,t]),null}function cb({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:[
183
- /* @__PURE__ */b(lb,{position:n,target:r}),
161
+ /* @__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 Ac={bubble:"rounded-2xl",image:"rounded-xl",button:"rounded-xl",card:"rounded-2xl"},Ic={bg:"bg-muted/50 dark:bg-muted/20",text:"text-foreground",border:"border-border/50"},Tc={text:"text-primary-foreground"};const Mc=(e,t)=>t.some(t=>e instanceof t);let Pc,Lc;const Dc=/* @__PURE__ */new WeakMap,jc=/* @__PURE__ */new WeakMap,Fc=/* @__PURE__ */new WeakMap;let Rc={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Dc.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Uc(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function $c(e){Rc=e(Rc)}function Bc(e){return"function"==typeof e?(t=e,(Lc||(Lc=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(Vc(this),e),Uc(this.request)}:function(...e){return Uc(t.apply(Vc(this),e))}):(e instanceof IDBTransaction&&function(e){if(Dc.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)});Dc.set(e,t)}(e),Mc(e,Pc||(Pc=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Rc):e);var t}function Uc(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(Uc(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)});return Fc.set(t,e),t}(e);if(jc.has(e))return jc.get(e);const t=Bc(e);return t!==e&&(jc.set(e,t),Fc.set(t,e)),t}const Vc=e=>Fc.get(e),qc=["get","getKey","getAll","getAllKeys","count"],Wc=["put","add","delete","clear"],Hc=/* @__PURE__ */new Map;function Zc(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Hc.get(t))return Hc.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=Wc.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!qc.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 Hc.set(t,i),i}$c(e=>({...e,get:(t,n,r)=>Zc(t,n)||e.get(t,n,r),has:(t,n)=>!!Zc(t,n)||e.has(t,n)}));const Jc=["continue","continuePrimaryKey","advance"],Kc={},Gc=/* @__PURE__ */new WeakMap,Yc=/* @__PURE__ */new WeakMap,Qc={get(e,t){if(!Jc.includes(t))return e[t];let n=Kc[t];return n||(n=Kc[t]=function(...e){Gc.set(this,Yc.get(this)[t](...e))}),n}};async function*Xc(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,Qc);for(Yc.set(n,t),Fc.set(n,Vc(t));t;)yield n,t=await(Gc.get(n)||t.continue()),Gc.delete(n)}function eu(e,t){return t===Symbol.asyncIterator&&Mc(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&Mc(e,[IDBIndex,IDBObjectStore])}$c(e=>({...e,get:(t,n,r)=>eu(t,n)?Xc:e.get(t,n,r),has:(t,n)=>eu(t,n)||e.has(t,n)}));class tu{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=Uc(a);return r&&a.addEventListener("upgradeneeded",e=>{r(Uc(a.result),e.oldVersion,e.newVersion,Uc(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")}}),Rt("IndexedDB initialized")}catch(e){throw jt("Failed to initialize IndexedDB:",e),e}}async saveMessage(e){this.db||await this.init();try{await this.db.put("messages",e)}catch(t){jt("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){jt("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 jt("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 jt("Failed to get message:",t)}}async deleteMessage(e){this.db||await this.init();try{await this.db.delete("messages",e)}catch(t){jt("Failed to delete message:",t)}}async clearMessages(){this.db||await this.init();try{await this.db.clear("messages"),Rt("Messages cleared from IndexedDB")}catch(e){jt("Failed to clear messages:",e)}}async setMetadata(e){this.db||await this.init();try{await this.db.put("metadata",e,"chat-metadata")}catch(t){jt("Failed to set metadata:",t)}}async getMetadata(){this.db||await this.init();try{return await this.db.get("metadata","chat-metadata")}catch(e){return jt("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")]),Rt("All data cleared from IndexedDB")}catch(e){jt("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),Rt(`Migrated ${e.length} messages from localStorage`)}o.sessionId&&await this.setMetadata({sessionId:o.sessionId}),localStorage.removeItem(n),Rt("Migration from localStorage completed")}catch(n){jt("Failed to migrate from localStorage:",n)}}}const nu=/* @__PURE__ */new Map,ru={isOpen:!1,isConnected:!1,isTyping:!1,messages:[],error:null,sessionId:null};function ou(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"CLEAR_CHAT":return{...ru,isOpen:e.isOpen};case"RESTORE_SESSION":return{...e,...t.payload,isConnected:!1,isTyping:!1,error:null};default:return e}}function iu(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 au extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class su extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const lu={};function cu(e){return lu}function uu(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 du(e,t){return"bigint"==typeof t?t.toString():t}function pu(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function hu(e){return null==e}function fu(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 gu(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 bu(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function yu(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function vu(e){return JSON.stringify(e)}const wu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function xu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const ku=pu(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function _u(e){if(!1===xu(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!==xu(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Su(e){return _u(e)?{...e}:Array.isArray(e)?[...e]:e}const Cu=/* @__PURE__ */new Set(["string","number","symbol"]);function Eu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zu(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Nu(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 Ou={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 Au(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 Iu(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Tu(e){return"string"==typeof e?e:e?.message}function Mu(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=Tu(e.inst?._zod.def?.error?.(e))??Tu(t?.error?.(e))??Tu(n.customError?.(e))??Tu(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Pu(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Lu(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Du=(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,du,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ju=iu("$ZodError",Du),Fu=iu("$ZodError",Du,{Parent:Error}),Ru=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 au;if(a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Mu(e,i,cu())));throw wu(t,o?.callee),t}return a.value},$u=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=>Mu(e,i,cu())));throw wu(t,o?.callee),t}return a.value},Bu=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 au;return i.issues.length?{success:!1,error:new(e??ju)(i.issues.map(e=>Mu(e,o,cu())))}:{success:!0,data:i.value}},Uu=/* @__PURE__ */Bu(Fu),Vu=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=>Mu(e,o,cu())))}:{success:!0,data:i.value}},qu=/* @__PURE__ */Vu(Fu),Wu=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ru(e)(t,n,o)},Hu=e=>(t,n,r)=>Ru(e)(t,n,r),Zu=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return $u(e)(t,n,o)},Ju=e=>async(t,n,r)=>$u(e)(t,n,r),Ku=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Bu(e)(t,n,o)},Gu=e=>(t,n,r)=>Bu(e)(t,n,r),Yu=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Vu(e)(t,n,o)},Qu=e=>async(t,n,r)=>Vu(e)(t,n,r),Xu=/^[cC][^\s-]{8,}$/,ed=/^[0-9a-z]+$/,td=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nd=/^[0-9a-vA-V]{20}$/,rd=/^[A-Za-z0-9]{27}$/,od=/^[a-zA-Z0-9_-]{21}$/,id=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ad=/^([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})$/,sd=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)$/,ld=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,cd=/^(?:(?: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])$/,ud=/^(([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}|:))$/,dd=/^((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])$/,pd=/^(([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])$/,hd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,fd=/^[A-Za-z0-9_-]*$/,md=/^\+[1-9]\d{6,14}$/,gd="(?:(?:\\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])))",bd=/* @__PURE__ */new RegExp(`^${gd}$`);function yd(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 vd=/^-?\d+$/,wd=/^-?\d+(?:\.\d+)?$/,xd=/^[^A-Z]*$/,kd=/^[^a-z]*$/,_d=/* @__PURE__ */iu("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Sd={number:"number",bigint:"bigint",object:"date"},Cd=/* @__PURE__ */iu("$ZodCheckLessThan",(e,t)=>{_d.init(e,t);const n=Sd[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})}}),Ed=/* @__PURE__ */iu("$ZodCheckGreaterThan",(e,t)=>{_d.init(e,t);const n=Sd[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__ */iu("$ZodCheckMultipleOf",(e,t)=>{_d.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})}}),Nd=/* @__PURE__ */iu("$ZodCheckNumberFormat",(e,t)=>{_d.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Ou[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=vd)}),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})}}),Od=/* @__PURE__ */iu("$ZodCheckMaxLength",(e,t)=>{var n;_d.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!hu(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=Pu(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ad=/* @__PURE__ */iu("$ZodCheckMinLength",(e,t)=>{var n;_d.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!hu(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=Pu(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Id=/* @__PURE__ */iu("$ZodCheckLengthEquals",(e,t)=>{var n;_d.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!hu(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=Pu(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})}}),Td=/* @__PURE__ */iu("$ZodCheckStringFormat",(e,t)=>{var n,r;_d.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=()=>{})}),Md=/* @__PURE__ */iu("$ZodCheckRegex",(e,t)=>{Td.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})}}),Pd=/* @__PURE__ */iu("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=xd),Td.init(e,t)}),Ld=/* @__PURE__ */iu("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=kd),Td.init(e,t)}),Dd=/* @__PURE__ */iu("$ZodCheckIncludes",(e,t)=>{_d.init(e,t);const n=Eu(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})}}),jd=/* @__PURE__ */iu("$ZodCheckStartsWith",(e,t)=>{_d.init(e,t);const n=new RegExp(`^${Eu(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})}}),Fd=/* @__PURE__ */iu("$ZodCheckEndsWith",(e,t)=>{_d.init(e,t);const n=new RegExp(`.*${Eu(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})}}),Rd=/* @__PURE__ */iu("$ZodCheckOverwrite",(e,t)=>{_d.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class $d{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 Bd={major:4,minor:3,patch:6},Ud=/* @__PURE__ */iu("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Bd;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=Au(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 au;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(o||(o=Au(e,t)))});else{if(e.issues.length===t)continue;o||(o=Au(e,t))}}return r?r.then(()=>e):e},n=(n,o,i)=>{if(Au(n))return n.aborted=!0,n;const a=t(o,r,i);if(a instanceof Promise){if(!1===i.async)throw new au;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 au;return a.then(e=>t(e,r,i))}return t(a,r,i)}}gu(e,"~standard",()=>({validate:t=>{try{const n=Uu(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return qu(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Vd=/* @__PURE__ */iu("$ZodString",(e,t)=>{var n;Ud.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}}),qd=/* @__PURE__ */iu("$ZodStringFormat",(e,t)=>{Td.init(e,t),Vd.init(e,t)}),Wd=/* @__PURE__ */iu("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ad),qd.init(e,t)}),Hd=/* @__PURE__ */iu("$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=sd(e))}else t.pattern??(t.pattern=sd());qd.init(e,t)}),Zd=/* @__PURE__ */iu("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ld),qd.init(e,t)}),Jd=/* @__PURE__ */iu("$ZodURL",(e,t)=>{qd.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})}}}),Kd=/* @__PURE__ */iu("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qd.init(e,t)}),Gd=/* @__PURE__ */iu("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=od),qd.init(e,t)}),Yd=/* @__PURE__ */iu("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Xu),qd.init(e,t)}),Qd=/* @__PURE__ */iu("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ed),qd.init(e,t)}),Xd=/* @__PURE__ */iu("$ZodULID",(e,t)=>{t.pattern??(t.pattern=td),qd.init(e,t)}),ep=/* @__PURE__ */iu("$ZodXID",(e,t)=>{t.pattern??(t.pattern=nd),qd.init(e,t)}),tp=/* @__PURE__ */iu("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=rd),qd.init(e,t)}),np=/* @__PURE__ */iu("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=yd({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(`^${gd}T(?:${r})$`)}(t)),qd.init(e,t)}),rp=/* @__PURE__ */iu("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=bd),qd.init(e,t)}),op=/* @__PURE__ */iu("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${yd(t)}$`)),qd.init(e,t)}),ip=/* @__PURE__ */iu("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=id),qd.init(e,t)}),ap=/* @__PURE__ */iu("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=cd),qd.init(e,t),e._zod.bag.format="ipv4"}),sp=/* @__PURE__ */iu("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ud),qd.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})}}}),lp=/* @__PURE__ */iu("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=dd),qd.init(e,t)}),cp=/* @__PURE__ */iu("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=pd),qd.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 up(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const dp=/* @__PURE__ */iu("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=hd),qd.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{up(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),pp=/* @__PURE__ */iu("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=fd),qd.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!fd.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return up(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})}}),hp=/* @__PURE__ */iu("$ZodE164",(e,t)=>{t.pattern??(t.pattern=md),qd.init(e,t)}),fp=/* @__PURE__ */iu("$ZodJWT",(e,t)=>{qd.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})}}),mp=/* @__PURE__ */iu("$ZodNumber",(e,t)=>{Ud.init(e,t),e._zod.pattern=e._zod.bag.pattern??wd,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}}),gp=/* @__PURE__ */iu("$ZodNumberFormat",(e,t)=>{Nd.init(e,t),mp.init(e,t)}),bp=/* @__PURE__ */iu("$ZodAny",(e,t)=>{Ud.init(e,t),e._zod.parse=e=>e}),yp=/* @__PURE__ */iu("$ZodUnknown",(e,t)=>{Ud.init(e,t),e._zod.parse=e=>e}),vp=/* @__PURE__ */iu("$ZodNever",(e,t)=>{Ud.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function wp(e,t,n){e.issues.length&&t.issues.push(...Iu(n,e.issues)),t.value[n]=e.value}const xp=/* @__PURE__ */iu("$ZodArray",(e,t)=>{Ud.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=>wp(t,n,e))):wp(s,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function kp(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...Iu(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function _p(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 Sp(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=>kp(e,n,d,t,u))):kp(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 Cp=/* @__PURE__ */iu("$ZodObject",(e,t)=>{Ud.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=pu(()=>_p(t));gu(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=xu,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=>kp(n,t,e,s,o))):kp(i,t,e,s,o)}return i?Sp(l,s,t,n,r.value,e):l.length?Promise.all(l).then(()=>t):t}}),Ep=/* @__PURE__ */iu("$ZodObjectJIT",(e,t)=>{Cp.init(e,t);const n=e._zod.parse,r=pu(()=>_p(t));let o;const i=xu,a=!lu.jitless,s=a&&ku.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 $d(["shape","payload","ctx"]),n=r.value,o=e=>{const t=vu(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=vu(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?Sp([],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=>!Au(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=>Mu(e,r,cu())))}),t)}const Np=/* @__PURE__ */iu("$ZodUnion",(e,t)=>{Ud.init(e,t),gu(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),gu(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),gu(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),gu(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=>fu(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)}}),Op=/* @__PURE__ */iu("$ZodIntersection",(e,t)=>{Ud.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])=>Ip(e,t,n)):Ip(e,o,i)}});function Ap(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(_u(e)&&_u(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=Ap(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=Ap(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 Ip(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}),Au(e))return e;const a=Ap(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 Tp=/* @__PURE__ */iu("$ZodEnum",(e,t)=>{Ud.init(e,t);const n=uu(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>Cu.has(typeof e)).map(e=>"string"==typeof e?Eu(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}}),Mp=/* @__PURE__ */iu("$ZodTransform",(e,t)=>{Ud.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new su(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 au;return n.value=o,n}});function Pp(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Lp=/* @__PURE__ */iu("$ZodOptional",(e,t)=>{Ud.init(e,t),e._zod.optin="optional",e._zod.optout="optional",gu(e._zod,"values",()=>t.innerType._zod.values?/* @__PURE__ */new Set([...t.innerType._zod.values,void 0]):void 0),gu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${fu(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=>Pp(t,e.value)):Pp(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Dp=/* @__PURE__ */iu("$ZodExactOptional",(e,t)=>{Lp.init(e,t),gu(e._zod,"values",()=>t.innerType._zod.values),gu(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),jp=/* @__PURE__ */iu("$ZodNullable",(e,t)=>{Ud.init(e,t),gu(e._zod,"optin",()=>t.innerType._zod.optin),gu(e._zod,"optout",()=>t.innerType._zod.optout),gu(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${fu(e.source)}|null)$`):void 0}),gu(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)}),Fp=/* @__PURE__ */iu("$ZodDefault",(e,t)=>{Ud.init(e,t),e._zod.optin="optional",gu(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=>Rp(e,t)):Rp(r,t)}});function Rp(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const $p=/* @__PURE__ */iu("$ZodPrefault",(e,t)=>{Ud.init(e,t),e._zod.optin="optional",gu(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))}),Bp=/* @__PURE__ */iu("$ZodNonOptional",(e,t)=>{Ud.init(e,t),gu(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=>Up(t,e)):Up(o,e)}});function Up(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 Vp=/* @__PURE__ */iu("$ZodCatch",(e,t)=>{Ud.init(e,t),gu(e._zod,"optin",()=>t.innerType._zod.optin),gu(e._zod,"optout",()=>t.innerType._zod.optout),gu(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=>Mu(e,n,cu()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Mu(e,n,cu()))},input:e.value}),e.issues=[]),e)}}),qp=/* @__PURE__ */iu("$ZodPipe",(e,t)=>{Ud.init(e,t),gu(e._zod,"values",()=>t.in._zod.values),gu(e._zod,"optin",()=>t.in._zod.optin),gu(e._zod,"optout",()=>t.out._zod.optout),gu(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=>Wp(e,t.in,n)):Wp(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Wp(e,t.out,n)):Wp(r,t.out,n)}});function Wp(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Hp=/* @__PURE__ */iu("$ZodReadonly",(e,t)=>{Ud.init(e,t),gu(e._zod,"propValues",()=>t.innerType._zod.propValues),gu(e._zod,"values",()=>t.innerType._zod.values),gu(e._zod,"optin",()=>t.innerType?._zod?.optin),gu(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(Zp):Zp(r)}});function Zp(e){return e.value=Object.freeze(e.value),e}const Jp=/* @__PURE__ */iu("$ZodCustom",(e,t)=>{_d.init(e,t),Ud.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=>Kp(t,n,r,e));Kp(o,n,r,e)}});function Kp(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(Lu(e))}}var Gp;(Gp=globalThis).__zod_globalRegistry??(Gp.__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 Yp=globalThis.__zod_globalRegistry;function Qp(e,t){return new e({type:"string",...Nu(t)})}function Xp(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Nu(t)})}function eh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Nu(t)})}function th(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Nu(t)})}function nh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Nu(t)})}function rh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Nu(t)})}function oh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Nu(t)})}function ih(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Nu(t)})}function ah(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Nu(t)})}function sh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Nu(t)})}function lh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Nu(t)})}function ch(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Nu(t)})}function uh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Nu(t)})}function dh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Nu(t)})}function ph(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Nu(t)})}function hh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Nu(t)})}function fh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Nu(t)})}function mh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Nu(t)})}function gh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Nu(t)})}function bh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Nu(t)})}function yh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Nu(t)})}function vh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Nu(t)})}function wh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Nu(t)})}function xh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Nu(t)})}function kh(e,t){return new e({type:"string",format:"date",check:"string_format",...Nu(t)})}function _h(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Nu(t)})}function Sh(e,t){return new e({type:"string",format:"duration",check:"string_format",...Nu(t)})}function Ch(e,t){return new e({type:"number",checks:[],...Nu(t)})}function Eh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Nu(t)})}function zh(e){return new e({type:"any"})}function Nh(e){return new e({type:"unknown"})}function Oh(e,t){return new e({type:"never",...Nu(t)})}function Ah(e,t){return new Cd({check:"less_than",...Nu(t),value:e,inclusive:!1})}function Ih(e,t){return new Cd({check:"less_than",...Nu(t),value:e,inclusive:!0})}function Th(e,t){return new Ed({check:"greater_than",...Nu(t),value:e,inclusive:!1})}function Mh(e,t){return new Ed({check:"greater_than",...Nu(t),value:e,inclusive:!0})}function Ph(e,t){return new zd({check:"multiple_of",...Nu(t),value:e})}function Lh(e,t){return new Od({check:"max_length",...Nu(t),maximum:e})}function Dh(e,t){return new Ad({check:"min_length",...Nu(t),minimum:e})}function jh(e,t){return new Id({check:"length_equals",...Nu(t),length:e})}function Fh(e,t){return new Md({check:"string_format",format:"regex",...Nu(t),pattern:e})}function Rh(e){return new Pd({check:"string_format",format:"lowercase",...Nu(e)})}function $h(e){return new Ld({check:"string_format",format:"uppercase",...Nu(e)})}function Bh(e,t){return new Dd({check:"string_format",format:"includes",...Nu(t),includes:e})}function Uh(e,t){return new jd({check:"string_format",format:"starts_with",...Nu(t),prefix:e})}function Vh(e,t){return new Fd({check:"string_format",format:"ends_with",...Nu(t),suffix:e})}function qh(e){return new Rd({check:"overwrite",tx:e})}function Wh(e){/* @__PURE__ */
162
+ return qh(t=>t.normalize(e))}function Hh(){/* @__PURE__ */
163
+ return qh(e=>e.trim())}function Zh(){/* @__PURE__ */
164
+ return qh(e=>e.toLowerCase())}function Jh(){/* @__PURE__ */
165
+ return qh(e=>e.toUpperCase())}function Kh(){/* @__PURE__ */
166
+ return qh(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e))}function Gh(e,t,n){return new e({type:"array",element:t,...Nu(n)})}function Yh(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Nu(n)})}function Qh(e){const t=/* @__PURE__ */Xh(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Lu(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(Lu(r))}},e(n.value,n)));return t}function Xh(e,t){const n=new _d({check:"custom",...Nu(t)});return n._zod.check=e,n}function ef(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??Yp,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 tf(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),tf(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&&of(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 nf(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 rf(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:af(t,"input",e.processors),output:af(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(a){throw new Error("Error converting schema to JSON.")}}function of(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 of(r.element,n);if("set"===r.type)return of(r.valueType,n);if("lazy"===r.type)return of(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 of(r.innerType,n);if("intersection"===r.type)return of(r.left,n)||of(r.right,n);if("record"===r.type||"map"===r.type)return of(r.keyType,n)||of(r.valueType,n);if("pipe"===r.type)return of(r.in,n)||of(r.out,n);if("object"===r.type){for(const e in r.shape)if(of(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(of(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(of(e,n))return!0;return!(!r.rest||!of(r.rest,n))}return!1}const af=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},a=ef({...o??{},target:i,io:t,processors:n});return tf(e,a),nf(a,e),rf(a,e)},sf={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},lf=(e,t,n,r)=>{const o=e._zod.def;tf(o.innerType,t,r),t.seen.get(e).ref=o.innerType},cf=/* @__PURE__ */iu("ZodISODateTime",(e,t)=>{np.init(e,t),Af.init(e,t)}),uf=/* @__PURE__ */iu("ZodISODate",(e,t)=>{rp.init(e,t),Af.init(e,t)}),df=/* @__PURE__ */iu("ZodISOTime",(e,t)=>{op.init(e,t),Af.init(e,t)}),pf=/* @__PURE__ */iu("ZodISODuration",(e,t)=>{ip.init(e,t),Af.init(e,t)}),hf=iu("ZodError",(e,t)=>{ju.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,du,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,du,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),ff=/* @__PURE__ */Ru(hf),mf=/* @__PURE__ */$u(hf),gf=/* @__PURE__ */Bu(hf),bf=/* @__PURE__ */Vu(hf),yf=/* @__PURE__ */Wu(hf),vf=/* @__PURE__ */Hu(hf),wf=/* @__PURE__ */Zu(hf),xf=/* @__PURE__ */Ju(hf),kf=/* @__PURE__ */Ku(hf),_f=/* @__PURE__ */Gu(hf),Sf=/* @__PURE__ */Yu(hf),Cf=/* @__PURE__ */Qu(hf),Ef=/* @__PURE__ */iu("ZodType",(e,t)=>(Ud.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:af(e,"input"),output:af(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=ef({...n,processors:t});return tf(e,r),nf(r,e),rf(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(yu(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)=>zu(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>ff(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>gf(e,t,n),e.parseAsync=async(t,n)=>mf(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>bf(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>yf(e,t,n),e.decode=(t,n)=>vf(e,t,n),e.encodeAsync=async(t,n)=>wf(e,t,n),e.decodeAsync=async(t,n)=>xf(e,t,n),e.safeEncode=(t,n)=>kf(e,t,n),e.safeDecode=(t,n)=>_f(e,t,n),e.safeEncodeAsync=async(t,n)=>Sf(e,t,n),e.safeDecodeAsync=async(t,n)=>Cf(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){/* @__PURE__ */
167
+ return Yh(Sm,e,t)}(t,n)),e.superRefine=t=>e.check(/* @__PURE__ */Qh(t)),e.overwrite=t=>e.check(/* @__PURE__ */qh(t)),e.optional=()=>hm(e),e.exactOptional=()=>new fm({type:"optional",innerType:e}),e.nullable=()=>gm(e),e.nullish=()=>hm(gm(e)),e.nonoptional=t=>function(e,t){return new vm({type:"nonoptional",innerType:e,...Nu(t)})}(e,t),e.array=()=>im(e),e.or=t=>new sm({type:"union",options:[e,t],...Nu(void 0)}),e.and=t=>new lm({type:"intersection",left:e,right:t}),e.transform=t=>km(e,new dm({type:"transform",transform:t})),e.default=t=>{return n=t,new bm({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():Su(n)}});var n},e.prefault=t=>{return n=t,new ym({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():Su(n)}});var n},e.catch=t=>{return new wm({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>km(e,t),e.readonly=()=>new _m({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return Yp.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>Yp.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Yp.get(e);const n=e.clone();return Yp.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),zf=/* @__PURE__ */iu("_ZodString",(e,t)=>{Vd.init(e,t),Ef.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=sf[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__ */Fh(...t)),e.includes=(...t)=>e.check(/* @__PURE__ */Bh(...t)),e.startsWith=(...t)=>e.check(/* @__PURE__ */Uh(...t)),e.endsWith=(...t)=>e.check(/* @__PURE__ */Vh(...t)),e.min=(...t)=>e.check(/* @__PURE__ */Dh(...t)),e.max=(...t)=>e.check(/* @__PURE__ */Lh(...t)),e.length=(...t)=>e.check(/* @__PURE__ */jh(...t)),e.nonempty=(...t)=>e.check(/* @__PURE__ */Dh(1,...t)),e.lowercase=t=>e.check(/* @__PURE__ */Rh(t)),e.uppercase=t=>e.check(/* @__PURE__ */$h(t)),e.trim=()=>e.check(/* @__PURE__ */Hh()),e.normalize=(...t)=>e.check(/* @__PURE__ */Wh(...t)),e.toLowerCase=()=>e.check(/* @__PURE__ */Zh()),e.toUpperCase=()=>e.check(/* @__PURE__ */Jh()),e.slugify=()=>e.check(/* @__PURE__ */Kh())}),Nf=/* @__PURE__ */iu("ZodString",(e,t)=>{Vd.init(e,t),zf.init(e,t),e.email=t=>e.check(/* @__PURE__ */Xp(If,t)),e.url=t=>e.check(/* @__PURE__ */ih(Pf,t)),e.jwt=t=>e.check(/* @__PURE__ */wh(Kf,t)),e.emoji=t=>e.check(/* @__PURE__ */ah(Lf,t)),e.guid=t=>e.check(/* @__PURE__ */eh(Tf,t)),e.uuid=t=>e.check(/* @__PURE__ */th(Mf,t)),e.uuidv4=t=>e.check(/* @__PURE__ */nh(Mf,t)),e.uuidv6=t=>e.check(/* @__PURE__ */rh(Mf,t)),e.uuidv7=t=>e.check(/* @__PURE__ */oh(Mf,t)),e.nanoid=t=>e.check(/* @__PURE__ */sh(Df,t)),e.guid=t=>e.check(/* @__PURE__ */eh(Tf,t)),e.cuid=t=>e.check(/* @__PURE__ */lh(jf,t)),e.cuid2=t=>e.check(/* @__PURE__ */ch(Ff,t)),e.ulid=t=>e.check(/* @__PURE__ */uh(Rf,t)),e.base64=t=>e.check(/* @__PURE__ */bh(Hf,t)),e.base64url=t=>e.check(/* @__PURE__ */yh(Zf,t)),e.xid=t=>e.check(/* @__PURE__ */dh($f,t)),e.ksuid=t=>e.check(/* @__PURE__ */ph(Bf,t)),e.ipv4=t=>e.check(/* @__PURE__ */hh(Uf,t)),e.ipv6=t=>e.check(/* @__PURE__ */fh(Vf,t)),e.cidrv4=t=>e.check(/* @__PURE__ */mh(qf,t)),e.cidrv6=t=>e.check(/* @__PURE__ */gh(Wf,t)),e.e164=t=>e.check(/* @__PURE__ */vh(Jf,t)),e.datetime=t=>e.check(function(e){/* @__PURE__ */
168
+ return xh(cf,e)}(t)),e.date=t=>e.check(function(e){/* @__PURE__ */
169
+ return kh(uf,e)}(t)),e.time=t=>e.check(function(e){/* @__PURE__ */
170
+ return _h(df,e)}(t)),e.duration=t=>e.check(function(e){/* @__PURE__ */
171
+ return Sh(pf,e)}(t))});function Of(e){/* @__PURE__ */
172
+ return Qp(Nf,e)}const Af=/* @__PURE__ */iu("ZodStringFormat",(e,t)=>{qd.init(e,t),zf.init(e,t)}),If=/* @__PURE__ */iu("ZodEmail",(e,t)=>{Zd.init(e,t),Af.init(e,t)}),Tf=/* @__PURE__ */iu("ZodGUID",(e,t)=>{Wd.init(e,t),Af.init(e,t)}),Mf=/* @__PURE__ */iu("ZodUUID",(e,t)=>{Hd.init(e,t),Af.init(e,t)}),Pf=/* @__PURE__ */iu("ZodURL",(e,t)=>{Jd.init(e,t),Af.init(e,t)}),Lf=/* @__PURE__ */iu("ZodEmoji",(e,t)=>{Kd.init(e,t),Af.init(e,t)}),Df=/* @__PURE__ */iu("ZodNanoID",(e,t)=>{Gd.init(e,t),Af.init(e,t)}),jf=/* @__PURE__ */iu("ZodCUID",(e,t)=>{Yd.init(e,t),Af.init(e,t)}),Ff=/* @__PURE__ */iu("ZodCUID2",(e,t)=>{Qd.init(e,t),Af.init(e,t)}),Rf=/* @__PURE__ */iu("ZodULID",(e,t)=>{Xd.init(e,t),Af.init(e,t)}),$f=/* @__PURE__ */iu("ZodXID",(e,t)=>{ep.init(e,t),Af.init(e,t)}),Bf=/* @__PURE__ */iu("ZodKSUID",(e,t)=>{tp.init(e,t),Af.init(e,t)}),Uf=/* @__PURE__ */iu("ZodIPv4",(e,t)=>{ap.init(e,t),Af.init(e,t)}),Vf=/* @__PURE__ */iu("ZodIPv6",(e,t)=>{sp.init(e,t),Af.init(e,t)}),qf=/* @__PURE__ */iu("ZodCIDRv4",(e,t)=>{lp.init(e,t),Af.init(e,t)}),Wf=/* @__PURE__ */iu("ZodCIDRv6",(e,t)=>{cp.init(e,t),Af.init(e,t)}),Hf=/* @__PURE__ */iu("ZodBase64",(e,t)=>{dp.init(e,t),Af.init(e,t)}),Zf=/* @__PURE__ */iu("ZodBase64URL",(e,t)=>{pp.init(e,t),Af.init(e,t)}),Jf=/* @__PURE__ */iu("ZodE164",(e,t)=>{hp.init(e,t),Af.init(e,t)}),Kf=/* @__PURE__ */iu("ZodJWT",(e,t)=>{fp.init(e,t),Af.init(e,t)}),Gf=/* @__PURE__ */iu("ZodNumber",(e,t)=>{mp.init(e,t),Ef.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__ */Th(t,n)),e.gte=(t,n)=>e.check(/* @__PURE__ */Mh(t,n)),e.min=(t,n)=>e.check(/* @__PURE__ */Mh(t,n)),e.lt=(t,n)=>e.check(/* @__PURE__ */Ah(t,n)),e.lte=(t,n)=>e.check(/* @__PURE__ */Ih(t,n)),e.max=(t,n)=>e.check(/* @__PURE__ */Ih(t,n)),e.int=t=>e.check(Xf(t)),e.safe=t=>e.check(Xf(t)),e.positive=t=>e.check(/* @__PURE__ */Th(0,t)),e.nonnegative=t=>e.check(/* @__PURE__ */Mh(0,t)),e.negative=t=>e.check(/* @__PURE__ */Ah(0,t)),e.nonpositive=t=>e.check(/* @__PURE__ */Ih(0,t)),e.multipleOf=(t,n)=>e.check(/* @__PURE__ */Ph(t,n)),e.step=(t,n)=>e.check(/* @__PURE__ */Ph(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 Yf(e){/* @__PURE__ */
173
+ return Ch(Gf,e)}const Qf=/* @__PURE__ */iu("ZodNumberFormat",(e,t)=>{gp.init(e,t),Gf.init(e,t)});function Xf(e){/* @__PURE__ */
174
+ return Eh(Qf,e)}const em=/* @__PURE__ */iu("ZodAny",(e,t)=>{bp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}}),tm=/* @__PURE__ */iu("ZodUnknown",(e,t)=>{yp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function nm(){/* @__PURE__ */
175
+ return Nh(tm)}const rm=/* @__PURE__ */iu("ZodNever",(e,t)=>{vp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),om=/* @__PURE__ */iu("ZodArray",(e,t)=>{xp.init(e,t),Ef.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=tf(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */Dh(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */Dh(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */Lh(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */jh(t,n)),e.unwrap=()=>e.element});function im(e,t){/* @__PURE__ */
176
+ return Gh(om,e,t)}const am=/* @__PURE__ */iu("ZodObject",(e,t)=>{Ep.init(e,t),Ef.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]=tf(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=tf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),gu(e,"shape",()=>t.shape),e.keyof=()=>um(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:nm()}),e.loose=()=>e.clone({...e._zod.def,catchall:nm()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */Oh(rm,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!_u(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=yu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return bu(this,"shape",n),n}});return zu(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!_u(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=yu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return bu(this,"shape",n),n}});return zu(e,n)}(e,t),e.merge=t=>function(e,t){const n=yu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return bu(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return zu(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 zu(e,yu(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 bu(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=yu(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 bu(this,"shape",r),r},checks:[]});return zu(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=yu(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 bu(this,"shape",o),o},checks:[]});return zu(t,o)}(pm,e,t[0]),e.required=(...t)=>function(e,t,n){const r=yu(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 bu(this,"shape",o),o}});return zu(t,r)}(vm,e,t[0])}),sm=/* @__PURE__ */iu("ZodUnion",(e,t)=>{Np.init(e,t),Ef.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)=>tf(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}),lm=/* @__PURE__ */iu("ZodIntersection",(e,t)=>{Op.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=tf(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=tf(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)}),cm=/* @__PURE__ */iu("ZodEnum",(e,t)=>{Tp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=uu(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 cm({...t,checks:[],...Nu(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 cm({...t,checks:[],...Nu(r),entries:o})}});function um(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new cm({type:"enum",entries:n,...Nu(t)})}const dm=/* @__PURE__ */iu("ZodTransform",(e,t)=>{Mp.init(e,t),Ef.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 su(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Lu(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(Lu(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),pm=/* @__PURE__ */iu("ZodOptional",(e,t)=>{Lp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function hm(e){return new pm({type:"optional",innerType:e})}const fm=/* @__PURE__ */iu("ZodExactOptional",(e,t)=>{Dp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),mm=/* @__PURE__ */iu("ZodNullable",(e,t)=>{jp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=tf(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 gm(e){return new mm({type:"nullable",innerType:e})}const bm=/* @__PURE__ */iu("ZodDefault",(e,t)=>{Fp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;tf(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}),ym=/* @__PURE__ */iu("ZodPrefault",(e,t)=>{$p.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;tf(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__ */iu("ZodNonOptional",(e,t)=>{Bp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;tf(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),wm=/* @__PURE__ */iu("ZodCatch",(e,t)=>{Vp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;tf(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}),xm=/* @__PURE__ */iu("ZodPipe",(e,t)=>{qp.init(e,t),Ef.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;tf(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function km(e,t){return new xm({type:"pipe",in:e,out:t})}const _m=/* @__PURE__ */iu("ZodReadonly",(e,t)=>{Hp.init(e,t),Ef.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;tf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Sm=/* @__PURE__ */iu("ZodCustom",(e,t)=>{Jp.init(e,t),Ef.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)}),Cm=/* @__PURE__ */Object.create(null);Cm.open="0",Cm.close="1",Cm.ping="2",Cm.pong="3",Cm.message="4",Cm.upgrade="5",Cm.noop="6";const Em=/* @__PURE__ */Object.create(null);Object.keys(Cm).forEach(e=>{Em[Cm[e]]=e});const zm={type:"error",data:"parser error"},Nm="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Om="function"==typeof ArrayBuffer,Am=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Im=({type:e,data:t},n,r)=>Nm&&t instanceof Blob?n?r(t):Tm(t,r):Om&&(t instanceof ArrayBuffer||Am(t))?n?r(t):Tm(new Blob([t]),r):r(Cm[e]+(t||"")),Tm=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function Mm(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Pm;const Lm="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let kb=0;kb<64;kb++)Lm["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(kb)]=kb;const Dm="function"==typeof ArrayBuffer,jm=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Rm(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:Fm(e.substring(1),t)}:Em[n]?e.length>1?{type:Em[n],data:e.substring(1)}:{type:Em[n]}:zm},Fm=(e,t)=>{if(Dm){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=Lm[e.charCodeAt(t)],r=Lm[e.charCodeAt(t+1)],o=Lm[e.charCodeAt(t+2)],i=Lm[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 Rm(n,t)}return{base64:!0,data:e}},Rm=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,$m=String.fromCharCode(30);let Bm;function Um(e){return e.reduce((e,t)=>e+t.length,0)}function Vm(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 qm(e){if(e)return function(e){for(var t in qm.prototype)e[t]=qm.prototype[t];return e}(e)}qm.prototype.on=qm.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},qm.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},qm.prototype.off=qm.prototype.removeListener=qm.prototype.removeAllListeners=qm.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},qm.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},qm.prototype.emitReserved=qm.prototype.emit,qm.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},qm.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Wm="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Hm="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Zm(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const Jm=Hm.setTimeout,Km=Hm.clearTimeout;function Gm(e,t){t.useNativeTimers?(e.setTimeoutFn=Jm.bind(Hm),e.clearTimeoutFn=Km.bind(Hm)):(e.setTimeoutFn=Hm.setTimeout.bind(Hm),e.clearTimeoutFn=Hm.clearTimeout.bind(Hm))}function Ym(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 Qm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Xm extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class eg extends qm{constructor(e){super(),this.writable=!1,Gm(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 Xm(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=jm(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 tg 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($m),r=[];for(let o=0;o<n.length;o++){const e=jm(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)=>{Im(e,!1,e=>{r[i]=e,++o===n&&t(r.join($m))})})})(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]=Qm()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let ng=!1;try{ng="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(xb){}const rg=ng;function og(){}class ig extends tg{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 ag extends qm{constructor(e,t,n){super(),this.createRequest=e,Gm(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=Zm(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=ag.requestsCount++,ag.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=og,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete ag.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 sg(){for(let e in ag.requests)ag.requests.hasOwnProperty(e)&&ag.requests[e].abort()}ag.requestsCount=0,ag.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",sg):"function"==typeof addEventListener&&addEventListener("onpagehide"in Hm?"pagehide":"unload",sg,!1));const lg=function(){const e=cg({xdomain:!1});return e&&null!==e.responseType}();function cg(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||rg))return new XMLHttpRequest}catch(n){}if(!t)try{return new(Hm[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const ug="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class dg extends eg{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=ug?{}:Zm(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(xb){return this.emitReserved("error",xb)}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;Im(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&Wm(()=>{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]=Qm()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const pg=Hm.WebSocket||Hm.MozWebSocket,hg={websocket:class extends dg{createSocket(e,t,n){return ug?new pg(e,t,n):t?new pg(e,t):new pg(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(xb){return this.emitReserved("error",xb)}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){Bm||(Bm=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(Um(n)<1)break;const e=Vm(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(Um(n)<2)break;const e=Vm(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(Um(n)<8)break;const e=Vm(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(zm);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(Um(n)<o)break;const e=Vm(n,o);s.enqueue(jm(i?e:Bm.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(zm);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){Nm&&e.data instanceof Blob?e.data.arrayBuffer().then(Mm).then(t):Om&&(e.data instanceof ArrayBuffer||Am(e.data))?t(Mm(e.data)):Im(e,!1,e=>{Pm||(Pm=new TextEncoder),t(Pm.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&&Wm(()=>{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=lg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new ag(cg,this.uri(),e)}}},fg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,mg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function gg(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[mg[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 bg="function"==typeof addEventListener&&"function"==typeof removeEventListener,yg=[];bg&&addEventListener("offline",()=>{yg.forEach(e=>e())},!1);class vg extends qm{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=gg(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=gg(t.host).host);Gm(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)),bg&&(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"})},yg.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+=Ym(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,Wm(()=>{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(),bg&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=yg.indexOf(this._offlineEventListener);-1!==e&&yg.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 xg=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=>hg[e]).filter(e=>!!e)),super(e,n)}};const kg="function"==typeof ArrayBuffer,_g=Object.prototype.toString,Sg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===_g.call(Blob),Cg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===_g.call(File);function Eg(e){return kg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Sg&&e instanceof Blob||Cg&&e instanceof File}function zg(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(zg(e[t]))return!0;return!1}if(Eg(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return zg(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&zg(e[n]))return!0;return!1}function Ng(e){const t=[],n=e.data,r=e;return r.data=Og(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Og(e,t){if(!e)return e;if(Eg(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]=Og(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]=Og(e[r],t));return n}return e}function Ag(e,t){return e.data=Ig(e.data,t),delete e.attachments,e}function Ig(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]=Ig(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Ig(e[n],t));return e}const Tg=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Mg,Pg;(Pg=Mg||(Mg={}))[Pg.CONNECT=0]="CONNECT",Pg[Pg.DISCONNECT=1]="DISCONNECT",Pg[Pg.EVENT=2]="EVENT",Pg[Pg.ACK=3]="ACK",Pg[Pg.CONNECT_ERROR=4]="CONNECT_ERROR",Pg[Pg.BINARY_EVENT=5]="BINARY_EVENT",Pg[Pg.BINARY_ACK=6]="BINARY_ACK";class Lg extends qm{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===Mg.BINARY_EVENT;n||t.type===Mg.BINARY_ACK?(t.type=n?Mg.EVENT:Mg.ACK,this.reconstructor=new Dg(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Eg(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===Mg[n.type])throw new Error("unknown packet type "+n.type);if(n.type===Mg.BINARY_EVENT||n.type===Mg.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(!jg(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(!Lg.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 Mg.CONNECT:return Fg(t);case Mg.DISCONNECT:return void 0===t;case Mg.CONNECT_ERROR:return"string"==typeof t||Fg(t);case Mg.EVENT:case Mg.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Tg.indexOf(t[0]));case Mg.ACK:case Mg.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Dg{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=Ag(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const jg=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function Fg(e){return"[object Object]"===Object.prototype.toString.call(e)}const Rg=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:Lg,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Mg.EVENT&&e.type!==Mg.ACK||!zg(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Mg.EVENT?Mg.BINARY_EVENT:Mg.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Mg.BINARY_EVENT&&e.type!==Mg.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=Ng(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return Mg}},Symbol.toStringTag,{value:"Module"}));function $g(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const Bg=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ug extends qm{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=[$g(e,"open",this.onopen.bind(this)),$g(e,"packet",this.onpacket.bind(this)),$g(e,"error",this.onerror.bind(this)),$g(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(Bg.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:Mg.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:Mg.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 Mg.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 Mg.EVENT:case Mg.BINARY_EVENT:this.onevent(e);break;case Mg.ACK:case Mg.BINARY_ACK:this.onack(e);break;case Mg.DISCONNECT:this.ondisconnect();break;case Mg.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:Mg.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:Mg.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 Vg(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}Vg.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)},Vg.prototype.reset=function(){this.attempts=0},Vg.prototype.setMin=function(e){this.ms=e},Vg.prototype.setMax=function(e){this.max=e},Vg.prototype.setJitter=function(e){this.jitter=e};class qg extends qm{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,Gm(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 Vg({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||Rg;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 xg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=$g(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=$g(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($g(e,"ping",this.onping.bind(this)),$g(e,"data",this.ondata.bind(this)),$g(e,"error",this.onerror.bind(this)),$g(e,"close",this.onclose.bind(this)),$g(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){Wm(()=>{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 Ug(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 Wg={};function Hg(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=gg(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=Wg[o]&&i in Wg[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new qg(r,t):(Wg[o]||(Wg[o]=new qg(r,t)),s=Wg[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(Hg,{Manager:qg,Socket:Ug,io:Hg,connect:Hg});const Zg="chat_device_id";function Jg(){return"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 Kg=function(){const e={type:"object",shape:{id:Of().optional(),type:um(["text","image","audio","location","system"]).default("text"),content:Of().optional(),imageUrl:Of().url().optional(),audioUrl:Of().optional(),latitude:Yf().optional(),longitude:Yf().optional(),timestamp:Of().optional(),sender:um(["bot","user","system"]).optional(),emotion:/* @__PURE__ */zh(em).optional(),sources:im(Of()).optional()}??{},...Nu(void 0)};return new am(e)}();class Gg{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),Dt("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?Ft():(this.isDisabled=!0,this.queue=[],Ft(t.status))}catch(t){this.isDisabled=!0,this.queue=[],Ft()}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}let Yg=null,Qg=null;function Xg(e){Yg=e}function eb(e){Qg=e}const tb=r(null);function nb({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(e=>{Yg?(Yg(e),Ft(0)):Dt("sendMessage called but no handler registered")},[]),m=s(()=>{Qg?(Qg(),Ft()):Dt("clearMessages called but no handler registered")},[]),g={isOpen:a,open:d,close:p,toggle:h,sendMessage:f,clearMessages:m,unreadCount:c},v=s((e,t)=>{"message:received"!==e||a||u(e=>e+1),o.onEvent?.(e,t)},[a,o]);/* @__PURE__ */
177
+ return y(tb.Provider,{value:g,children:[e,
178
+ /* @__PURE__ */b(cb,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:v})]})}function rb(){const e=o(tb);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const ob=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function ib(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,onThemeUpdate:v}=e,[w,x]=i(0),k=f(0),{t:_}=D(),S=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Gg(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),C=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||$t,h=l||Bt;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 Dt("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),Rt("Notification permission:",e),"granted"===e}catch(e){return jt("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){jt("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=>{Ft(0)})}catch(n){jt("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}),E=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:z,actions:N}=function(e,t="default"){const[r,o]=g(ou,ru),[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 nu.has(n)||nu.set(n,new tu(e,t)),nu.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){Dt("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){jt("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){jt("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){jt("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:[]})},[]);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:_}}}(t,o),O=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),A=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(Zg);if(e)return e;const t=Jg();return localStorage.setItem(Zg,t),t}catch{return Dt("localStorage not available, using session-only device ID"),Jg()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=Kg.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=Hg(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:l?.token,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});e.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),e.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),e.on("connect_error",e=>{h(!1),c.current.onError(`Error de conexión: ${e.message}`)}),e.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),e.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){jt("ChatSocket Error processing bot_message:",t)}}),e.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 Ft(),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){Ft()}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),e.on("bot_typing",e=>c.current.onTyping(e));const o=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};e.on("onboarding:command",e=>o(e)),e.on("form:command",e=>o(e)),e.on("request_form_state",()=>{o({type:"botuyo-request-form-state"})}),e.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),e.on("custom_event",e=>{if(o({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)}}});const i=t=>{const{type:n}=t.data||{};"botuyo-onboarding-state"!==n&&"botuyo-form-state"!==n||e.emit("form_state",t.data)};window.addEventListener("message",i),d.current=e,e.__formCleanup=()=>window.removeEventListener("message",i)},[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}),jt("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]),N=u(()=>tc(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:N,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>O?{...l||{},seo:{...O||{}}}:l,[l,O]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=k.current>0?t-k.current:void 0;k.current=t,N.addMessage(e),S.trackMessageReceived(e.type,n),z.isOpen||"bot"!==e.sender||(x(e=>e+1),C.notifyWithSound(e))},[N,z.isOpen,S,C]),onConnected:s((e,t)=>{N.setConnected(!0),N.setSessionId(e),S.trackConnectionStatus(!0),t&&v&&v(t),t&&b&&b("backend_config",t)},[N,b,v,S]),onDisconnected:s(()=>{N.setConnected(!1),S.trackConnectionStatus(!1)},[N,S]),onTyping:s(e=>N.setTyping(e),[N]),onError:s(e=>{N.setError(e),S.trackError(e)},[N,S]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:v,onHistoryLoaded:s(e=>{const t=new Set(z.messages.map(e=>e.id)),n=e.filter(e=>!t.has(e.id));n.length>0&&(0===z.messages.length?N.setMessages(e):n.forEach(e=>N.addMessage(e)))},[z.messages,N])}),I=s(()=>{Ft(0,z.isOpen),z.isOpen?(N.closeWindow(),S.trackClose(),y?.(!1),Ft()):(N.openWindow(),x(0),S.trackOpen(),y?.(!0),Ft())},[z.isOpen,N,y,S]),T=s(e=>{if(!E.isAllowed()){const e=E.getTimeUntilReset(),t=Math.ceil(e/1e3);return void N.setError(_("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};N.addMessage(t),S.trackMessageSent("text"),A.sendMessage(e,"text")},[N,A,E,S,_]),M=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}`},N.addMessage(n);const r=await ob(e);A.sendMessage(r,t)},[N,A]),P=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"};N.addMessage(t),A.sendMessage(JSON.stringify(e),"location")},[N,A]);a(()=>{const e=()=>{z.isOpen||N.openWindow()},t=()=>{z.isOpen&&N.closeWindow()},n=()=>{z.isOpen?N.closeWindow():N.openWindow()},r=e=>{e.detail?.message&&T(e.detail.message)};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),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:send-message",r)}},[z.isOpen,N,T]),a(()=>(Xg(T),()=>Xg(null)),[T]);const L=s(()=>{N.clearMessages(),Rt("Chat history cleared")},[N]);a(()=>(eb(L),()=>eb(null)),[L]);const j=u(()=>{if(z.isTyping)return"thinking";const e=[...z.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[z.isTyping,z.messages]);return{state:z,actions:N,unreadCount:w,currentBotEmotion:j,isConnected:A.isConnected,getSocket:A.getSocket,handleToggle:I,handleSendText:T,handleSendAttachment:M,handleSendLocation:P}}function ab({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),Ft(),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function sb(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,initialOpen:w=!1,hideLauncher:x=!1}=e,k=f(null),_=nc(),S=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}(k),[C,E]=i(),{mergedTheme:z,mergedStyles:N,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={...zt,...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:{...Ac,...e?.bubbleStyles?.radius},bot:{...Ic,...e?.bubbleStyles?.bot},user:{...Tc,...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,C);a(()=>{z.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.')},[z.isHidden]);const{state:A,actions:I,unreadCount:T,currentBotEmotion:M,isConnected:P,handleToggle:L,handleSendText:D,handleSendAttachment:j,handleSendLocation:F,getSocket:R}=ib({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,onThemeUpdate:E}),$=f(!1);a(()=>{w&&C&&!$.current&&($.current=!0,A.isOpen||I.openWindow())},[w,C,A.isOpen,I]);const B=s(e=>{I.addMessage({id:`voice-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"text",sender:e.sender,timestamp:e.timestamp||/* @__PURE__ */new Date,content:e.content})},[I]),U=u(()=>{const e={...d||{}},t=C;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,C]),V=s(()=>{I.closeWindow()},[I]),q=s(e=>{e.stopPropagation()},[]),W=O(A.isOpen,_,c?.position),H=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(!z.cssVariables)return e;let t={...z.cssVariables};if(S){const e=C?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Nt,...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},[z.cssVariables,S,C,c?.darkCssVariables]);return z.isHidden?null:C?/* @__PURE__ */y("div",{ref:k,id:"botuyo-chat-widget-root",className:Et("botuyo-chat-widget flex flex-col",!_&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...W,...H,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:[
179
+ /* @__PURE__ */b("div",{className:Et("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",_?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",A.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:A.isOpen?"auto":"none"},onMouseDown:q,onTouchStart:q,children:/* @__PURE__ */b(Oc,{children:/* @__PURE__ */b(Nc,{isOpen:A.isOpen,isConnected:P,isTyping:A.isTyping,messages:A.messages,onClose:V,onSendMessage:D,onSendAttachment:j,onSendLocation:F,botName:z.botName,logoUrl:z.logoUrl,welcomeMessage:z.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||C?.inputPlaceholder,position:c?.position,bubbleStyles:N,avatars:c?.avatars||C?.avatars||C?.avatarAnimations||{},mediaConfig:U,theme:z,avatar3dUrl:c?.avatar3dUrl||C?.avatar3dUrl,getSocket:R,onAddVoiceMessage:B,suggestedQuestions:C?.suggestedQuestions})})}),!x&&/* @__PURE__ */b("div",{className:Et(A.isOpen?"hidden":"block",!_&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:q,onTouchStart:q,children:/* @__PURE__ */b(Vt,{isOpen:A.isOpen,onClick:L,unreadCount:T,position:c?.position||"bottom-right",primaryColor:Ot(z),logoUrl:z.logoUrl,starterPrompt:c?.starterPrompt||C?.starterPrompt,avatars:c?.avatars||C?.avatars||C?.avatarAnimations||{},emotion:M,styles:N,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??C?.avatarScale,showPromptAvatar:c?.showPromptAvatar??C?.showPromptAvatar})})]}):null}function lb(e){/* @__PURE__ */
180
+ return b(Pt,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(sb,{...e})})}function cb(e){/* @__PURE__ */
181
+ return b(M,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b(ab,{children:/* @__PURE__ */b(lb,{...e})})})}const ub=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:cb,ChatWidgetInner:sb,ChatWidgetWithProviders:lb},Symbol.toStringTag,{value:"Module"}));function db({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__ */
182
+ return b("div",{style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:/* @__PURE__ */b(M,{defaultLocale:r,children:/* @__PURE__ */b(lb,{...i})})},n)}function pb({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 hb({position:e,target:t}){const{camera:n}=_();return a(()=>{e&&t&&(n.position.set(...e),n.lookAt(...t))},[n,e,t]),null}function fb({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:[
183
+ /* @__PURE__ */b(hb,{position:n,target:r}),
184
184
  /* @__PURE__ */b("ambientLight",{intensity:.6}),
185
185
  /* @__PURE__ */b("directionalLight",{position:[1,2,3],intensity:.8,color:"#ffffff"}),
186
186
  /* @__PURE__ */b("directionalLight",{position:[-1,1,-1],intensity:.3,color:"#b4c6e7"}),
187
187
  /* @__PURE__ */b("pointLight",{position:[0,.5,-.5],intensity:.5,distance:3}),
188
- /* @__PURE__ */b(sb,{url:e,autoRotate:o,hasCustomCamera:!(!n||!r)})]})})}):null}const ub="https://api.botuyo.com";class db 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 pb={"--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%"},hb=p(()=>Promise.resolve().then(()=>ib).then(e=>({default:e.ChatWidgetWithProviders})));class fb{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||ub},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(pb).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(pb).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||ub,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(hb,t));this.root.render(n.createElement(db,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"))}sendMessage(e){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:e}}))}getState(){return null}}const mb=new fb;window.BotUyoChat=mb;export{cb as A,fb as B,ob as C,K as L,ab as P,se as X,Et as a,Yg as b,$ as c,rb as d,M as e,Qg as f,Ot as g,P as h,mb as i,D as u};
189
- //# sourceMappingURL=standalone-Dj57xV3P.js.map
188
+ /* @__PURE__ */b(pb,{url:e,autoRotate:o,hasCustomCamera:!(!n||!r)})]})})}):null}const mb="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 bb={"--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%"},yb=p(()=>Promise.resolve().then(()=>ub).then(e=>({default:e.ChatWidgetWithProviders})));class vb{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||mb},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(bb).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(bb).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||mb,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(yb,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"))}sendMessage(e){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:e}}))}getState(){return null}}const wb=new vb;window.BotUyoChat=wb;export{fb as A,vb as B,cb as C,K as L,db as P,se as X,Et as a,nb as b,$ as c,lb as d,M as e,rb as f,Ot as g,P as h,wb as i,D as u};
189
+ //# sourceMappingURL=standalone-D_HyV1wJ.js.map