@botuyo/chat-widget-standalone 1.7.0 → 1.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AudioPlayer-DWoSy0eU.js → AudioPlayer-C-QlUBwD.js} +2 -2
- package/dist/{AudioPlayer-DWoSy0eU.js.map → AudioPlayer-C-QlUBwD.js.map} +1 -1
- package/dist/Avatar3D-B_M9-Vb8.js +9 -0
- package/dist/Avatar3D-B_M9-Vb8.js.map +1 -0
- package/dist/{Gallery-FVjRcegN.js → Gallery-D6fZeqeG.js} +2 -2
- package/dist/{Gallery-FVjRcegN.js.map → Gallery-D6fZeqeG.js.map} +1 -1
- package/dist/botuyo-chat.es.js +1 -1
- package/dist/botuyo-chat.umd.js +1 -1
- package/dist/botuyo-chat.umd.js.map +1 -1
- package/dist/src/chat-widget/components/Avatar3D.d.ts.map +1 -1
- package/dist/src/chat-widget/components/Avatar3DPreview.d.ts.map +1 -1
- package/dist/src/chat-widget/utils/avatar3d.d.ts +51 -0
- package/dist/src/chat-widget/utils/avatar3d.d.ts.map +1 -0
- package/dist/{standalone-CrFgr-Ss.js → standalone-DS5eWQKM.js} +9 -9
- package/dist/standalone-DS5eWQKM.js.map +1 -0
- package/dist/stats-umd.html +1 -1
- package/dist/stats.html +1 -1
- package/package.json +1 -1
- package/dist/Avatar3D-CoXzuLgX.js +0 -9
- package/dist/Avatar3D-CoXzuLgX.js.map +0 -1
- package/dist/standalone-CrFgr-Ss.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Avatar3D.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/components/Avatar3D.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;
|
|
1
|
+
{"version":3,"file":"Avatar3D.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/components/Avatar3D.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAgBH,KAAK,SAAS,GAAG,MAAM,GAAG,YAAY,GAAG,WAAW,GAAG,UAAU,GAAG,UAAU,CAAA;AAE9E,UAAU,aAAa;IACrB,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,SAAS,EAAE,SAAS,CAAA;IACpB,UAAU,EAAE,MAAM,CAAA;IAClB,YAAY,EAAE,MAAM,CAAA;IACpB,IAAI,EAAE,MAAM,CAAA;CACb;AAilBD,MAAM,CAAC,OAAO,UAAU,QAAQ,CAAC,EAC/B,QAAQ,EACR,OAAO,EACP,SAAS,EACT,UAAU,EACV,YAAY,EACZ,IAAI,GACL,EAAE,aAAa,2CAqEf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Avatar3DPreview.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/components/Avatar3DPreview.tsx"],"names":[],"mappings":"AAAA;;;;;;GAMG;
|
|
1
|
+
{"version":3,"file":"Avatar3DPreview.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/components/Avatar3DPreview.tsx"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAcH,UAAU,oBAAoB;IAC5B,GAAG,EAAE,MAAM,CAAA;IACX,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;IACzC,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;IACzC,yCAAyC;IACzC,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,qEAAqE;IACrE,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,oEAAoE;IACpE,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,4CAA4C;IAC5C,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,6CAA6C;IAC7C,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,oDAAoD;IACpD,MAAM,CAAC,EAAE,MAAM,IAAI,CAAA;IACnB,wCAAwC;IACxC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAA;CACnC;AA6QD,wBAAgB,eAAe,CAAC,EAC9B,GAAG,EACH,SAAc,EACd,cAAc,EACd,cAAc,EACd,UAAiB,EACjB,WAAkB,EAClB,UAAiB,EACjB,YAAkC,EAClC,UAA0C,EAC1C,MAAM,EACN,OAAO,GACR,EAAE,oBAAoB,kDAgGtB"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure 3D-avatar helpers shared by the voice-call avatar (`Avatar3D`) and the
|
|
3
|
+
* dashboard/landing previewer (`Avatar3DPreview`).
|
|
4
|
+
*
|
|
5
|
+
* The preview framing was already correct, so it is the single source of truth:
|
|
6
|
+
* both the call and the preview place the camera with `computeGlbFraming`, which
|
|
7
|
+
* guarantees the call shows exactly what the preview shows — same distance, same
|
|
8
|
+
* front-facing orientation — instead of the two drifting apart (the call used to
|
|
9
|
+
* render the avatar from behind, "de espaldas").
|
|
10
|
+
*
|
|
11
|
+
* No three.js / R3F imports on purpose: this is plain math so it is trivially
|
|
12
|
+
* unit-testable in happy-dom without mocking the WebGL stack.
|
|
13
|
+
*/
|
|
14
|
+
/** Bounding-box size (metres) of the model AFTER it has been centred on the origin. */
|
|
15
|
+
export interface AvatarSize {
|
|
16
|
+
x: number;
|
|
17
|
+
y: number;
|
|
18
|
+
z: number;
|
|
19
|
+
}
|
|
20
|
+
export interface AvatarFraming {
|
|
21
|
+
/** Camera position `[x, y, z]`. Always on **+Z** (glTF / Ready-Player-Me avatars face +Z). */
|
|
22
|
+
position: [number, number, number];
|
|
23
|
+
/** Look-at / orbit target `[x, y, z]`, kept level with the camera height. */
|
|
24
|
+
target: [number, number, number];
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Compute where to place the camera to frame a centred GLB avatar.
|
|
28
|
+
*
|
|
29
|
+
* The model is expected to already be centred on the origin (its bbox centre at
|
|
30
|
+
* `(0,0,0)`), so it spans `[-size.y/2, +size.y/2]` vertically. The camera is
|
|
31
|
+
* placed on the **positive Z axis** because glTF / Ready-Player-Me humanoids
|
|
32
|
+
* face +Z — this is what stops the avatar from appearing "de espaldas".
|
|
33
|
+
*
|
|
34
|
+
* The numbers mirror the preview's original (correct) framing, so the voice call
|
|
35
|
+
* and the preview render the avatar identically.
|
|
36
|
+
*/
|
|
37
|
+
export declare function computeGlbFraming(size: AvatarSize, fovDegrees: number): AvatarFraming;
|
|
38
|
+
/**
|
|
39
|
+
* Pick the single idle animation clip to auto-play, or `null`.
|
|
40
|
+
*
|
|
41
|
+
* Avatars in a chat/voice context should stay put — they are talking heads, not
|
|
42
|
+
* game characters. Auto-playing *every* embedded clip (or a locomotion/jump
|
|
43
|
+
* clip) makes the model jump, walk or T-pose inside the frame. So we only play a
|
|
44
|
+
* clip that is explicitly named like an idle loop; anything else (jump, run,
|
|
45
|
+
* walk, generic "mixamo.com" / "Take 001" names) is skipped in favour of the
|
|
46
|
+
* component's procedural breathing/sway.
|
|
47
|
+
*/
|
|
48
|
+
export declare function selectIdleClip<T extends {
|
|
49
|
+
name?: string | null;
|
|
50
|
+
}>(clips: readonly T[]): T | null;
|
|
51
|
+
//# sourceMappingURL=avatar3d.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"avatar3d.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/utils/avatar3d.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,uFAAuF;AACvF,MAAM,WAAW,UAAU;IACzB,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;CACV;AAED,MAAM,WAAW,aAAa;IAC5B,8FAA8F;IAC9F,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;IAClC,6EAA6E;IAC7E,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;CACjC;AAQD;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,GAAG,aAAa,CAYrF;AAKD;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS;IAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,GAAG,CAAC,GAAG,IAAI,CAMhG"}
|
|
@@ -26,7 +26,7 @@ return y("div",{className:"w-full my-2 rounded-2xl border shadow-sm overflow-hid
|
|
|
26
26
|
/* @__PURE__ */y("button",{type:"button",onClick:()=>{d||(c("cancelled"),o?.(e.proposalId))},"data-testid":"tool-proposal-cancel",className:"flex-1 flex items-center justify-center gap-1.5 py-3 text-xs font-bold transition-colors hover:bg-muted/50 active:scale-[0.98]",style:{color:"hsl(var(--muted-foreground))"},children:[
|
|
27
27
|
/* @__PURE__ */b(de,{size:14,strokeWidth:2.5}),a("cancel")]}),
|
|
28
28
|
/* @__PURE__ */y("button",{type:"button",onClick:()=>{p||(c("confirmed"),r?.(e.proposalId))},disabled:p,"data-testid":"tool-proposal-confirm",className:"flex-1 flex items-center justify-center gap-1.5 py-3 text-xs font-black text-white transition-all active:scale-[0.98] disabled:opacity-40 disabled:cursor-not-allowed disabled:active:scale-100",style:{backgroundColor:s},children:[
|
|
29
|
-
/* @__PURE__ */b(V,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Zl=p(()=>import("./AudioPlayer-
|
|
29
|
+
/* @__PURE__ */b(V,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Zl=p(()=>import("./AudioPlayer-C-QlUBwD.js").then(e=>({default:e.AudioPlayer}))),Jl=p(()=>import("./Gallery-D6fZeqeG.js").then(e=>({default:e.Gallery})));function Kl({message:e,brandColor:t,onButtonClick:n}){const[r,o]=i(e.selectedId||null);/* @__PURE__ */
|
|
30
30
|
return y("div",{className:"space-y-3",children:[
|
|
31
31
|
/* @__PURE__ */b("div",{className:Tt("prose prose-sm max-w-none break-words leading-relaxed dark:prose-invert text-foreground"),children:/* @__PURE__ */b(Ba,{remarkPlugins:[Pl],rehypePlugins:[[Vl,{tagNames:["p","strong","em","br","span"],attributes:{}}]],components:{p:({children:e})=>/* @__PURE__ */b("p",{className:"mb-0 last:mb-0",children:e})},children:e.content})}),
|
|
32
32
|
/* @__PURE__ */b("div",{className:"flex flex-col gap-2",children:e.buttons.map((i,a)=>{const s=r===i.id;/* @__PURE__ */
|
|
@@ -107,7 +107,7 @@ return b("div",{"data-testid":"quiz-dock",className:"shrink-0 border-t animate-i
|
|
|
107
107
|
/* @__PURE__ */b("p",{className:"text-sm font-semibold mb-2 text-foreground break-words leading-snug",children:e.content}),
|
|
108
108
|
/* @__PURE__ */b("div",{className:"flex flex-col gap-2",children:e.buttons.map((e,t)=>/* @__PURE__ */b("button",{type:"button",onClick:()=>n(e.label,e.id),className:"w-full text-left px-4 py-3 rounded-xl border text-sm font-semibold transition-all duration-200 cursor-pointer hover:scale-[1.02] hover:shadow-md active:scale-[0.97]",style:{backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))",color:"hsl(var(--foreground))"},children:/* @__PURE__ */y("span",{className:"flex items-center gap-3",children:[
|
|
109
109
|
/* @__PURE__ */b("span",{className:"flex items-center justify-center w-6 h-6 rounded-full text-xs font-black shrink-0",style:{backgroundColor:r,color:"white"},children:String.fromCharCode(65+t)}),
|
|
110
|
-
/* @__PURE__ */b("span",{children:e.label})]})},e.id))})]})})}function lc(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 cc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=lc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const uc="24px",dc={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},pc=85,hc=.7,fc=200,mc=.5,gc=3e3,bc=1,yc=6,vc=7500,wc=.7,xc=-20,kc=8,_c=6,Sc=.002,Cc=.12,Ec={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},zc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{...Ec},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function Nc(e=Ec,t="voice-pcm-processor",n=1600){return`\nclass VoicePCMProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n this.gain = 1; // current applied gain — starts open\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 >= ${n}) {\n // 1. Frame RMS — near-field speaker vs. background energy\n let sumSq = 0;\n for (let j = 0; j < ${n}; j++) sumSq += this.buffer[j] * this.buffer[j];\n const rms = Math.sqrt(sumSq / ${n});\n\n // 2. Downward-expander target + smoothed gain (fast attack, slow release)\n const target = rms >= ${e.openThreshold} ? 1 : ${e.floorGain};\n let nextGain;\n if (target >= this.gain) {\n nextGain = Math.min(target, this.gain + ${e.attackStep});\n } else {\n nextGain = Math.max(target, this.gain - ${e.releaseStep});\n }\n\n // 3. Apply gain with a per-sample ramp (click-free) → Int16 PCM\n const int16 = new Int16Array(${n});\n const gStep = (nextGain - this.gain) / ${n};\n let g = this.gain;\n for (let j = 0; j < ${n}; j++) {\n g += gStep;\n const s = Math.max(-1, Math.min(1, this.buffer[j] * g));\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n this.gain = nextGain;\n\n // 4. ALWAYS post PCM + this frame's RMS. The client VAD gate decides\n // per frame what actually reaches the provider.\n this.port.postMessage({ pcm: int16.buffer, rms: rms }, [int16.buffer]);\n\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('${t}', VoicePCMProcessor);\n`}const Ac={low:{positiveSpeechThreshold:.4,negativeSpeechThreshold:.3,nearFieldRms:.012,bargeInRms:.022,onsetFrames:1,redemptionFrames:10},standard:{positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,nearFieldRms:.02,bargeInRms:.035,onsetFrames:2,redemptionFrames:8},high:{positiveSpeechThreshold:.6,negativeSpeechThreshold:.45,nearFieldRms:.032,bargeInRms:.055,onsetFrames:3,redemptionFrames:6}};function Tc(e){return void 0===e||"standard"===e?{...Ac.standard}:"string"==typeof e?{...Ac[e]??Ac.standard}:{...Ac.standard,...e}}class Ic{config;_state="silence";onsetCount=0;redemptionCount=0;constructor(e={}){this.config={...Ac.standard,...e}}get state(){return this._state}reset(){this._state="silence",this.onsetCount=0,this.redemptionCount=0}process(e){return"silence"===this._state?this.processSilence(e):this.processSpeech(e)}processSilence(e){const t=e.botSpeaking?this.config.bargeInRms:this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.positiveSpeechThreshold)&&e.rms>=t?(this.onsetCount+=1,this.onsetCount<this.config.onsetFrames?{shouldStream:!1,state:"silence"}:(this._state="speech",this.onsetCount=0,this.redemptionCount=0,{shouldStream:!0,state:"speech",event:e.botSpeaking?"barge_in":"speech_start"})):(this.onsetCount=0,{shouldStream:!1,state:"silence"})}processSpeech(e){const t=.5*this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.negativeSpeechThreshold)&&e.rms>=t?(this.redemptionCount=0,{shouldStream:!0,state:"speech"}):(this.redemptionCount+=1,this.redemptionCount<this.config.redemptionFrames?{shouldStream:!0,state:"speech"}:(this._state="silence",this.redemptionCount=0,{shouldStream:!1,state:"silence",event:"speech_end"}))}}const Oc="0.0.30",Mc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Oc}/dist/`,Pc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Oc}/+esm`;function Lc(e){if(0===e.length)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}async function Dc(){return await import(Pc)}class jc{constructor(e){this.instance=e}_running=!1;get running(){return this._running}async start(){await this.instance.start(),this._running=!0}destroy(){try{this.instance.destroy()}catch(e){$t("[VAD] error while destroying detector",e)}this._running=!1}}const Rc=p(()=>import("./Avatar3D-
|
|
110
|
+
/* @__PURE__ */b("span",{children:e.label})]})},e.id))})]})})}function lc(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 cc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=lc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const uc="24px",dc={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},pc=85,hc=.7,fc=200,mc=.5,gc=3e3,bc=1,yc=6,vc=7500,wc=.7,xc=-20,kc=8,_c=6,Sc=.002,Cc=.12,Ec={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},zc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{...Ec},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function Nc(e=Ec,t="voice-pcm-processor",n=1600){return`\nclass VoicePCMProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n this.gain = 1; // current applied gain — starts open\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 >= ${n}) {\n // 1. Frame RMS — near-field speaker vs. background energy\n let sumSq = 0;\n for (let j = 0; j < ${n}; j++) sumSq += this.buffer[j] * this.buffer[j];\n const rms = Math.sqrt(sumSq / ${n});\n\n // 2. Downward-expander target + smoothed gain (fast attack, slow release)\n const target = rms >= ${e.openThreshold} ? 1 : ${e.floorGain};\n let nextGain;\n if (target >= this.gain) {\n nextGain = Math.min(target, this.gain + ${e.attackStep});\n } else {\n nextGain = Math.max(target, this.gain - ${e.releaseStep});\n }\n\n // 3. Apply gain with a per-sample ramp (click-free) → Int16 PCM\n const int16 = new Int16Array(${n});\n const gStep = (nextGain - this.gain) / ${n};\n let g = this.gain;\n for (let j = 0; j < ${n}; j++) {\n g += gStep;\n const s = Math.max(-1, Math.min(1, this.buffer[j] * g));\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n this.gain = nextGain;\n\n // 4. ALWAYS post PCM + this frame's RMS. The client VAD gate decides\n // per frame what actually reaches the provider.\n this.port.postMessage({ pcm: int16.buffer, rms: rms }, [int16.buffer]);\n\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('${t}', VoicePCMProcessor);\n`}const Ac={low:{positiveSpeechThreshold:.4,negativeSpeechThreshold:.3,nearFieldRms:.012,bargeInRms:.022,onsetFrames:1,redemptionFrames:10},standard:{positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,nearFieldRms:.02,bargeInRms:.035,onsetFrames:2,redemptionFrames:8},high:{positiveSpeechThreshold:.6,negativeSpeechThreshold:.45,nearFieldRms:.032,bargeInRms:.055,onsetFrames:3,redemptionFrames:6}};function Tc(e){return void 0===e||"standard"===e?{...Ac.standard}:"string"==typeof e?{...Ac[e]??Ac.standard}:{...Ac.standard,...e}}class Ic{config;_state="silence";onsetCount=0;redemptionCount=0;constructor(e={}){this.config={...Ac.standard,...e}}get state(){return this._state}reset(){this._state="silence",this.onsetCount=0,this.redemptionCount=0}process(e){return"silence"===this._state?this.processSilence(e):this.processSpeech(e)}processSilence(e){const t=e.botSpeaking?this.config.bargeInRms:this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.positiveSpeechThreshold)&&e.rms>=t?(this.onsetCount+=1,this.onsetCount<this.config.onsetFrames?{shouldStream:!1,state:"silence"}:(this._state="speech",this.onsetCount=0,this.redemptionCount=0,{shouldStream:!0,state:"speech",event:e.botSpeaking?"barge_in":"speech_start"})):(this.onsetCount=0,{shouldStream:!1,state:"silence"})}processSpeech(e){const t=.5*this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.negativeSpeechThreshold)&&e.rms>=t?(this.redemptionCount=0,{shouldStream:!0,state:"speech"}):(this.redemptionCount+=1,this.redemptionCount<this.config.redemptionFrames?{shouldStream:!0,state:"speech"}:(this._state="silence",this.redemptionCount=0,{shouldStream:!1,state:"silence",event:"speech_end"}))}}const Oc="0.0.30",Mc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Oc}/dist/`,Pc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Oc}/+esm`;function Lc(e){if(0===e.length)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}async function Dc(){return await import(Pc)}class jc{constructor(e){this.instance=e}_running=!1;get running(){return this._running}async start(){await this.instance.start(),this._running=!0}destroy(){try{this.instance.destroy()}catch(e){$t("[VAD] error while destroying detector",e)}this._running=!1}}const Rc=p(()=>import("./Avatar3D-B_M9-Vb8.js")),Fc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},$c={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"]}}},Uc=24e3;function qc(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++)n+=String.fromCharCode(t[r]);return btoa(n)}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||Vt:t||Vt: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__ */
|
|
111
111
|
return y("div",n&&!d?{className:"relative flex flex-col items-center gap-4",children:[
|
|
112
112
|
/* @__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(Rc,{modelUrl:n,emotion:r,callState:o,audioLevel:a,primaryColor:s.speakingColor,size:s.orbSize})})}),s.showWaveform&&/* @__PURE__ */b(Hc,{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:[
|
|
113
113
|
/* @__PURE__ */y("div",{className:Tt("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:[
|
|
@@ -197,23 +197,23 @@ return kh(Xf,e)}const tm=/* @__PURE__ */Eu("ZodStringFormat",(e,t)=>{pp.init(e,t
|
|
|
197
197
|
return Kh(xm,e)}const _m=/* @__PURE__ */Eu("ZodNumberFormat",(e,t)=>{Rp.init(e,t),xm.init(e,t)});function Sm(e){/* @__PURE__ */
|
|
198
198
|
return Gh(_m,e)}const Cm=/* @__PURE__ */Eu("ZodBoolean",(e,t)=>{Fp.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)}),Em=/* @__PURE__ */Eu("ZodAny",(e,t)=>{$p.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}}),zm=/* @__PURE__ */Eu("ZodUnknown",(e,t)=>{Bp.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Nm(){/* @__PURE__ */
|
|
199
199
|
return Xh(zm)}const Am=/* @__PURE__ */Eu("ZodNever",(e,t)=>{Up.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),Tm=/* @__PURE__ */Eu("ZodArray",(e,t)=>{Vp.init(e,t),Yf.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=zf(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */lf(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */lf(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */sf(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */cf(t,n)),e.unwrap=()=>e.element});function Im(e,t){/* @__PURE__ */
|
|
200
|
-
return kf(Tm,e,t)}const Om=/* @__PURE__ */Eu("ZodObject",(e,t)=>{Kp.init(e,t),Yf.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]=zf(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=zf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),ju(e,"shape",()=>t.shape),e.keyof=()=>Rm(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__ */ef(Am,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Vu(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=Fu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ru(this,"shape",n),n}});return Ju(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Vu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Fu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ru(this,"shape",n),n}});return Ju(e,n)}(e,t),e.merge=t=>function(e,t){const n=Fu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Ru(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Ju(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 Ju(e,Fu(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 Ru(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=Fu(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 Ru(this,"shape",r),r},checks:[]});return Ju(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=Fu(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 Ru(this,"shape",o),o},checks:[]});return Ju(t,o)}($m,e,t[0]),e.required=(...t)=>function(e,t,n){const r=Fu(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 Ru(this,"shape",o),o}});return Ju(t,r)}(Zm,e,t[0])});function Mm(e,t){const n={type:"object",shape:e??{},...Ku(t)};return new Om(n)}const Pm=/* @__PURE__ */Eu("ZodUnion",(e,t)=>{Yp.init(e,t),Yf.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)=>zf(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__ */Eu("ZodIntersection",(e,t)=>{Qp.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=zf(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=zf(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)}),Dm=/* @__PURE__ */Eu("ZodRecord",(e,t)=>{th.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object";const a=i.keyType,s=a._zod.bag,l=s?.patterns;if("loose"===i.mode&&l&&l.size>0){const e=zf(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const t of l)o.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(o.propertyNames=zf(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=zf(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=a._zod.values;if(c){const e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(o.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType}),jm=/* @__PURE__ */Eu("ZodEnum",(e,t)=>{nh.init(e,t),Yf.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 jm({...t,checks:[],...Ku(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 jm({...t,checks:[],...Ku(r),entries:o})}});function Rm(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new jm({type:"enum",entries:n,...Ku(t)})}const Fm=/* @__PURE__ */Eu("ZodTransform",(e,t)=>{rh.init(e,t),Yf.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(nd(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(nd(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),$m=/* @__PURE__ */Eu("ZodOptional",(e,t)=>{ih.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Bm(e){return new $m({type:"optional",innerType:e})}const Um=/* @__PURE__ */Eu("ZodExactOptional",(e,t)=>{ah.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),qm=/* @__PURE__ */Eu("ZodNullable",(e,t)=>{sh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=zf(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 Vm(e){return new qm({type:"nullable",innerType:e})}const Wm=/* @__PURE__ */Eu("ZodDefault",(e,t)=>{lh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;zf(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)=>{uh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;zf(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}),Zm=/* @__PURE__ */Eu("ZodNonOptional",(e,t)=>{dh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;zf(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Jm=/* @__PURE__ */Eu("ZodCatch",(e,t)=>{hh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;zf(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}),Km=/* @__PURE__ */Eu("ZodPipe",(e,t)=>{fh.init(e,t),Yf.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;zf(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function Gm(e,t){return new Km({type:"pipe",in:e,out:t})}const Ym=/* @__PURE__ */Eu("ZodReadonly",(e,t)=>{gh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;zf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Qm=/* @__PURE__ */Eu("ZodCustom",(e,t)=>{yh.init(e,t),Yf.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)}),Xm=/* @__PURE__ */Object.create(null);Xm.open="0",Xm.close="1",Xm.ping="2",Xm.pong="3",Xm.message="4",Xm.upgrade="5",Xm.noop="6";const eg=/* @__PURE__ */Object.create(null);Object.keys(Xm).forEach(e=>{eg[Xm[e]]=e});const tg={type:"error",data:"parser error"},ng="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),rg="function"==typeof ArrayBuffer,og=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ig=({type:e,data:t},n,r)=>ng&&t instanceof Blob?n?r(t):ag(t,r):rg&&(t instanceof ArrayBuffer||og(t))?n?r(t):ag(new Blob([t]),r):r(Xm[e]+(t||"")),ag=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function sg(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let lg;const cg="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let ay=0;ay<64;ay++)cg["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(ay)]=ay;const ug="function"==typeof ArrayBuffer,dg=(e,t)=>{if("string"!=typeof e)return{type:"message",data:hg(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:pg(e.substring(1),t)}:eg[n]?e.length>1?{type:eg[n],data:e.substring(1)}:{type:eg[n]}:tg},pg=(e,t)=>{if(ug){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=cg[e.charCodeAt(t)],r=cg[e.charCodeAt(t+1)],o=cg[e.charCodeAt(t+2)],i=cg[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 hg(n,t)}return{base64:!0,data:e}},hg=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,fg=String.fromCharCode(30);let mg;function gg(e){return e.reduce((e,t)=>e+t.length,0)}function bg(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 yg(e){if(e)return function(e){for(var t in yg.prototype)e[t]=yg.prototype[t];return e}(e)}yg.prototype.on=yg.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},yg.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},yg.prototype.off=yg.prototype.removeListener=yg.prototype.removeAllListeners=yg.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},yg.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},yg.prototype.emitReserved=yg.prototype.emit,yg.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},yg.prototype.hasListeners=function(e){return!!this.listeners(e).length};const vg="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),wg="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function xg(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const kg=wg.setTimeout,_g=wg.clearTimeout;function Sg(e,t){t.useNativeTimers?(e.setTimeoutFn=kg.bind(wg),e.clearTimeoutFn=_g.bind(wg)):(e.setTimeoutFn=wg.setTimeout.bind(wg),e.clearTimeoutFn=wg.clearTimeout.bind(wg))}function Cg(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 Eg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class zg extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Ng extends yg{constructor(e){super(),this.writable=!1,Sg(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 zg(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=dg(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 Ag extends Ng{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(fg),r=[];for(let o=0;o<n.length;o++){const e=dg(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)=>{ig(e,!1,e=>{r[i]=e,++o===n&&t(r.join(fg))})})})(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]=Eg()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Tg=!1;try{Tg="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(iy){}const Ig=Tg;function Og(){}class Mg extends Ag{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 Pg extends yg{constructor(e,t,n){super(),this.createRequest=e,Sg(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=xg(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=Pg.requestsCount++,Pg.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 Pg.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 Lg(){for(let e in Pg.requests)Pg.requests.hasOwnProperty(e)&&Pg.requests[e].abort()}Pg.requestsCount=0,Pg.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Lg):"function"==typeof addEventListener&&addEventListener("onpagehide"in wg?"pagehide":"unload",Lg,!1));const Dg=function(){const e=jg({xdomain:!1});return e&&null!==e.responseType}();function jg(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Ig))return new XMLHttpRequest}catch(n){}if(!t)try{return new(wg[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const Rg="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Fg extends Ng{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Rg?{}:xg(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(iy){return this.emitReserved("error",iy)}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;ig(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&vg(()=>{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]=Eg()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const $g=wg.WebSocket||wg.MozWebSocket,Bg={websocket:class extends Fg{createSocket(e,t,n){return Rg?new $g(e,t,n):t?new $g(e,t):new $g(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Ng{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(iy){return this.emitReserved("error",iy)}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){mg||(mg=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(gg(n)<1)break;const e=bg(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(gg(n)<2)break;const e=bg(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(gg(n)<8)break;const e=bg(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(tg);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(gg(n)<o)break;const e=bg(n,o);s.enqueue(dg(i?e:mg.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(tg);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){ng&&e.data instanceof Blob?e.data.arrayBuffer().then(sg).then(t):rg&&(e.data instanceof ArrayBuffer||og(e.data))?t(sg(e.data)):ig(e,!1,e=>{lg||(lg=new TextEncoder),t(lg.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&&vg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Mg{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Dg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Pg(jg,this.uri(),e)}}},Ug=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Vg(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=Ug.exec(e||""),i={},a=14;for(;a--;)i[qg[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 Wg="function"==typeof addEventListener&&"function"==typeof removeEventListener,Hg=[];Wg&&addEventListener("offline",()=>{Hg.forEach(e=>e())},!1);class Zg extends yg{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=Vg(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=Vg(t.host).host);Sg(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)),Wg&&(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&&Zg.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",Zg.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+=Cg(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,vg(()=>{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(Zg.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(),Wg&&(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}}}Zg.protocol=4;class Jg extends Zg{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;Zg.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;Zg.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 Kg=class extends Jg{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=>Bg[e]).filter(e=>!!e)),super(e,n)}};const Gg="function"==typeof ArrayBuffer,Yg=Object.prototype.toString,Qg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Yg.call(Blob),Xg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Yg.call(File);function eb(e){return Gg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Qg&&e instanceof Blob||Xg&&e instanceof File}function tb(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(tb(e[t]))return!0;return!1}if(eb(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return tb(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&tb(e[n]))return!0;return!1}function nb(e){const t=[],n=e.data,r=e;return r.data=rb(n,t),r.attachments=t.length,{packet:r,buffers:t}}function rb(e,t){if(!e)return e;if(eb(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]=rb(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]=rb(e[r],t));return n}return e}function ob(e,t){return e.data=ib(e.data,t),delete e.attachments,e}function ib(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]=ib(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ib(e[n],t));return e}const ab=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var sb,lb;(lb=sb||(sb={}))[lb.CONNECT=0]="CONNECT",lb[lb.DISCONNECT=1]="DISCONNECT",lb[lb.EVENT=2]="EVENT",lb[lb.ACK=3]="ACK",lb[lb.CONNECT_ERROR=4]="CONNECT_ERROR",lb[lb.BINARY_EVENT=5]="BINARY_EVENT",lb[lb.BINARY_ACK=6]="BINARY_ACK";class cb extends yg{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===sb.BINARY_EVENT;n||t.type===sb.BINARY_ACK?(t.type=n?sb.EVENT:sb.ACK,this.reconstructor=new ub(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!eb(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===sb[n.type])throw new Error("unknown packet type "+n.type);if(n.type===sb.BINARY_EVENT||n.type===sb.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(!db(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(!cb.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 sb.CONNECT:return pb(t);case sb.DISCONNECT:return void 0===t;case sb.CONNECT_ERROR:return"string"==typeof t||pb(t);case sb.EVENT:case sb.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ab.indexOf(t[0]));case sb.ACK:case sb.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ub{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=ob(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const db=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function pb(e){return"[object Object]"===Object.prototype.toString.call(e)}const hb=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:cb,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==sb.EVENT&&e.type!==sb.ACK||!tb(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===sb.EVENT?sb.BINARY_EVENT:sb.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==sb.BINARY_EVENT&&e.type!==sb.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=nb(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return sb}},Symbol.toStringTag,{value:"Module"}));function fb(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const mb=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class gb extends yg{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=[fb(e,"open",this.onopen.bind(this)),fb(e,"packet",this.onpacket.bind(this)),fb(e,"error",this.onerror.bind(this)),fb(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(mb.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:sb.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:sb.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 sb.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 sb.EVENT:case sb.BINARY_EVENT:this.onevent(e);break;case sb.ACK:case sb.BINARY_ACK:this.onack(e);break;case sb.DISCONNECT:this.ondisconnect();break;case sb.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:sb.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:sb.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 bb(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}bb.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)},bb.prototype.reset=function(){this.attempts=0},bb.prototype.setMin=function(e){this.ms=e},bb.prototype.setMax=function(e){this.max=e},bb.prototype.setJitter=function(e){this.jitter=e};class yb extends yg{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,Sg(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 bb({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||hb;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 Kg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=fb(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=fb(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(fb(e,"ping",this.onping.bind(this)),fb(e,"data",this.ondata.bind(this)),fb(e,"error",this.onerror.bind(this)),fb(e,"close",this.onclose.bind(this)),fb(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){vg(()=>{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 gb(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 vb={};function wb(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=Vg(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=vb[o]&&i in vb[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new yb(r,t):(vb[o]||(vb[o]=new yb(r,t)),s=vb[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(wb,{Manager:yb,Socket:gb,io:wb,connect:wb});const xb=Mm({proposalId:em().min(1),tool:em().min(1),title:em().optional(),summary:em().optional(),args:(kb=em(),_b=Nm(),new Dm({type:"record",keyType:kb,valueType:_b,...Ku(void 0)})).optional(),ownerOnly:/* @__PURE__ */Yh(Cm,void 0).optional()});var kb,_b;const Sb=Mm({proposalId:em().min(1),status:Rm(["confirmed","cancelled","expired"]).optional()}),Cb="chat_device_id";function Eb(){const e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if("function"==typeof e?.randomUUID)return e.randomUUID();if("function"==typeof e?.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=Array.from(t,e=>e.toString(16).padStart(2,"0"));return n.slice(0,4).join("")+"-"+n.slice(4,6).join("")+"-"+n.slice(6,8).join("")+"-"+n.slice(8,10).join("")+"-"+n.slice(10,16).join("")}return $t("[deviceId] Web Crypto API unavailable, falling back to Math.random()"),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const zb=Mm({id:em().optional(),type:Rm(["text","image","audio","location","system"]).default("text"),content:em().optional(),imageUrl:em().url().optional(),audioUrl:em().optional(),latitude:km().optional(),longitude:km().optional(),timestamp:em().optional(),sender:Rm(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Qh(Em).optional(),sources:Im(em()).optional()}),Nb=Mm({agentId:em().optional(),name:em().optional(),label:em().optional(),avatarUrl:em().optional(),variantKey:em().optional()}),Ab=Mm({imageUrl:em().url(),caption:em().optional(),alt:em().optional(),attribution:em().optional(),sourceUrl:em().url().optional(),license:em().optional()}),Tb=/USER_IDENTITY_REQUIRED|AUTH_EXPIRED|AUTH_INVALID|AUTH_REQUIRED|unauthorized/i;class Ib{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),$t("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?Ut():(this.isDisabled=!0,this.queue=[],Ut(t.status))}catch(t){this.isDisabled=!0,this.queue=[],Ut()}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}const Ob=e=>{const t=new Date(e.timestamp).getTime();return Number.isFinite(t)?t:0},Mb=e=>`${e.sender}|${(e=>{const t=e.content;return"string"==typeof t?t:""})(e).trim()}`;let Pb=null,Lb=null;function Db(e){Pb=e}function jb(e){Lb=e}const Rb=r(null);function Fb({children:e,defaultLocale:t,initialState:n,onStateChange:r,...o}){const[a,l]=i(n?.isOpen??!1),[c,u]=i(0),d=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:open"))},[r]),p=s(()=>{l(!1),r?.(!1),window.dispatchEvent(new CustomEvent("botuyo-chat:close"))},[r]),h=s(()=>{l(e=>{const t=!e;return t&&u(0),r?.(t),t}),window.dispatchEvent(new CustomEvent("botuyo-chat:toggle"))},[r]),f=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))},[r]),m=s(e=>{Pb?(Pb(e),Ut(0)):$t("sendMessage called but no handler registered")},[]),g=s(()=>{Lb?(Lb(),Ut()):$t("clearMessages called but no handler registered")},[]),v={isOpen:a,open:d,close:p,toggle:h,startCall:f,sendMessage:m,clearMessages:g,unreadCount:c},w=s((e,t)=>{"message:received"!==e||a||u(e=>e+1),o.onEvent?.(e,t)},[a,o]);/* @__PURE__ */
|
|
200
|
+
return kf(Tm,e,t)}const Om=/* @__PURE__ */Eu("ZodObject",(e,t)=>{Kp.init(e,t),Yf.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]=zf(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=zf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),ju(e,"shape",()=>t.shape),e.keyof=()=>Rm(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__ */ef(Am,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Vu(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=Fu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ru(this,"shape",n),n}});return Ju(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Vu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Fu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ru(this,"shape",n),n}});return Ju(e,n)}(e,t),e.merge=t=>function(e,t){const n=Fu(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Ru(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Ju(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 Ju(e,Fu(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 Ru(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=Fu(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 Ru(this,"shape",r),r},checks:[]});return Ju(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=Fu(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 Ru(this,"shape",o),o},checks:[]});return Ju(t,o)}($m,e,t[0]),e.required=(...t)=>function(e,t,n){const r=Fu(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 Ru(this,"shape",o),o}});return Ju(t,r)}(Zm,e,t[0])});function Mm(e,t){const n={type:"object",shape:e??{},...Ku(t)};return new Om(n)}const Pm=/* @__PURE__ */Eu("ZodUnion",(e,t)=>{Yp.init(e,t),Yf.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)=>zf(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__ */Eu("ZodIntersection",(e,t)=>{Qp.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=zf(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=zf(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)}),Dm=/* @__PURE__ */Eu("ZodRecord",(e,t)=>{th.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object";const a=i.keyType,s=a._zod.bag,l=s?.patterns;if("loose"===i.mode&&l&&l.size>0){const e=zf(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const t of l)o.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(o.propertyNames=zf(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=zf(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=a._zod.values;if(c){const e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(o.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType}),jm=/* @__PURE__ */Eu("ZodEnum",(e,t)=>{nh.init(e,t),Yf.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 jm({...t,checks:[],...Ku(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 jm({...t,checks:[],...Ku(r),entries:o})}});function Rm(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new jm({type:"enum",entries:n,...Ku(t)})}const Fm=/* @__PURE__ */Eu("ZodTransform",(e,t)=>{rh.init(e,t),Yf.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(nd(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(nd(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),$m=/* @__PURE__ */Eu("ZodOptional",(e,t)=>{ih.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Bm(e){return new $m({type:"optional",innerType:e})}const Um=/* @__PURE__ */Eu("ZodExactOptional",(e,t)=>{ah.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mf(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),qm=/* @__PURE__ */Eu("ZodNullable",(e,t)=>{sh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=zf(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 Vm(e){return new qm({type:"nullable",innerType:e})}const Wm=/* @__PURE__ */Eu("ZodDefault",(e,t)=>{lh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;zf(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)=>{uh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;zf(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}),Zm=/* @__PURE__ */Eu("ZodNonOptional",(e,t)=>{dh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;zf(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Jm=/* @__PURE__ */Eu("ZodCatch",(e,t)=>{hh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;zf(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}),Km=/* @__PURE__ */Eu("ZodPipe",(e,t)=>{fh.init(e,t),Yf.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;zf(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function Gm(e,t){return new Km({type:"pipe",in:e,out:t})}const Ym=/* @__PURE__ */Eu("ZodReadonly",(e,t)=>{gh.init(e,t),Yf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;zf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Qm=/* @__PURE__ */Eu("ZodCustom",(e,t)=>{yh.init(e,t),Yf.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)}),Xm=/* @__PURE__ */Object.create(null);Xm.open="0",Xm.close="1",Xm.ping="2",Xm.pong="3",Xm.message="4",Xm.upgrade="5",Xm.noop="6";const eg=/* @__PURE__ */Object.create(null);Object.keys(Xm).forEach(e=>{eg[Xm[e]]=e});const tg={type:"error",data:"parser error"},ng="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),rg="function"==typeof ArrayBuffer,og=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ig=({type:e,data:t},n,r)=>ng&&t instanceof Blob?n?r(t):ag(t,r):rg&&(t instanceof ArrayBuffer||og(t))?n?r(t):ag(new Blob([t]),r):r(Xm[e]+(t||"")),ag=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function sg(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let lg;const cg="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let cy=0;cy<64;cy++)cg["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(cy)]=cy;const ug="function"==typeof ArrayBuffer,dg=(e,t)=>{if("string"!=typeof e)return{type:"message",data:hg(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:pg(e.substring(1),t)}:eg[n]?e.length>1?{type:eg[n],data:e.substring(1)}:{type:eg[n]}:tg},pg=(e,t)=>{if(ug){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=cg[e.charCodeAt(t)],r=cg[e.charCodeAt(t+1)],o=cg[e.charCodeAt(t+2)],i=cg[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 hg(n,t)}return{base64:!0,data:e}},hg=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,fg=String.fromCharCode(30);let mg;function gg(e){return e.reduce((e,t)=>e+t.length,0)}function bg(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 yg(e){if(e)return function(e){for(var t in yg.prototype)e[t]=yg.prototype[t];return e}(e)}yg.prototype.on=yg.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},yg.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},yg.prototype.off=yg.prototype.removeListener=yg.prototype.removeAllListeners=yg.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},yg.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},yg.prototype.emitReserved=yg.prototype.emit,yg.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},yg.prototype.hasListeners=function(e){return!!this.listeners(e).length};const vg="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),wg="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function xg(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const kg=wg.setTimeout,_g=wg.clearTimeout;function Sg(e,t){t.useNativeTimers?(e.setTimeoutFn=kg.bind(wg),e.clearTimeoutFn=_g.bind(wg)):(e.setTimeoutFn=wg.setTimeout.bind(wg),e.clearTimeoutFn=wg.clearTimeout.bind(wg))}function Cg(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 Eg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class zg extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Ng extends yg{constructor(e){super(),this.writable=!1,Sg(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 zg(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=dg(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 Ag extends Ng{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(fg),r=[];for(let o=0;o<n.length;o++){const e=dg(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)=>{ig(e,!1,e=>{r[i]=e,++o===n&&t(r.join(fg))})})})(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]=Eg()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Tg=!1;try{Tg="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(ly){}const Ig=Tg;function Og(){}class Mg extends Ag{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 Pg extends yg{constructor(e,t,n){super(),this.createRequest=e,Sg(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=xg(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=Pg.requestsCount++,Pg.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 Pg.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 Lg(){for(let e in Pg.requests)Pg.requests.hasOwnProperty(e)&&Pg.requests[e].abort()}Pg.requestsCount=0,Pg.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Lg):"function"==typeof addEventListener&&addEventListener("onpagehide"in wg?"pagehide":"unload",Lg,!1));const Dg=function(){const e=jg({xdomain:!1});return e&&null!==e.responseType}();function jg(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Ig))return new XMLHttpRequest}catch(n){}if(!t)try{return new(wg[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const Rg="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Fg extends Ng{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Rg?{}:xg(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(ly){return this.emitReserved("error",ly)}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;ig(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&vg(()=>{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]=Eg()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const $g=wg.WebSocket||wg.MozWebSocket,Bg={websocket:class extends Fg{createSocket(e,t,n){return Rg?new $g(e,t,n):t?new $g(e,t):new $g(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Ng{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(ly){return this.emitReserved("error",ly)}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){mg||(mg=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(gg(n)<1)break;const e=bg(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(gg(n)<2)break;const e=bg(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(gg(n)<8)break;const e=bg(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(tg);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(gg(n)<o)break;const e=bg(n,o);s.enqueue(dg(i?e:mg.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(tg);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){ng&&e.data instanceof Blob?e.data.arrayBuffer().then(sg).then(t):rg&&(e.data instanceof ArrayBuffer||og(e.data))?t(sg(e.data)):ig(e,!1,e=>{lg||(lg=new TextEncoder),t(lg.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&&vg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Mg{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Dg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Pg(jg,this.uri(),e)}}},Ug=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Vg(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=Ug.exec(e||""),i={},a=14;for(;a--;)i[qg[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 Wg="function"==typeof addEventListener&&"function"==typeof removeEventListener,Hg=[];Wg&&addEventListener("offline",()=>{Hg.forEach(e=>e())},!1);class Zg extends yg{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=Vg(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=Vg(t.host).host);Sg(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)),Wg&&(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&&Zg.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",Zg.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+=Cg(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,vg(()=>{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(Zg.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(),Wg&&(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}}}Zg.protocol=4;class Jg extends Zg{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;Zg.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;Zg.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 Kg=class extends Jg{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=>Bg[e]).filter(e=>!!e)),super(e,n)}};const Gg="function"==typeof ArrayBuffer,Yg=Object.prototype.toString,Qg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Yg.call(Blob),Xg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Yg.call(File);function eb(e){return Gg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Qg&&e instanceof Blob||Xg&&e instanceof File}function tb(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(tb(e[t]))return!0;return!1}if(eb(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return tb(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&tb(e[n]))return!0;return!1}function nb(e){const t=[],n=e.data,r=e;return r.data=rb(n,t),r.attachments=t.length,{packet:r,buffers:t}}function rb(e,t){if(!e)return e;if(eb(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]=rb(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]=rb(e[r],t));return n}return e}function ob(e,t){return e.data=ib(e.data,t),delete e.attachments,e}function ib(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]=ib(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ib(e[n],t));return e}const ab=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var sb,lb;(lb=sb||(sb={}))[lb.CONNECT=0]="CONNECT",lb[lb.DISCONNECT=1]="DISCONNECT",lb[lb.EVENT=2]="EVENT",lb[lb.ACK=3]="ACK",lb[lb.CONNECT_ERROR=4]="CONNECT_ERROR",lb[lb.BINARY_EVENT=5]="BINARY_EVENT",lb[lb.BINARY_ACK=6]="BINARY_ACK";class cb extends yg{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===sb.BINARY_EVENT;n||t.type===sb.BINARY_ACK?(t.type=n?sb.EVENT:sb.ACK,this.reconstructor=new ub(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!eb(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===sb[n.type])throw new Error("unknown packet type "+n.type);if(n.type===sb.BINARY_EVENT||n.type===sb.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(!db(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(!cb.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 sb.CONNECT:return pb(t);case sb.DISCONNECT:return void 0===t;case sb.CONNECT_ERROR:return"string"==typeof t||pb(t);case sb.EVENT:case sb.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ab.indexOf(t[0]));case sb.ACK:case sb.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ub{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=ob(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const db=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function pb(e){return"[object Object]"===Object.prototype.toString.call(e)}const hb=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:cb,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==sb.EVENT&&e.type!==sb.ACK||!tb(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===sb.EVENT?sb.BINARY_EVENT:sb.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==sb.BINARY_EVENT&&e.type!==sb.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=nb(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return sb}},Symbol.toStringTag,{value:"Module"}));function fb(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const mb=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class gb extends yg{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=[fb(e,"open",this.onopen.bind(this)),fb(e,"packet",this.onpacket.bind(this)),fb(e,"error",this.onerror.bind(this)),fb(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(mb.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:sb.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:sb.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 sb.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 sb.EVENT:case sb.BINARY_EVENT:this.onevent(e);break;case sb.ACK:case sb.BINARY_ACK:this.onack(e);break;case sb.DISCONNECT:this.ondisconnect();break;case sb.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:sb.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:sb.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 bb(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}bb.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)},bb.prototype.reset=function(){this.attempts=0},bb.prototype.setMin=function(e){this.ms=e},bb.prototype.setMax=function(e){this.max=e},bb.prototype.setJitter=function(e){this.jitter=e};class yb extends yg{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,Sg(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 bb({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||hb;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 Kg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=fb(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=fb(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(fb(e,"ping",this.onping.bind(this)),fb(e,"data",this.ondata.bind(this)),fb(e,"error",this.onerror.bind(this)),fb(e,"close",this.onclose.bind(this)),fb(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){vg(()=>{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 gb(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 vb={};function wb(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=Vg(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=vb[o]&&i in vb[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new yb(r,t):(vb[o]||(vb[o]=new yb(r,t)),s=vb[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(wb,{Manager:yb,Socket:gb,io:wb,connect:wb});const xb=Mm({proposalId:em().min(1),tool:em().min(1),title:em().optional(),summary:em().optional(),args:(kb=em(),_b=Nm(),new Dm({type:"record",keyType:kb,valueType:_b,...Ku(void 0)})).optional(),ownerOnly:/* @__PURE__ */Yh(Cm,void 0).optional()});var kb,_b;const Sb=Mm({proposalId:em().min(1),status:Rm(["confirmed","cancelled","expired"]).optional()}),Cb="chat_device_id";function Eb(){const e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if("function"==typeof e?.randomUUID)return e.randomUUID();if("function"==typeof e?.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=Array.from(t,e=>e.toString(16).padStart(2,"0"));return n.slice(0,4).join("")+"-"+n.slice(4,6).join("")+"-"+n.slice(6,8).join("")+"-"+n.slice(8,10).join("")+"-"+n.slice(10,16).join("")}return $t("[deviceId] Web Crypto API unavailable, falling back to Math.random()"),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const zb=Mm({id:em().optional(),type:Rm(["text","image","audio","location","system"]).default("text"),content:em().optional(),imageUrl:em().url().optional(),audioUrl:em().optional(),latitude:km().optional(),longitude:km().optional(),timestamp:em().optional(),sender:Rm(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Qh(Em).optional(),sources:Im(em()).optional()}),Nb=Mm({agentId:em().optional(),name:em().optional(),label:em().optional(),avatarUrl:em().optional(),variantKey:em().optional()}),Ab=Mm({imageUrl:em().url(),caption:em().optional(),alt:em().optional(),attribution:em().optional(),sourceUrl:em().url().optional(),license:em().optional()}),Tb=/USER_IDENTITY_REQUIRED|AUTH_EXPIRED|AUTH_INVALID|AUTH_REQUIRED|unauthorized/i;class Ib{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),$t("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?Ut():(this.isDisabled=!0,this.queue=[],Ut(t.status))}catch(t){this.isDisabled=!0,this.queue=[],Ut()}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}const Ob=e=>{const t=new Date(e.timestamp).getTime();return Number.isFinite(t)?t:0},Mb=e=>`${e.sender}|${(e=>{const t=e.content;return"string"==typeof t?t:""})(e).trim()}`;let Pb=null,Lb=null;function Db(e){Pb=e}function jb(e){Lb=e}const Rb=r(null);function Fb({children:e,defaultLocale:t,initialState:n,onStateChange:r,...o}){const[a,l]=i(n?.isOpen??!1),[c,u]=i(0),d=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:open"))},[r]),p=s(()=>{l(!1),r?.(!1),window.dispatchEvent(new CustomEvent("botuyo-chat:close"))},[r]),h=s(()=>{l(e=>{const t=!e;return t&&u(0),r?.(t),t}),window.dispatchEvent(new CustomEvent("botuyo-chat:toggle"))},[r]),f=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))},[r]),m=s(e=>{Pb?(Pb(e),Ut(0)):$t("sendMessage called but no handler registered")},[]),g=s(()=>{Lb?(Lb(),Ut()):$t("clearMessages called but no handler registered")},[]),v={isOpen:a,open:d,close:p,toggle:h,startCall:f,sendMessage:m,clearMessages:g,unreadCount:c},w=s((e,t)=>{"message:received"!==e||a||u(e=>e+1),o.onEvent?.(e,t)},[a,o]);/* @__PURE__ */
|
|
201
201
|
return y(Rb.Provider,{value:v,children:[e,
|
|
202
202
|
/* @__PURE__ */b(Hb,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:w})]})}function $b(){const e=o(Rb);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const Bb=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function Ub(e){const{apiKey:t,apiBaseUrl:r,agentId:o,pageContext:l,includeSEOMetadata:c=!1,theme:d,userContext:p,onLogin:h,onNavigate:m,onEvent:b,onStateChange:y,getUserToken:v,onAuthRequired:w,onThemeUpdate:x}=e,[k,_]=i(0),S=f(0),C=f(!1),{t:E}=j(),z=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Ib(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),N=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||Vt,h=l||Wt;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 $t("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),qt("Notification permission:",e),"granted"===e}catch(e){return Bt("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){Bt("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=>{Ut(0)})}catch(n){Bt("Error playing sound:",n)}},[e,t]),y=s(e=>{g(e),b()},[g,b]);return{permission:c,requestPermission:m,notify:g,playSound:b,notifyWithSound:y}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:d?.botName||"BotUyo",logoUrl:d?.logoUrl}),A=function(e=10,t=6e4){const n=f([]);return{isAllowed:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),!(n.current.length>=e||(n.current.push(r),0))},[e,t]),getRemainingAttempts:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),Math.max(0,e-n.current.length)},[e,t]),getTimeUntilReset:s(()=>{if(0===n.current.length)return 0;const e=Date.now(),r=n.current[0],o=t-(e-r);return Math.max(0,o)},[t]),reset:s(()=>{n.current=[]},[])}}(10,6e4),{state:T,actions:I}=function(e,t="default"){const[r,o]=g(Cu,_u),[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 ku.has(n)||ku.set(n,new xu(e,t)),ku.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){$t("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){Bt("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){Bt("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){Bt("Chat: Fallback persistence failed",t)}}},500);return()=>clearTimeout(e)},[r.isOpen,r.messages,r.sessionId,l]);const p=s(e=>{o({type:"ADD_MESSAGE",payload:e})},[]),h=s(()=>o({type:"TOGGLE_WINDOW"}),[]),f=s(()=>o({type:"OPEN_WINDOW"}),[]),m=s(()=>o({type:"CLOSE_WINDOW"}),[]),b=s(e=>o({type:"SET_CONNECTED",payload:e}),[]),y=s(e=>o({type:"SET_TYPING",payload:e}),[]),v=s(e=>o({type:"SET_MESSAGES",payload:e}),[]),w=s(e=>o({type:"SET_ERROR",payload:e}),[]),x=s(e=>o({type:"SET_SESSION_ID",payload:e}),[]),k=s(()=>{localStorage.removeItem(u),o({type:"CLEAR_CHAT"})},[]),_=s(()=>{o({type:"SET_MESSAGES",payload:[]})},[]),S=s((e,t)=>o({type:"ANSWER_QUIZ",payload:{messageId:e,buttonId:t}}),[]),C=s((e,t)=>o({type:"RESOLVE_PROPOSAL",payload:{proposalId:e,status:t}}),[]);return{state:r,isHydrated:l,actions:{toggleWindow:h,openWindow:f,closeWindow:m,setConnected:b,setTyping:y,addMessage:p,setMessages:v,setError:w,setSessionId:x,clearChat:k,clearMessages:_,answerQuiz:S,resolveProposal:C}}}(t,o),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),M=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(Cb);if(e)return e;const t=Eb();return localStorage.setItem(Cb,t),t}catch{return $t("localStorage not available, using session-only device ID"),Eb()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=zb.safeParse(e),r=t.success&&t.data.id?t.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=t.success&&t.data.sender?t.data.sender:"bot",i=t.success&&t.data.timestamp?new Date(t.data.timestamp):/* @__PURE__ */new Date,a=t.success?t.data:{type:"text"};switch(a.type){case"image":return{id:r,type:"image",sender:o,timestamp:i,imageUrl:a.imageUrl||a.content||"",altText:"Imagen enviada"};case"audio":{const e=a.audioUrl||"";return{id:r,type:"audio",sender:o,timestamp:i,content:e.startsWith("http://")||e.startsWith("https://")?e:e?`${n}/api/voice/audio/${r}`:a.content||"",text:a.content||void 0}}case"location":return{id:r,type:"location",sender:o,timestamp:i,latitude:Number(a.latitude||0),longitude:Number(a.longitude||0),name:a.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:i,content:String(a.content||"")};default:return{id:r,type:"text",sender:o,timestamp:i,content:String(a.content||"Sin contenido"),emotion:a.emotion,...a.sources?.length?{sources:a.sources}:{}}}},[]),w=s(()=>{if(!t||!n)return;if(d.current?.connected)return;h(!0);const e=e=>{const o=wb(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});o.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),o.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),o.on("connect_error",e=>{h(!1);const n=String(e?.data instanceof Object?e?.data?.code:e?.data??e?.message??"");if(Tb.test(n)||Tb.test(e?.message??"")){c.current.onAuthRequired?.();const e=c.current.getUserToken;e&&e().then(e=>{d.current&&(d.current.auth={apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata})}).catch(e=>Bt("[useChatSocket] Token refresh failed:",e))}c.current.onError(`Error de conexión: ${e.message}`)}),o.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),o.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){Bt("ChatSocket Error processing bot_message:",t)}}),o.on("chat_history",e=>{if(e.messages&&Array.isArray(e.messages))if(c.current.onHistoryLoaded){const t=e.messages.map(e=>{try{return v(e)}catch(t){return Ut(),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){Ut()}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),o.on("bot_typing",e=>c.current.onTyping(e));const i=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};o.on("onboarding:command",e=>i(e)),o.on("form:command",e=>i(e)),o.on("request_form_state",()=>{i({type:"botuyo-request-form-state"})}),o.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),o.on("custom_event",e=>{if(i({type:"botuyo-custom-event",...e}),"quiz_question"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const{question:t,buttons:n}=e.data;if(t&&n?.length){const e={id:`quiz-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"buttons",sender:"bot",timestamp:/* @__PURE__ */new Date,content:t,buttons:n};c.current.onMessage(e)}}if("show_image"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const t=Ab.safeParse(e.data);if(t.success){const e=t.data,n={id:`img-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"image",sender:"bot",timestamp:/* @__PURE__ */new Date,imageUrl:e.imageUrl,altText:e.alt||e.caption||"Imagen",...e.caption?{caption:e.caption}:{},...e.attribution?{attribution:e.attribution}:{},...e.sourceUrl?{sourceUrl:e.sourceUrl}:{}};c.current.onMessage(n)}else Ut()}if("agent_switched"===e?.eventName&&e?.data){const t=Nb.safeParse(e.data);t.success?c.current.onAgentSwitched?.(t.data):Ut()}if("tool_proposal"===e?.eventName&&e?.data){const t=xb.safeParse(e.data);if(t.success){const e=t.data,n={id:`proposal-${e.proposalId}`,type:"tool_proposal",sender:"bot",timestamp:/* @__PURE__ */new Date,proposalId:e.proposalId,toolName:e.tool,title:e.title,summary:e.summary,ownerOnly:e.ownerOnly,status:"pending"};c.current.onMessage(n)}else Ut()}if(("tool_proposal_resolved"===e?.eventName||"tool_proposal_expired"===e?.eventName)&&e?.data){const t=Sb.safeParse(e.data);if(t.success){const n="tool_proposal_expired"===e.eventName?"expired":t.data.status??"confirmed";c.current.onToolProposalResolved?.(t.data.proposalId,n)}else Ut()}});const a=e=>{const{type:t}=e.data||{};"botuyo-onboarding-state"!==t&&"botuyo-form-state"!==t||o.emit("form_state",e.data)};window.addEventListener("message",a),d.current=o,o.__formCleanup=()=>window.removeEventListener("message",a)},o=c.current.getUserToken;o?o().then(t=>e(t)).catch(t=>{Bt("[useChatSocket] getUserToken failed:",t),c.current.onAuthRequired?.(),e(l?.token)}):e(l?.token)},[t,n]),x=s(()=>{d.current&&(d.current.disconnect(),d.current=null,g(!1))},[]),k=f(w);k.current=w,a(()=>(k.current(),()=>{d.current&&(d.current.disconnect(),d.current=null)}),[]);const _=f([]),S=f([]),C=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),E=s(()=>{if(d.current?.connected)for(;_.current.length>0;){const e=_.current.shift();d.current.emit("user_message",e)}},[]);a(()=>{m&&E()},[m,E]),a(()=>{if(!m)return;const e=setInterval(()=>{const e=Date.now();S.current=S.current.filter(t=>e<t.nextRetryAt||(t.attempts>=t.maxAttempts?(c.current.onEvent?.("message_failed",{id:t.id,payload:t.payload}),Bt("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(()=>lc(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,confirmProposal:s(e=>{d.current?.emit("tool_confirm",{proposalId:e})},[]),rejectProposal:s(e=>{d.current?.emit("tool_reject",{proposalId:e})},[])}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>O?{...l||{},seo:{...O||{}}}:l,[l,O]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=S.current>0?t-S.current:void 0;S.current=t,I.addMessage(e),z.trackMessageReceived(e.type,n),T.isOpen||"bot"!==e.sender||(_(e=>e+1),N.notifyWithSound(e))},[I,T.isOpen,z,N]),onConnected:s((e,t)=>{I.setConnected(!0),I.setSessionId(e),z.trackConnectionStatus(!0),t&&x&&x(t),t&&b&&b("backend_config",t)},[I,b,x,z]),onDisconnected:s(()=>{I.setConnected(!1),z.trackConnectionStatus(!1)},[I,z]),onTyping:s(e=>I.setTyping(e),[I]),onError:s(e=>{I.setError(e),z.trackError(e)},[I,z]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:x,onAgentSwitched:s(e=>{const t=function(e,t){const n=(e||"").trim(),r=(t||"").trim();return n&&r&&!n.toLowerCase().includes(r.toLowerCase())?`${n} · ${r}`:n||r}(e.name,e.label);x&&x(n=>({...n||{},...t?{botName:t}:{},...e.avatarUrl?{logoUrl:e.avatarUrl}:{}})),t&&I.addMessage({id:`agent-switched-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"system",sender:"system",timestamp:/* @__PURE__ */new Date,content:E("agent_switched",{name:t})})},[x,I,E]),onHistoryLoaded:s(e=>{0!==e.length&&I.setMessages(function(e,t){if(!t||0===t.length)return e;const n=t.reduce((e,t)=>Math.max(e,Ob(t)),0),r=new Set(t.map(e=>e.id)),o=new Set(t.map(Mb)),i=e.filter(e=>!r.has(e.id)&&Ob(e)>n&&!o.has(Mb(e)));return[...t,...i].sort((e,t)=>Ob(e)-Ob(t))}(T.messages,e))},[T.messages,I]),getUserToken:v,onAuthRequired:w,onToolProposalResolved:s((e,t)=>I.resolveProposal(e,t),[I]),isVoiceCallActive:s(()=>C.current,[])}),P=s(e=>{C.current=e},[]),L=u(()=>function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("buttons"===n.type&&!n.answered)return n}return null}(T.messages),[T.messages]),D=f(L);a(()=>{D.current=L},[L]);const R=s(()=>{Ut(0,T.isOpen),T.isOpen?(I.closeWindow(),z.trackClose(),y?.(!1),Ut()):(I.openWindow(),_(0),z.trackOpen(),y?.(!0),Ut())},[T.isOpen,I,y,z]),F=s(e=>{if(!A.isAllowed()){const e=A.getTimeUntilReset(),t=Math.ceil(e/1e3);return void I.setError(E("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};I.addMessage(t),z.trackMessageSent("text"),M.sendMessage(e,"text"),D.current&&I.answerQuiz(D.current.id)},[I,M,A,z,E]),$=s((e,t,n)=>{I.answerQuiz(e.id,n),M.sendMessage(`Answer: ${t}`,"text"),z.trackMessageSent("text")},[I,M,z]),B=s(e=>{I.resolveProposal(e,"confirmed"),M.confirmProposal(e)},[I,M]),U=s(e=>{I.resolveProposal(e,"cancelled"),M.rejectProposal(e)},[I,M]),q=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}`},I.addMessage(n);const r=await Bb(e);M.sendMessage(r,t)},[I,M]),V=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"};I.addMessage(t),M.sendMessage(JSON.stringify(e),"location")},[I,M]);a(()=>{const e=()=>{T.isOpen||I.openWindow()},t=()=>{T.isOpen&&I.closeWindow()},n=()=>{T.isOpen?I.closeWindow():I.openWindow()},r=e=>{e.detail?.message&&F(e.detail.message)},o=()=>{T.isOpen||I.openWindow()};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),window.addEventListener("botuyo-chat:start-call",o),window.addEventListener("botuyo-chat:send-message",r),()=>{window.removeEventListener("botuyo-chat:open",e),window.removeEventListener("botuyo-chat:close",t),window.removeEventListener("botuyo-chat:toggle",n),window.removeEventListener("botuyo-chat:start-call",o),window.removeEventListener("botuyo-chat:send-message",r)}},[T.isOpen,I,F]),a(()=>(Db(F),()=>Db(null)),[F]);const W=s(()=>{I.clearMessages(),qt("Chat history cleared")},[I]);a(()=>(jb(W),()=>jb(null)),[W]);const H=u(()=>{if(T.isTyping)return"thinking";const e=[...T.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[T.isTyping,T.messages]);return{state:T,actions:I,unreadCount:k,currentBotEmotion:H,isConnected:M.isConnected,getSocket:M.getSocket,activeQuiz:L,handleToggle:R,handleSendText:F,handleSendAttachment:q,handleSendLocation:V,handleQuizAnswer:$,handleConfirmProposal:B,handleCancelProposal:U,setVoiceCallActive:P}}function qb({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=D.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),Ut(),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function Vb(e){const{apiKey:t,apiBaseUrl:n="https://api.botuyo.com",agentId:r,pageContext:o,includeSEOMetadata:l=!1,theme:c,mediaConfig:d,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,initialOpen:k=!1,hideLauncher:_=!1,voiceFirst:S=!1}=e,C=f(null),E=cc(),z=function(e){const[t,n]=i(!1);return a(()=>{let t=null;const r=()=>{if(!e.current)return;const t=!!e.current.parentElement?.closest(".dark"),r=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),o=document.getElementById("botuyo-chat-widget-root"),i=!!o?.parentElement?.closest(".dark"),a=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),l="dark"===document.documentElement.getAttribute("data-theme"),c="dark"===document.body.getAttribute("data-theme"),u=!!e.current.parentElement?.closest('[data-theme="dark"]'),d=window.matchMedia("(prefers-color-scheme: dark)").matches,p=t||r||i||a||s||l||c||u||d;e.current&&(p?e.current.classList.add("dark"):e.current.classList.remove("dark")),n(p)};r();const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r();o.addEventListener("change",i);const a=new MutationObserver(()=>{r()}),s=document.getElementById("botuyo-chat-widget-root");s&&(a.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(a.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=s.parentElement)),a.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),a.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let l=e.current?.parentElement;for(;l;)a.observe(l,{attributes:!0,attributeFilter:["class","data-theme"]}),l=l.parentElement;const c=setInterval(()=>{const e=document.getElementById("botuyo-chat-widget-root");e&&e.parentElement!==t&&(t&&e.parentElement&&(a.observe(e.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=e.parentElement),r())},100);return()=>{a.disconnect(),o.removeEventListener("change",i),clearInterval(c)}},[e]),t}(C),[N,A]=i(),{mergedTheme:T,mergedStyles:I,getContainerStyle:O}=function(e,t){const n=function(){const[e,t]=i(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return a(()=>{const e=window.matchMedia("(prefers-contrast: high)"),n=window.matchMedia("(prefers-contrast: more)"),r=e=>{t(e.matches)};return e.addEventListener("change",r),n.addEventListener("change",r),()=>{e.removeEventListener("change",r),n.removeEventListener("change",r)}},[]),e}(),r=u(()=>{const r=function(e,t){const n={...It,...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:{...Gc,...e?.bubbleStyles?.radius},bot:{...Yc,...e?.bubbleStyles?.bot},user:{...Qc,...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,N);a(()=>{T.isHidden&&console.warn('[BotUyo] ⚠️ El agente (o Flow) de IA asociado a esta API Key se encuentra pausado o en estado "boceto" (draft). El widget no se mostrará hasta que lo publiques dentro de la plataforma BotUyo.')},[T.isHidden]);const{state:M,actions:P,unreadCount:L,currentBotEmotion:D,isConnected:j,handleToggle:R,handleSendText:F,handleSendAttachment:$,handleSendLocation:B,getSocket:U,activeQuiz:q,handleQuizAnswer:V,handleConfirmProposal:W,handleCancelProposal:H,setVoiceCallActive:Z}=Ub({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,onThemeUpdate:A}),J=f(!1);a(()=>{k&&N&&!J.current&&(J.current=!0,M.isOpen||P.openWindow())},[k,N,M.isOpen,P]);const K=u(()=>{const e={...d||{}},t=N;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,N]),G=s(()=>{P.closeWindow()},[P]),Y=s(e=>{e.stopPropagation()},[]),Q=O(M.isOpen,E,c?.position),X=u(()=>{const e={"--background":"0 0% 100%","--foreground":"240 10% 3.9%","--card":"0 0% 100%","--card-foreground":"240 10% 3.9%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 4.8% 95.9%","--muted-foreground":"240 3.8% 46.1%","--border":"240 5.9% 90%","--destructive":"0 84.2% 60.2%","--radius":"0.5rem","--window-border-radius":"24px","--launcher-border-radius":"50%","--window-height":"700px","--window-bottom":"24px","--spacing-1":"0.25rem","--spacing-2":"0.5rem","--spacing-3":"0.75rem","--spacing-4":"1rem","--spacing-5":"0.75rem","--spacing-6":"1.5rem","--spacing-7":"1.75rem","--spacing-8":"2rem"};if(!T.cssVariables)return e;let t={...T.cssVariables};if(z){const e=N?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Ot,...e,...n}}const n={...e};return t.background&&(n["--background"]=t.background),t.foreground&&(n["--foreground"]=t.foreground),t.card&&(n["--card"]=t.card),t.cardForeground&&(n["--card-foreground"]=t.cardForeground),t.primary&&(n["--primary"]=t.primary),t.primaryForeground&&(n["--primary-foreground"]=t.primaryForeground),t.muted&&(n["--muted"]=t.muted),t.mutedForeground&&(n["--muted-foreground"]=t.mutedForeground),t.border&&(n["--border"]=t.border),t.destructive&&(n["--destructive"]=t.destructive),t.radius&&(n["--radius"]=t.radius),t.windowBorderRadius&&(n["--window-border-radius"]=t.windowBorderRadius),t.launcherBorderRadius&&(n["--launcher-border-radius"]=t.launcherBorderRadius),t.windowHeight&&(n["--window-height"]=t.windowHeight),t.windowBottom&&(n["--window-bottom"]=t.windowBottom),t.spacing1&&(n["--spacing-1"]=t.spacing1),t.spacing2&&(n["--spacing-2"]=t.spacing2),t.spacing3&&(n["--spacing-3"]=t.spacing3),t.spacing4&&(n["--spacing-4"]=t.spacing4),t.spacing5&&(n["--spacing-5"]=t.spacing5),t.spacing6&&(n["--spacing-6"]=t.spacing6),t.spacing7&&(n["--spacing-7"]=t.spacing7),t.spacing8&&(n["--spacing-8"]=t.spacing8),n},[T.cssVariables,z,N,c?.darkCssVariables]),ee=c?.voiceNoiseGate??N?.voiceNoiseGate,te=u(()=>({noiseGate:ee}),[ee]),[ne,re]=i(!1);return a(()=>{S&&j&&re(!0)},[S,j]),T.isHidden?null:N?S?/* @__PURE__ */b("div",{ref:C,id:"botuyo-chat-widget-root",className:"botuyo-chat-widget",style:{position:"fixed",inset:0,zIndex:2147483e3,...X},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,children:/* @__PURE__ */b(Kc,{children:/* @__PURE__ */b(Zc,{isOpen:ne,onClose:()=>g?.("voice_first_ended",{}),onCallEnded:e=>g?.("voice_call_ended",{reason:e}),primaryColor:Mt(T),avatars:c?.avatars||N?.avatars||N?.avatarAnimations||{},logoUrl:T.logoUrl,avatar3dUrl:c?.avatar3dUrl||N?.avatar3dUrl,voiceConfig:te,getSocket:U})})}):/* @__PURE__ */y("div",{ref:C,id:"botuyo-chat-widget-root",className:Tt("botuyo-chat-widget flex flex-col",!E&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...Q,...X,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:[
|
|
203
203
|
/* @__PURE__ */b("div",{className:Tt("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",E?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",M.isOpen?"opacity-100 scale-100 h-full w-full translate-y-0 pointer-events-auto":"opacity-0 scale-[0.85] pointer-events-none translate-y-8 h-0 w-0"),style:{pointerEvents:M.isOpen?"auto":"none"},onMouseDown:Y,onTouchStart:Y,children:/* @__PURE__ */b(Kc,{children:/* @__PURE__ */b(Jc,{isOpen:M.isOpen,isConnected:j,isTyping:M.isTyping,messages:M.messages,onClose:G,onSendMessage:F,onSendAttachment:$,onSendLocation:B,botName:T.botName,logoUrl:T.logoUrl,welcomeMessage:T.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||N?.inputPlaceholder,position:c?.position,bubbleStyles:I,avatars:c?.avatars||N?.avatars||N?.avatarAnimations||{},mediaConfig:K,theme:T,avatar3dUrl:c?.avatar3dUrl||N?.avatar3dUrl,voiceConfig:te,getSocket:U,suggestedQuestions:N?.suggestedQuestions,activeQuiz:q,onQuizAnswer:V,onProposalAction:(e,t)=>"confirm"===t?W(e):H(e),onVoiceActiveChange:Z})})}),!_&&/* @__PURE__ */b("div",{className:Tt(M.isOpen?"hidden":"block",!E&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:Y,onTouchStart:Y,children:/* @__PURE__ */b(Zt,{isOpen:M.isOpen,onClick:R,unreadCount:L,position:c?.position||"bottom-right",primaryColor:Mt(T),logoUrl:T.logoUrl,starterPrompt:c?.starterPrompt||N?.starterPrompt,avatars:c?.avatars||N?.avatars||N?.avatarAnimations||{},emotion:D,styles:I,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??N?.avatarScale,showPromptAvatar:c?.showPromptAvatar??N?.showPromptAvatar})})]}):null}function Wb(e){/* @__PURE__ */
|
|
204
204
|
return b(Rt,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(Vb,{...e})})}function Hb(e){/* @__PURE__ */
|
|
205
205
|
return b(P,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b(qb,{children:/* @__PURE__ */b(Wb,{...e})})})}const Zb=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:Hb,ChatWidgetInner:Vb,ChatWidgetWithProviders:Wb},Symbol.toStringTag,{value:"Module"}));function Jb({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__ */
|
|
206
|
-
return b("div",{style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:/* @__PURE__ */b(P,{defaultLocale:r,children:/* @__PURE__ */b(Wb,{...i})})},n)}function Kb({url:e,autoRotate:t,hasCustomCamera:n,frameRef:r,onLoaded:o,onError:i}){const s=f(null),l=f(null),c=f(null),u=f(0),d=f(0),p=f(0),{scene:h,camera:m}=_();return a(()=>{const t=new z;return t.register(e=>new C(e)),t.load(e,e=>{const t=e.userData?.vrm;if(t){s.current=t,t.scene.rotation.y=Math.PI;const e=(new E.Box3).setFromObject(t.scene).getSize(new E.Vector3);if(p.current=0,d.current=Math.PI,h.add(t.scene),!n){const t=.75*e.y,n=m.fov*(Math.PI/180),o=.55*e.y*.5/Math.tan(n/2)*1.3;m.position.set(0,t,o),m.lookAt(0,t,0),r.current.targetY=t}t.lookAt&&(t.lookAt.target=m)}else{const t=e.scene;t.updateMatrixWorld(!0);const o=(new E.Box3).setFromObject(t),i=o.getCenter(new E.Vector3),a=o.getSize(new E.Vector3),s=new E.Group;if(t.position.sub(i),s.add(t),l.current=s,p.current=0,d.current=0,h.add(s),!n){const e=
|
|
206
|
+
return b("div",{style:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},children:/* @__PURE__ */b(P,{defaultLocale:r,children:/* @__PURE__ */b(Wb,{...i})})},n)}function Kb(e,t){const n=e.y>0?e.y:1,r=(t>0?t:30)*Math.PI/180,o=.3*n;return{position:[0,o,.5*n/Math.tan(r/2)*1.2],target:[0,o,0]}}const Gb=/idle|breath|relax/i;function Yb(e){if(!e||0===e.length)return null;for(const t of e)if(t&&Gb.test(t.name??""))return t;return null}function Qb({url:e,autoRotate:t,hasCustomCamera:n,frameRef:r,onLoaded:o,onError:i}){const s=f(null),l=f(null),c=f(null),u=f(0),d=f(0),p=f(0),{scene:h,camera:m}=_();return a(()=>{const t=new z;return t.register(e=>new C(e)),t.load(e,e=>{const t=e.userData?.vrm;if(t){s.current=t,t.scene.rotation.y=Math.PI;const e=(new E.Box3).setFromObject(t.scene).getSize(new E.Vector3);if(p.current=0,d.current=Math.PI,h.add(t.scene),!n){const t=.75*e.y,n=m.fov*(Math.PI/180),o=.55*e.y*.5/Math.tan(n/2)*1.3;m.position.set(0,t,o),m.lookAt(0,t,0),r.current.targetY=t}t.lookAt&&(t.lookAt.target=m)}else{const t=e.scene;t.updateMatrixWorld(!0);const o=(new E.Box3).setFromObject(t),i=o.getCenter(new E.Vector3),a=o.getSize(new E.Vector3),s=new E.Group;if(t.position.sub(i),s.add(t),l.current=s,p.current=0,d.current=0,h.add(s),!n){const e=Kb({x:a.x,y:a.y,z:a.z},m.fov);m.position.set(...e.position),m.lookAt(...e.target),r.current.targetY=e.target[1]}const u=Yb(e.animations);if(u){const e=new E.AnimationMixer(t);c.current=e,e.clipAction(u).play()}}o?.()},void 0,e=>{Bt("[Avatar3DPreview] Failed to load model:",e),i?.(e)}),()=>{s.current&&(h.remove(s.current.scene),s.current=null),l.current&&(h.remove(l.current),l.current=null),c.current&&(c.current.stopAllAction(),c.current=null)}},[e,h,m,t,n,r,o,i]),S((e,n)=>{const r=Math.min(n,.1);u.current+=1.2*r;const o=t?.5*r:0;if(l.current){c.current&&c.current.update(r);const e=l.current,n=.003*Math.sin(u.current);e.position.y=p.current+n,t&&(d.current-=o);const i=.02*Math.sin(.3*u.current);return void(e.rotation.y=d.current+i)}const i=s.current;if(i){const e=.003*Math.sin(u.current);if(i.scene.position.y=p.current+e,t&&(d.current-=o,i.scene.rotation.y=d.current),i.humanoid){const e=i.humanoid.getNormalizedBoneNode("spine");if(e){const t=.008*Math.sin(.4*u.current),n=.005*Math.cos(.25*u.current);e.rotation.z=E.MathUtils.lerp(e.rotation.z,t,2*r),e.rotation.x=E.MathUtils.lerp(e.rotation.x,n,2*r)}}i.update(r)}}),null}function Xb({position:e,target:t}){const{camera:n}=_();return a(()=>{e&&t&&(n.position.set(...e),n.lookAt(...t))},[n,e,t]),null}function ey({enabled:e,autoRotate:t,frameRef:n}){const{camera:r,gl:o}=_(),i=f(null),s=f(!1);return a(()=>{if(!e)return;const n=new N(r,o.domElement);return n.enablePan=!1,n.enableDamping=!0,n.dampingFactor=.08,n.rotateSpeed=.6,n.zoomSpeed=.8,n.minDistance=.15,n.maxDistance=6,n.autoRotate=t,n.autoRotateSpeed=1.2,i.current=n,s.current=!1,()=>{n.dispose(),i.current=null}},[e,t,r,o]),S(()=>{const e=i.current;e&&(!s.current&&n.current.targetY&&(e.target.set(0,n.current.targetY,0),s.current=!0),e.update())}),null}function ty({url:e,className:t="",cameraPosition:n,targetPosition:r,autoRotate:o=!0,interactive:a=!0,showShadow:l=!0,loadingLabel:c="Loading 3D model…",errorLabel:u="Could not load the 3D model",onLoad:d,onError:p}){const[h,m]=i({url:e,status:"loading"}),g=h.url===e?h.status:"loading",v=f({targetY:0}),w=s(()=>{m({url:e,status:"ready"}),d?.()},[e,d]),x=s(t=>{m({url:e,status:"error"}),p?.(t)},[e,p]);if(!e)return null;const _=!(!n||!r),S=o&&!a;/* @__PURE__ */
|
|
207
207
|
return y("div",{className:`relative h-full w-full overflow-hidden ${t}`,children:[l&&/* @__PURE__ */b("div",{"aria-hidden":!0,className:"pointer-events-none absolute bottom-[8%] left-1/2 z-0 h-[10%] w-[55%] -translate-x-1/2 rounded-[50%]",style:{background:"radial-gradient(ellipse at center, rgba(0,0,0,0.28) 0%, rgba(0,0,0,0) 70%)",filter:"blur(2px)"}}),
|
|
208
208
|
/* @__PURE__ */y(k,{className:"relative z-10",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:[
|
|
209
|
-
/* @__PURE__ */b(
|
|
210
|
-
/* @__PURE__ */b(
|
|
209
|
+
/* @__PURE__ */b(Xb,{position:n,target:r}),
|
|
210
|
+
/* @__PURE__ */b(ey,{enabled:a&&!_,autoRotate:o,frameRef:v}),
|
|
211
211
|
/* @__PURE__ */b("ambientLight",{intensity:.55}),
|
|
212
212
|
/* @__PURE__ */b("directionalLight",{position:[1.5,2,3],intensity:.9,color:"#ffffff"}),
|
|
213
213
|
/* @__PURE__ */b("directionalLight",{position:[-2,1,1.5],intensity:.35,color:"#b4c6e7"}),
|
|
214
214
|
/* @__PURE__ */b("directionalLight",{position:[0,1.5,-2.5],intensity:.5,color:"#ffffff"}),
|
|
215
215
|
/* @__PURE__ */b("pointLight",{position:[0,-.5,.5],intensity:.25,distance:4}),
|
|
216
|
-
/* @__PURE__ */b(
|
|
216
|
+
/* @__PURE__ */b(Qb,{url:e,autoRotate:S,hasCustomCamera:_,frameRef:v,onLoaded:w,onError:x})]},e),"loading"===g&&/* @__PURE__ */y("div",{className:"pointer-events-none absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 text-gray-400",children:[
|
|
217
217
|
/* @__PURE__ */b("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-current border-t-transparent opacity-70"}),c&&/* @__PURE__ */b("span",{className:"text-xs",children:c})]}),"error"===g&&/* @__PURE__ */y("div",{className:"absolute inset-0 z-20 flex flex-col items-center justify-center gap-1 px-3 text-center text-gray-400",children:[
|
|
218
|
-
/* @__PURE__ */b(ce,{className:"h-5 w-5","aria-hidden":!0}),u&&/* @__PURE__ */b("span",{className:"text-xs",children:u})]})]})}const
|
|
219
|
-
//# sourceMappingURL=standalone-
|
|
218
|
+
/* @__PURE__ */b(ce,{className:"h-5 w-5","aria-hidden":!0}),u&&/* @__PURE__ */b("span",{className:"text-xs",children:u})]})]})}const ny="https://api.botuyo.com";class ry 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 oy={"--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%"},iy=p(()=>Promise.resolve().then(()=>Zb).then(e=>({default:e.ChatWidgetWithProviders})));class ay{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||ny},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=D.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(oy).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(oy).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||ny,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(iy,t));this.root.render(n.createElement(ry,null,n.createElement(P,{defaultLocale:this.config.theme?.defaultLocale,children:r}))),console.log("[BotUyoChat] Widget initialized",t)}update(e){this.config?(this.config={...this.config,...e,theme:{...this.config.theme,...e.theme}},this.render()):console.error("[BotUyoChat] Widget not initialized")}destroy(){this.darkModeObserver&&(this.darkModeObserver.disconnect(),this.darkModeObserver=null),this.darkModeMediaQuery&&(this.darkModeMediaQuery.removeEventListener("change",this.handleDarkModeChange),this.darkModeMediaQuery=null),this.root&&(this.root.unmount(),this.root=null),this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null,this.shadowRoot=null,this.mountPoint=null),this.config=null,console.log("[BotUyoChat] Widget destroyed")}setupDarkModeDetection(){this.config?.theme?.cssVariables||(this.handleDarkModeChange=()=>this.render(),this.darkModeObserver=new MutationObserver(this.handleDarkModeChange),this.darkModeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),this.darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.darkModeMediaQuery.addEventListener("change",this.handleDarkModeChange))}handleDarkModeChange=()=>{};open(){window.dispatchEvent(new CustomEvent("botuyo-chat:open"))}close(){window.dispatchEvent(new CustomEvent("botuyo-chat:close"))}startCall(){window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))}sendMessage(e){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:e}}))}getState(){return null}}const sy=new ay;window.BotUyoChat=sy;export{ty as A,ay as B,Hb as C,Y as L,Jb as P,de as X,B as a,Tt as b,Kb as c,Fb as d,Wb as e,P as f,Mt as g,$b as h,sy as i,L as j,Yb as s,j as u};
|
|
219
|
+
//# sourceMappingURL=standalone-DS5eWQKM.js.map
|