@botuyo/chat-widget-standalone 1.7.4 → 1.7.5
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-Dvsd3dvs.js → AudioPlayer-CMrzRQ8U.js} +2 -2
- package/dist/{AudioPlayer-Dvsd3dvs.js.map → AudioPlayer-CMrzRQ8U.js.map} +1 -1
- package/dist/{Avatar3D-Bsemx1XZ.js → Avatar3D-CRxMpnig.js} +2 -2
- package/dist/{Avatar3D-Bsemx1XZ.js.map → Avatar3D-CRxMpnig.js.map} +1 -1
- package/dist/{Gallery-C16PGHL3.js → Gallery-COjq47z7.js} +2 -2
- package/dist/{Gallery-C16PGHL3.js.map → Gallery-COjq47z7.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/VoiceCallOverlay.d.ts.map +1 -1
- package/dist/{standalone-3qms0iXz.js → standalone-Xxf8KK4I.js} +4 -4
- package/dist/{standalone-3qms0iXz.js.map → standalone-Xxf8KK4I.js.map} +1 -1
- package/dist/stats-umd.html +1 -1
- package/dist/stats.html +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VoiceCallOverlay.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/components/VoiceCallOverlay.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAqBH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD,OAAO,EAML,KAAK,gBAAgB,EACtB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAQL,KAAK,cAAc,EACpB,MAAM,kBAAkB,CAAA;AAOzB,8CAA8C;AAC9C,MAAM,WAAW,kBAAkB;IACjC,0DAA0D;IAC1D,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,8DAA8D;IAC9D,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,2DAA2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,4DAA4D;IAC5D,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,yEAAyE;IACzE,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,sEAAsE;IACtE,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,mDAAmD;IACnD,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,kDAAkD;IAClD,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,gDAAgD;IAChD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,wDAAwD;IACxD,aAAa,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAC/C,qCAAqC;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAA;IACjD,0CAA0C;IAC1C,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,gDAAgD;IAChD,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,gDAAgD;IAChD,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,yEAAyE;IACzE,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;;;;;;OAQG;IACH,SAAS,CAAC,EAAE,gBAAgB,CAAA;IAC5B;;;;;;;;;;OAUG;IACH,GAAG,CAAC,EAAE,KAAK,GAAG,cAAc,CAAA;IAC5B,iFAAiF;IACjF,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,UAAU,qBAAqB;IAC7B,MAAM,EAAE,OAAO,CAAA;IACf,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,EAAE,MAAM,GAAG,CAAA;IACrB,OAAO,CAAC,EAAE,gBAAgB,CAAA;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,iDAAiD;IACjD,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,2DAA2D;IAC3D,WAAW,CAAC,EAAE,kBAAkB,CAAA;IAChC;;;;OAIG;IACH,WAAW,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,KAAK,IAAI,CAAA;CACxC;AAED,KAAK,SAAS,GAAG,MAAM,GAAG,YAAY,GAAG,WAAW,GAAG,UAAU,GAAG,UAAU,CAAA;AA4b9E,wBAAgB,gBAAgB,CAAC,EAC/B,MAAM,EACN,OAAO,EACP,YAAwB,EACxB,SAAS,EACT,OAAO,EACP,OAAO,EACP,WAAW,EACX,WAAW,EACX,WAAW,GACZ,EAAE,qBAAqB,
|
|
1
|
+
{"version":3,"file":"VoiceCallOverlay.d.ts","sourceRoot":"","sources":["../../../../src/chat-widget/components/VoiceCallOverlay.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAqBH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD,OAAO,EAML,KAAK,gBAAgB,EACtB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAQL,KAAK,cAAc,EACpB,MAAM,kBAAkB,CAAA;AAOzB,8CAA8C;AAC9C,MAAM,WAAW,kBAAkB;IACjC,0DAA0D;IAC1D,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,8DAA8D;IAC9D,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,2DAA2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,4DAA4D;IAC5D,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,yEAAyE;IACzE,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,sEAAsE;IACtE,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,mDAAmD;IACnD,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,kDAAkD;IAClD,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,gDAAgD;IAChD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,wDAAwD;IACxD,aAAa,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAC/C,qCAAqC;IACrC,YAAY,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAA;IACjD,0CAA0C;IAC1C,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,gDAAgD;IAChD,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,gDAAgD;IAChD,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,yEAAyE;IACzE,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;;;;;;OAQG;IACH,SAAS,CAAC,EAAE,gBAAgB,CAAA;IAC5B;;;;;;;;;;OAUG;IACH,GAAG,CAAC,EAAE,KAAK,GAAG,cAAc,CAAA;IAC5B,iFAAiF;IACjF,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,UAAU,qBAAqB;IAC7B,MAAM,EAAE,OAAO,CAAA;IACf,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,EAAE,MAAM,GAAG,CAAA;IACrB,OAAO,CAAC,EAAE,gBAAgB,CAAA;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,iDAAiD;IACjD,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,2DAA2D;IAC3D,WAAW,CAAC,EAAE,kBAAkB,CAAA;IAChC;;;;OAIG;IACH,WAAW,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,KAAK,IAAI,CAAA;CACxC;AAED,KAAK,SAAS,GAAG,MAAM,GAAG,YAAY,GAAG,WAAW,GAAG,UAAU,GAAG,UAAU,CAAA;AA4b9E,wBAAgB,gBAAgB,CAAC,EAC/B,MAAM,EACN,OAAO,EACP,YAAwB,EACxB,SAAS,EACT,OAAO,EACP,OAAO,EACP,WAAW,EACX,WAAW,EACX,WAAW,GACZ,EAAE,qBAAqB,kDAkjDvB"}
|
|
@@ -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(he,{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(H,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Vl=p(()=>import("./AudioPlayer-
|
|
29
|
+
/* @__PURE__ */b(H,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Vl=p(()=>import("./AudioPlayer-CMrzRQ8U.js").then(e=>({default:e.AudioPlayer}))),Wl=p(()=>import("./Gallery-COjq47z7.js").then(e=>({default:e.Gallery})));function Hl({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:Ot("prose prose-sm max-w-none break-words leading-relaxed dark:prose-invert text-foreground"),children:/* @__PURE__ */b(Ra,{remarkPlugins:[Il],rehypePlugins:[[Bl,{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 ic(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 ac(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=ic(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const sc="24px",lc={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},cc=85,uc=.7,dc=200,pc=.5,hc=3e3,fc=1,mc=6,gc=7500,bc=.7,yc=-20,vc=8,wc=6,xc=.002,kc=.12,_c={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},Sc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{..._c},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function Cc(e=_c,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 Ec={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 zc(e){return void 0===e||"standard"===e?{...Ec.standard}:"string"==typeof e?{...Ec[e]??Ec.standard}:{...Ec.standard,...e}}class Ac{config;_state="silence";onsetCount=0;redemptionCount=0;constructor(e={}){this.config={...Ec.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 Nc="0.0.30",Tc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Nc}/dist/`,Ic=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Nc}/+esm`;function Oc(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 Mc(){return await import(Ic)}class Pc{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){O.warn("[VAD] error while destroying detector",e)}this._running=!1}}const Lc=p(()=>import("./Avatar3D-
|
|
110
|
+
/* @__PURE__ */b("span",{children:e.label})]})},e.id))})]})})}function ic(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 ac(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=ic(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const sc="24px",lc={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},cc=85,uc=.7,dc=200,pc=.5,hc=3e3,fc=1,mc=6,gc=7500,bc=.7,yc=-20,vc=8,wc=6,xc=.002,kc=.12,_c={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},Sc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{..._c},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function Cc(e=_c,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 Ec={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 zc(e){return void 0===e||"standard"===e?{...Ec.standard}:"string"==typeof e?{...Ec[e]??Ec.standard}:{...Ec.standard,...e}}class Ac{config;_state="silence";onsetCount=0;redemptionCount=0;constructor(e={}){this.config={...Ec.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 Nc="0.0.30",Tc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Nc}/dist/`,Ic=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${Nc}/+esm`;function Oc(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 Mc(){return await import(Ic)}class Pc{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){O.warn("[VAD] error while destroying detector",e)}this._running=!1}}const Lc=p(()=>import("./Avatar3D-CRxMpnig.js")),Dc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},jc={idle:"Llamada de voz",connecting:"Conectando...",listening:"Escuchando...",thinking:"Pensando...",speaking:"Hablando..."},Rc={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"]}}},Fc=24e3;function $c(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 Bc extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){O.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 Uc({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||Bt:t||Bt: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(Bc,{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(Lc,{modelUrl:n,emotion:r,callState:o,audioLevel:a,primaryColor:s.speakingColor,size:s.orbSize})})}),s.showWaveform&&/* @__PURE__ */b(qc,{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:Ot("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:[
|
|
@@ -117,7 +117,7 @@ return y("div",n&&!d?{className:"relative flex flex-col items-center gap-4",chil
|
|
|
117
117
|
/* @__PURE__ */b("div",{className:"absolute rounded-full",style:{inset:"12px",border:`1px solid ${g}15`,animation:m?"spin 12s linear infinite reverse":"none"}}),
|
|
118
118
|
/* @__PURE__ */b("div",{className:"absolute rounded-full flex items-center justify-center",style:{inset:"24px",background:`radial-gradient(circle at 35% 35%, ${g}40, ${g}10 60%, transparent 80%)`,boxShadow:m?`0 0 60px ${g}35, 0 0 120px ${g}15, inset 0 0 40px ${g}10`:`0 0 30px ${g}15`,transform:`scale(${v})`,transition:"all 0.5s cubic-bezier(0.4, 0, 0.2, 1)"},children:/* @__PURE__ */b("div",{className:"rounded-full",style:{width:.35*w+"px",height:.35*w+"px",background:`radial-gradient(circle, ${g}90, ${g}40)`,boxShadow:`0 0 20px ${g}60`,animation:m?"pulse 2s ease-in-out infinite":"none"}})}),m&&[0,1,2].map(e=>/* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"4px",height:"4px",backgroundColor:g,opacity:.6,top:"50%",left:"50%",transform:`rotate(${120*e}deg) translateX(${(w+48)/2}px)`,animation:`spin ${6+2*e}s linear infinite`,boxShadow:`0 0 6px ${g}`}},e))]}),s.showWaveform&&/* @__PURE__ */b(qc,{isActive:m,audioLevel:a,color:g})]})}function qc({isActive:e,audioLevel:t,color:n}){/* @__PURE__ */
|
|
119
119
|
return b("div",{className:"flex items-center gap-[3px] h-10",children:Array.from({length:12}).map((r,o)=>{const i=Math.abs(o-5.5)/5.5,a=e?Math.max(4,40*t*(1-.5*i)*(.5+.5*Math.sin(.8*o))):4;/* @__PURE__ */
|
|
120
|
-
return b("div",{className:"rounded-full transition-all duration-100",style:{width:"3px",height:`${a}px`,backgroundColor:n,opacity:e?.7-.3*i:.2}},o)})})}function Vc({isOpen:e,onClose:t,primaryColor:n="#10b981",getSocket:r,avatars:o,logoUrl:l,avatar3dUrl:c,voiceConfig:d,onCallEnded:p}){const h=u(()=>function(e,t="#10b981"){return{backgroundColor:e?.backgroundColor??"#0a0a0a",listeningColor:e?.listeningColor??"#10b981",speakingColor:e?.speakingColor??t,thinkingColor:e?.thinkingColor??"#a855f7",showEmojis:e?.showEmojis??!0,showEmotionLabel:e?.showEmotionLabel??!0,showWaveform:e?.showWaveform??!0,showBadge:e?.showBadge??!1,badgeText:e?.badgeText??"",emotionEmojis:{...Dc,...e?.emotionEmojis},statusLabels:{...jc,...e?.statusLabels},orbSize:e?.orbSize??128,speakingScale:e?.speakingScale??1.08,thinkingScale:e?.thinkingScale??.95,avatar3dUrl:e?.avatar3dUrl,voiceGate:(n=e?.noiseGate,void 0===n||!0===n||"standard"===n?{...Sc.standard}:!1===n||"off"===n?{...Sc.off}:"string"==typeof n?{...Sc[n]??Sc.standard}:{...Sc.standard,...n}),vad:!1!==e?.vad&&zc(e?.vad),vadAssetBaseUrl:e?.vadAssetBaseUrl};var n}(d,n),[d,n]);!function(e){const t=f(null);a(()=>{const n="undefined"==typeof navigator?null:navigator.wakeLock??null;if(!e||!n)return;let r=!1;const o=async()=>{if(!t.current||t.current.released)try{const e=await n.request("screen");if(r)return void e.release();t.current=e,e.addEventListener("release",()=>{t.current===e&&(t.current=null)})}catch(e){O.warn("[useWakeLock] Could not acquire screen wake lock",e)}},i=()=>{"visible"===document.visibilityState&&o()};return o(),document.addEventListener("visibilitychange",i),()=>{r=!0,document.removeEventListener("visibilitychange",i);const e=t.current;t.current=null,e&&!e.released&&e.release().catch(()=>{})}},[e])}(e);const[m,g]=i("idle"),[w,x]=i(0),[k,_]=i(!1),[S,C]=i(0),[E,z]=i(null),[A,N]=i([]),[T,I]=i(!1),[M,P]=i(""),[L,D]=i(!1),[j,R]=i(null),[F,$]=i(void 0),[B,U]=i(void 0),[q,V]=i(void 0),[W,H]=i(!1),Z=f(null),J=f(null),K=f(null),G=f(null),Y=f(null),X=f(0),ee=f(!1),te=f(null),ie=f(null),ae=f(()=>{}),le=f(null),ce=f(0),ue=f(null),de=f([]),he=f(!1),fe=f(0),me=f([]),ge=f(null),be=f(null),ye=f(1),ve=f(0),we=s(e=>`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`,[]),xe=s(()=>{if(0===de.current.length)return;ue.current&&"closed"!==ue.current.state||(ue.current=new AudioContext({sampleRate:Fc})),"suspended"===ue.current.state&&ue.current.resume().catch(()=>{});const e=ue.current;he.current=!0,g("speaking");const t=e.currentTime;for(fe.current<t&&(fe.current=t);de.current.length>0;){const t=de.current.shift(),n=e.createBuffer(1,t.length,Fc);n.getChannelData(0).set(t);const r=e.createBufferSource();r.buffer=n,r.connect(e.destination),r.start(fe.current),me.current.push(r),r.onended=()=>{me.current=me.current.filter(e=>e!==r),0===me.current.length&&0===de.current.length&&(he.current=!1,g(e=>"speaking"===e?"listening":e))},fe.current+=t.length/Fc}},[]),ke=s(()=>{me.current.forEach(e=>{try{e.stop()}catch{}}),me.current=[],de.current.length=0,fe.current=0,he.current=!1,g("listening")},[]),_e=f({}),Se=s(()=>{const e=r?.();if(!e||ee.current)return;const n=e=>{e&&($(e.avatars||void 0),U(e.logoUrl||void 0),V(e.avatar3dUrl||void 0),H(!0))},o=e=>{g("listening"),n(e?.agentAvatar)},i=e=>{Te();const t=(e?.agentName||"").toString().trim();R(t||"Nuevo agente"),n(e?.agentAvatar),N(e=>[...e,{role:"bot",text:t?`🔄 Continuás con ${t}.`:"🔄 Te derivé con el área correspondiente.",standalone:!0}])},a=e=>{if(!e?.data)return;const t=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);const r=new Int16Array(n.buffer),o=new Float32Array(r.length);for(let i=0;i<r.length;i++)o[i]=r[i]/32768;return o}(e.data);de.current.push(t),xe(),Te()},s=()=>{ke()},l=()=>{},c=e=>{console.error("[VoiceCall] Voice error:",e)},u=e=>{e?.emotion&&(z(e.emotion),setTimeout(()=>z(t=>t===e.emotion?null:t),4e3))},d=e=>{e?.text&&(Te(),N(t=>{if(t.length>0&&"user"===t[t.length-1].role){const n=[...t],r=n[n.length-1].text,o=r.length>0&&!r.endsWith(" ")&&!e.text.startsWith(" ");return n[n.length-1]={...n[n.length-1],text:r+(o?" ":"")+e.text},n}return[...t,{role:"user",text:e.text}]}))},h=e=>{e?.text&&N(t=>{const n=t.map(e=>e.role).lastIndexOf("user");if(n>=0){const r=[...t];return r[n]={...r[n],text:e.text},r}return[...t,{role:"user",text:e.text}]})},f=e=>{e?.text&&N(t=>{const n=[...t];for(let o=n.length-1;o>=0;o--)if("user"===n[o].role&&n[o].text===e.original)return n[o]={...n[o],text:e.text},n;const r=n.map(e=>e.role).lastIndexOf("user");return r>=0?(n[r]={...n[r],text:e.text},n):t})},m=e=>{e?.text&&(Te(),N(t=>{const n=t[t.length-1];let r=t;if(!n||"bot"!==n.role||n.standalone){let e=-1;for(let n=t.length-1;n>=0;n--)if(t[n].quizButtons&&t[n].quizButtons.length>0){e=n;break}e>=0&&t.slice(e+1).some(e=>"user"===e.role)&&(r=t.map((t,n)=>n===e?{...t,quizButtons:void 0}:t))}const o=r[r.length-1];if(o&&"bot"===o.role&&!o.standalone){const t=[...r],n=o.text,i=n.length>0&&!n.endsWith(" ")&&!e.text.startsWith(" ");return t[t.length-1]={...o,text:n+(i?" ":"")+e.text},t}return[...r,{role:"bot",text:e.text}]}))},b=()=>{g("thinking"),Te()},y=e=>{if(!e?.items?.length)return;if(Te(),"present_quiz"===e.tool)return;if("show_content"===e.tool){const t=e.items.map(e=>"link"===e.type?`[${e.label||e.url}](${e.url})`:"image"===e.type?``:e.label||"").filter(Boolean).join("\n");return void(t&&N(e=>[...e,{role:"bot",text:t,standalone:!0}]))}const t=e.items.map(t=>{if("search_accommodations"===e.tool){const e=t.options?.[0],n=e?`${e.totalPrice} ${e.currency}`:"",r=(t.features||[]).slice(0,3).join(" • "),o=t.cover?``:"",i=e?.link?`[Ver detalles](${e.link})`:"";return`${o}\n**${t.index}. ${t.title}**\n📍 ${t.location} ${t.rating?`⭐ ${t.rating}`:""}\n💰 ${n}\n${r}\n${i}`}if("get_accommodation_details"===e.tool){const e=(t.images||[]).slice(0,4).map(e=>``).join("\n"),n=t.specs?Object.entries(t.specs).map(([e,t])=>`${e}: ${t}`).join(" • "):"",r=(t.rooms||[]).map(e=>`• ${e.name}: ${e.price}`).join("\n"),o=t.rules?`🕐 Check-in: ${t.rules.checkIn||"-"} | Check-out: ${t.rules.checkOut||"-"} | Mascotas: ${t.rules.pets||"-"}`:"",i=t.seeMoreLink?`[Ver más detalles](${t.seeMoreLink})`:"";return`${e}\n**${t.title||t.name}**\n${t.description||""}\n${n}\n${r}\n${o}\n${i}`}if("card"===t.type&&t.content)return t.content;if("link"===t.type&&t.url)return`🔗 [${t.label||t.url}](${t.url})`;if("image"===t.type&&t.url)return``;if(t.systemInstruction&&"string"==typeof t.systemInstruction)return t.systemInstruction;const n=t.signupUrl||t.url||t.link||t.redirectUrl||t.actionPayload?.signupUrl||t.actionPayload?.url;return n?`🔗 [${t.label||t.title||e.tool.replace(/_/g," ")}](${n})`:"error"===t.status?t.error||"Error al ejecutar la acción":""}).filter(Boolean).join("\n\n---\n\n");t&&N(e=>[...e,{role:"bot",text:t,standalone:!0}])},v=e=>{if("quiz_question"===e?.eventName&&e?.data){const{question:t,buttons:n}=e.data;t&&n?.length&&(Te(),N(e=>[...e,{role:"bot",text:`📝 ${t}`,quizButtons:n,standalone:!0}]))}if("suggest_next_class"===e?.eventName&&e?.data){const{scheduledAt:t,title:n,body:r}=e.data;if("string"==typeof t&&""!==t.trim()){const e=new Date(t),o=[`📅 **Próxima clase** — ${Number.isNaN(e.getTime())?t:new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"short"}).format(e)}`];"string"==typeof n&&""!==n.trim()&&o.push(`**${n.trim()}**`),"string"==typeof r&&""!==r.trim()&&o.push(r.trim()),Te(),N(e=>[...e,{role:"bot",text:o.join("\n\n"),standalone:!0}])}}};_e.current={voiceReady:o,voiceAudioChunk:a,voiceInterrupted:s,voiceTurnComplete:l,voiceError:c,voiceEmotion:u,voiceUserTranscript:d,voiceUserTranscriptFinal:h,voiceUserTranscriptCorrected:f,voiceModelTranscript:m,voiceModelThinking:b,voiceToolVisual:y,voiceCustomEvent:v,voiceAgentSwitched:i},e.on("voice_ready",o),e.on("voice_audio_chunk",a),e.on("voice_interrupted",s),e.on("voice_turn_complete",l),e.on("voice_error",c),e.on("voice_emotion",u),e.on("voice_user_transcript",d),e.on("voice_user_transcript_final",h),e.on("voice_user_transcript_corrected",f),e.on("voice_model_transcript",m),e.on("voice_model_thinking",b),e.on("voice_tool_visual",y),e.on("custom_event",v),e.on("voice_agent_switched",i),e.on("voice_timeout",()=>{ae.current()});const w=e=>{p?.(e?.reason),N(e=>[...e,{role:"bot",text:"📞 Llamada finalizada."}]);const n=r?.();n?.connected&&setTimeout(()=>{try{n.emit("request_history")}catch{}},1500),setTimeout(()=>{t()},2500)};e.on("voice_call_ended",w),_e.current.voiceCallEnded=w,ee.current=!0},[r,xe,ke]),Ce=s(()=>{const e=r?.();if(!e||!ee.current)return;const t=_e.current;t.voiceReady&&e.off("voice_ready",t.voiceReady),t.voiceAudioChunk&&e.off("voice_audio_chunk",t.voiceAudioChunk),t.voiceInterrupted&&e.off("voice_interrupted",t.voiceInterrupted),t.voiceTurnComplete&&e.off("voice_turn_complete",t.voiceTurnComplete),t.voiceError&&e.off("voice_error",t.voiceError),t.voiceEmotion&&e.off("voice_emotion",t.voiceEmotion),t.voiceUserTranscript&&e.off("voice_user_transcript",t.voiceUserTranscript),t.voiceUserTranscriptFinal&&e.off("voice_user_transcript_final",t.voiceUserTranscriptFinal),t.voiceUserTranscriptCorrected&&e.off("voice_user_transcript_corrected",t.voiceUserTranscriptCorrected),t.voiceModelTranscript&&e.off("voice_model_transcript",t.voiceModelTranscript),t.voiceModelThinking&&e.off("voice_model_thinking",t.voiceModelThinking),t.voiceToolVisual&&e.off("voice_tool_visual",t.voiceToolVisual),t.voiceCustomEvent&&e.off("custom_event",t.voiceCustomEvent),t.voiceAgentSwitched&&e.off("voice_agent_switched",t.voiceAgentSwitched),t.voiceCallEnded&&e.off("voice_call_ended",t.voiceCallEnded),e.off("voice_timeout"),_e.current={},ee.current=!1},[r]),Ee=s(async()=>{const e=r?.();if(!e)return;const t=await navigator.mediaDevices.getUserMedia({audio:lc});K.current=t;const n=!1!==h.vad;ge.current=new Ac(n?h.vad:{energyOnly:!0}),ye.current=1,ve.current=0,n&&async function(e){const t=e.loadVad??Mc;try{const n=await t(),r=(t,n)=>{e.onFrame({speechProb:t?.isSpeech??0,rms:Oc(n)})},o=await n.MicVAD.new(function(e,t){const n={model:e.model??"v5",baseAssetPath:e.assetBaseUrl??Tc,onnxWASMBasePath:e.onnxWasmBaseUrl??"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",startOnLoad:!1,onFrameProcessed:t};if(e.audioContext&&(n.audioContext=e.audioContext),e.stream){const t=e.stream;n.getStream=async()=>t,n.pauseStream=async()=>{},n.resumeStream=async()=>{}}return n}(e,r));return O.info("[VAD] Silero speech detector ready"),new Pc(o)}catch(n){return O.warn("[VAD] Silero unavailable — falling back to energy gate",n),null}}({stream:t,assetBaseUrl:h.vadAssetBaseUrl,onFrame:({speechProb:e})=>{ye.current=e,ve.current=performance.now()}}).then(e=>{if(e){if(K.current)return be.current=e,e.start();e.destroy()}}).catch(()=>{});const o=new AudioContext({sampleRate:16e3});G.current=o,"suspended"===o.state&&await o.resume();const i=o.createMediaStreamSource(t),a=function(e,t){const n=e.createBiquadFilter();n.type="highpass",n.frequency.value=cc,n.Q.value=uc;const r=e.createBiquadFilter();r.type="highpass",r.frequency.value=dc,r.Q.value=pc;const o=e.createBiquadFilter();o.type="peaking",o.frequency.value=hc,o.Q.value=fc,o.gain.value=mc;const i=e.createBiquadFilter();i.type="lowpass",i.frequency.value=gc,i.Q.value=bc;const a=e.createDynamicsCompressor();return a.threshold.value=yc,a.knee.value=vc,a.ratio.value=wc,a.attack.value=xc,a.release.value=kc,t.connect(n),n.connect(r),r.connect(o),o.connect(i),i.connect(a),a}(o,i),s=o.createAnalyser();if(s.fftSize=256,a.connect(s),J.current=s,!te.current){const e=new Blob([Cc(h.voiceGate)],{type:"application/javascript"});te.current=URL.createObjectURL(e)}await o.audioWorklet.addModule(te.current);const l=new AudioWorkletNode(o,"voice-pcm-processor");Y.current=l,l.port.onmessage=t=>{const n=ge.current;if(!n)return;const r=performance.now()-ve.current<600,o=ue.current,i=function(e){return!!e.isPlaying&&!!e.contextRunning&&e.nextPlayTime>e.currentTime}({isPlaying:he.current,contextRunning:"running"===o?.state,nextPlayTime:fe.current,currentTime:o?.currentTime??0}),{frame:a,confirmedSpeech:s}=function(e){return e.botSpeaking&&!e.vadFresh?{frame:{speechProb:0,rms:0,botSpeaking:!0},confirmedSpeech:!1}:{frame:{speechProb:e.vadFresh?e.speechProb:1,rms:e.rms,botSpeaking:e.botSpeaking},confirmedSpeech:e.vadFresh}}({botSpeaking:i,vadFresh:r,speechProb:ye.current,rms:t.data.rms}),{shouldStream:l,event:c}=n.process(a);"barge_in"===c&&ke();const u=function(e){return!e.botSpeaking||e.gateShouldStream}({gateShouldStream:l,botSpeaking:i});if(u&&e.connected&&!k){const n=function(e){return e.confirmedSpeech||!e.vadFresh}({confirmedSpeech:s,vadFresh:r});e.emit("voice_audio_chunk",{data:$c(t.data.pcm),speech:n})}},a.connect(l);const c=()=>{if(!J.current)return;const e=new Uint8Array(J.current.frequencyBinCount);J.current.getByteFrequencyData(e);const t=e.reduce((e,t)=>e+t,0)/e.length;C(t/255),X.current=requestAnimationFrame(c)};c()},[r,k,h.voiceGate,h.vad,h.vadAssetBaseUrl,ke]),ze=s(()=>{cancelAnimationFrame(X.current),be.current?.destroy(),be.current=null,ge.current=null,ye.current=1,ve.current=0,Y.current?.disconnect(),Y.current=null,K.current?.getTracks().forEach(e=>e.stop()),K.current=null,G.current?.close(),G.current=null,J.current=null,C(0)},[]),Ae=s(async()=>{const e=r?.();if(e?.connected){g("connecting"),x(0),N([]),z(null),$(void 0),U(void 0),V(void 0),H(!1),de.current=[],Se(),ue.current&&"closed"!==ue.current.state||(ue.current=new AudioContext({sampleRate:Fc})),ue.current.resume().catch(()=>{});try{await Ee()}catch(t){return console.error("[VoiceCall] Mic error:",t),void g("idle")}e.emit("voice_start",{language:"es-AR",voice:"Kore"}),Z.current=setInterval(()=>{x(e=>e+1)},1e3),Ie()}else console.error("[VoiceCall] Socket not connected")},[r,Se,Ee]),Ne=s(()=>{ze(),me.current.forEach(e=>{try{e.stop()}catch{}}),me.current=[],de.current=[],fe.current=0,he.current=!1,ue.current?.close(),ue.current=null,Z.current&&(clearInterval(Z.current),Z.current=null),le.current&&(clearInterval(le.current),le.current=null);const e=r?.();e?.connected&&(e.emit("voice_stop"),setTimeout(()=>{try{e.emit("request_history")}catch{}},1500)),Ce(),g("idle"),C(0),x(0),_(!1),N([]),D(!1),R(null),$(void 0),U(void 0),V(void 0),H(!1),t()},[r,ze,Ce,t]);a(()=>{ae.current=Ne},[Ne]);const Te=s(()=>{ce.current=0,D(!1)},[]),Ie=s(()=>{ce.current=0,le.current&&clearInterval(le.current),le.current=setInterval(()=>{ce.current+=1;const e=ce.current;e>=90&&e<120&&D(!0),e>=120&&ae.current()},1e3)},[]),Oe=s(()=>{_(e=>!e)},[]),Me=s(()=>{const e=M.trim();if(!e)return;const t=r?.();t?.connected&&(t.emit("voice_text_input",{text:e}),P(""),I(!1))},[M,r]);if(a(()=>{e&&"idle"===m&&Ae()},[e]),a(()=>{ie.current?.scrollIntoView({behavior:"smooth"})},[A]),a(()=>()=>{ze(),Z.current&&clearInterval(Z.current),Ce()},[]),!e)return null;const Pe="speaking"===m?h.speakingColor:"thinking"===m?h.thinkingColor:"listening"===m?h.listeningColor:n,Le=W?F:o,De=W?B:l,je=(W?q:c)||h.avatar3dUrl;let Re=-1;for(let i=A.length-1;i>=0;i--)if(A[i].quizButtons&&A[i].quizButtons.length>0){Re=i;break}const Fe=Re>=0?A[Re]:null;/* @__PURE__ */
|
|
120
|
+
return b("div",{className:"rounded-full transition-all duration-100",style:{width:"3px",height:`${a}px`,backgroundColor:n,opacity:e?.7-.3*i:.2}},o)})})}function Vc({isOpen:e,onClose:t,primaryColor:n="#10b981",getSocket:r,avatars:o,logoUrl:l,avatar3dUrl:c,voiceConfig:d,onCallEnded:p}){const h=u(()=>function(e,t="#10b981"){return{backgroundColor:e?.backgroundColor??"#0a0a0a",listeningColor:e?.listeningColor??"#10b981",speakingColor:e?.speakingColor??t,thinkingColor:e?.thinkingColor??"#a855f7",showEmojis:e?.showEmojis??!0,showEmotionLabel:e?.showEmotionLabel??!0,showWaveform:e?.showWaveform??!0,showBadge:e?.showBadge??!1,badgeText:e?.badgeText??"",emotionEmojis:{...Dc,...e?.emotionEmojis},statusLabels:{...jc,...e?.statusLabels},orbSize:e?.orbSize??128,speakingScale:e?.speakingScale??1.08,thinkingScale:e?.thinkingScale??.95,avatar3dUrl:e?.avatar3dUrl,voiceGate:(n=e?.noiseGate,void 0===n||!0===n||"standard"===n?{...Sc.standard}:!1===n||"off"===n?{...Sc.off}:"string"==typeof n?{...Sc[n]??Sc.standard}:{...Sc.standard,...n}),vad:!1!==e?.vad&&zc(e?.vad),vadAssetBaseUrl:e?.vadAssetBaseUrl};var n}(d,n),[d,n]);!function(e){const t=f(null);a(()=>{const n="undefined"==typeof navigator?null:navigator.wakeLock??null;if(!e||!n)return;let r=!1;const o=async()=>{if(!t.current||t.current.released)try{const e=await n.request("screen");if(r)return void e.release();t.current=e,e.addEventListener("release",()=>{t.current===e&&(t.current=null)})}catch(e){O.warn("[useWakeLock] Could not acquire screen wake lock",e)}},i=()=>{"visible"===document.visibilityState&&o()};return o(),document.addEventListener("visibilitychange",i),()=>{r=!0,document.removeEventListener("visibilitychange",i);const e=t.current;t.current=null,e&&!e.released&&e.release().catch(()=>{})}},[e])}(e);const[m,g]=i("idle"),[w,x]=i(0),[k,_]=i(!1),[S,C]=i(0),[E,z]=i(null),[A,N]=i([]),[T,I]=i(!1),[M,P]=i(""),[L,D]=i(!1),[j,R]=i(null),[F,$]=i(void 0),[B,U]=i(void 0),[q,V]=i(void 0),[W,H]=i(!1),Z=f(null),J=f(null),K=f(null),G=f(null),Y=f(null),X=f(0),ee=f(!1),te=f(null),ie=f(null),ae=f(()=>{}),le=f(null),ce=f(0),ue=f(null),de=f([]),he=f(!1),fe=f(0),me=f([]),ge=f(null),be=f(null),ye=f(1),ve=f(0),we=s(e=>`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`,[]),xe=s(()=>{if(0===de.current.length)return;ue.current&&"closed"!==ue.current.state||(ue.current=new AudioContext({sampleRate:Fc})),"suspended"===ue.current.state&&ue.current.resume().catch(()=>{});const e=ue.current;he.current=!0,g("speaking");const t=e.currentTime;for(fe.current<t&&(fe.current=t);de.current.length>0;){const t=de.current.shift(),n=e.createBuffer(1,t.length,Fc);n.getChannelData(0).set(t);const r=e.createBufferSource();r.buffer=n,r.connect(e.destination),r.start(fe.current),me.current.push(r),r.onended=()=>{me.current=me.current.filter(e=>e!==r),0===me.current.length&&0===de.current.length&&(he.current=!1,g(e=>"speaking"===e?"listening":e))},fe.current+=t.length/Fc}},[]),ke=s(()=>{me.current.forEach(e=>{try{e.stop()}catch{}}),me.current=[],de.current.length=0,fe.current=0,he.current=!1,g("listening")},[]),_e=f({}),Se=s(()=>{const e=r?.();if(!e||ee.current)return;const n=e=>{e&&($(e.avatars||void 0),U(e.logoUrl||void 0),V(e.avatar3dUrl||void 0),H(!0))},o=e=>{g("listening"),n(e?.agentAvatar)},i=e=>{Te();const t=(e?.agentName||"").toString().trim();R(t||"Nuevo agente"),n(e?.agentAvatar),N(e=>[...e,{role:"bot",text:t?`🔄 Continuás con ${t}.`:"🔄 Te derivé con el área correspondiente.",standalone:!0}])},a=e=>{if(!e?.data)return;const t=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);const r=new Int16Array(n.buffer),o=new Float32Array(r.length);for(let i=0;i<r.length;i++)o[i]=r[i]/32768;return o}(e.data);de.current.push(t),xe(),Te()},s=()=>{ke()},l=()=>{},c=e=>{console.error("[VoiceCall] Voice error:",e)},u=e=>{e?.emotion&&(z(e.emotion),setTimeout(()=>z(t=>t===e.emotion?null:t),4e3))},d=e=>{e?.text&&(Te(),N(t=>{if(t.length>0&&"user"===t[t.length-1].role){const n=[...t],r=n[n.length-1].text,o=r.length>0&&!r.endsWith(" ")&&!e.text.startsWith(" ");return n[n.length-1]={...n[n.length-1],text:r+(o?" ":"")+e.text},n}return[...t,{role:"user",text:e.text}]}))},h=e=>{e?.text&&N(t=>{const n=t.map(e=>e.role).lastIndexOf("user");if(n>=0){const r=[...t];return r[n]={...r[n],text:e.text},r}return[...t,{role:"user",text:e.text}]})},f=e=>{e?.text&&N(t=>{const n=[...t];for(let o=n.length-1;o>=0;o--)if("user"===n[o].role&&n[o].text===e.original)return n[o]={...n[o],text:e.text},n;const r=n.map(e=>e.role).lastIndexOf("user");return r>=0?(n[r]={...n[r],text:e.text},n):t})},m=e=>{e?.text&&(Te(),N(t=>{const n=t[t.length-1];let r=t;if(!n||"bot"!==n.role||n.standalone){let e=-1;for(let n=t.length-1;n>=0;n--)if(t[n].quizButtons&&t[n].quizButtons.length>0){e=n;break}e>=0&&t.slice(e+1).some(e=>"user"===e.role)&&(r=t.map((t,n)=>n===e?{...t,quizButtons:void 0}:t))}const o=r[r.length-1];if(o&&"bot"===o.role&&!o.standalone){const t=[...r],n=o.text,i=n.length>0&&!n.endsWith(" ")&&!e.text.startsWith(" ");return t[t.length-1]={...o,text:n+(i?" ":"")+e.text},t}return[...r,{role:"bot",text:e.text}]}))},b=()=>{g("thinking"),Te()},y=e=>{if(!e?.items?.length)return;if(Te(),"present_quiz"===e.tool)return;if("show_content"===e.tool){const t=e.items.map(e=>"link"===e.type?`[${e.label||e.url}](${e.url})`:"image"===e.type?``:e.label||"").filter(Boolean).join("\n");return void(t&&N(e=>[...e,{role:"bot",text:t,standalone:!0}]))}const t=e.items.map(t=>{if("search_accommodations"===e.tool){const e=t.options?.[0],n=e?`${e.totalPrice} ${e.currency}`:"",r=(t.features||[]).slice(0,3).join(" • "),o=t.cover?``:"",i=e?.link?`[Ver detalles](${e.link})`:"";return`${o}\n**${t.index}. ${t.title}**\n📍 ${t.location} ${t.rating?`⭐ ${t.rating}`:""}\n💰 ${n}\n${r}\n${i}`}if("get_accommodation_details"===e.tool){const e=(t.images||[]).slice(0,4).map(e=>``).join("\n"),n=t.specs?Object.entries(t.specs).map(([e,t])=>`${e}: ${t}`).join(" • "):"",r=(t.rooms||[]).map(e=>`• ${e.name}: ${e.price}`).join("\n"),o=t.rules?`🕐 Check-in: ${t.rules.checkIn||"-"} | Check-out: ${t.rules.checkOut||"-"} | Mascotas: ${t.rules.pets||"-"}`:"",i=t.seeMoreLink?`[Ver más detalles](${t.seeMoreLink})`:"";return`${e}\n**${t.title||t.name}**\n${t.description||""}\n${n}\n${r}\n${o}\n${i}`}if("card"===t.type&&t.content)return t.content;if("link"===t.type&&t.url)return`🔗 [${t.label||t.url}](${t.url})`;if("image"===t.type&&t.url)return``;if(t.systemInstruction&&"string"==typeof t.systemInstruction)return t.systemInstruction;const n=t.signupUrl||t.url||t.link||t.redirectUrl||t.actionPayload?.signupUrl||t.actionPayload?.url;return n?`🔗 [${t.label||t.title||e.tool.replace(/_/g," ")}](${n})`:"error"===t.status?t.error||"Error al ejecutar la acción":""}).filter(Boolean).join("\n\n---\n\n");t&&N(e=>[...e,{role:"bot",text:t,standalone:!0}])},v=e=>{if("quiz_question"===e?.eventName&&e?.data){const{question:t,buttons:n}=e.data;t&&n?.length&&(Te(),N(e=>[...e,{role:"bot",text:`📝 ${t}`,quizButtons:n,standalone:!0}]))}if("suggest_next_class"===e?.eventName&&e?.data){const{scheduledAt:t,title:n,body:r}=e.data;if("string"==typeof t&&""!==t.trim()){const e=new Date(t),o=[`📅 **Próxima clase** — ${Number.isNaN(e.getTime())?t:new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"short"}).format(e)}`];"string"==typeof n&&""!==n.trim()&&o.push(`**${n.trim()}**`),"string"==typeof r&&""!==r.trim()&&o.push(r.trim()),Te(),N(e=>[...e,{role:"bot",text:o.join("\n\n"),standalone:!0}])}}};_e.current={voiceReady:o,voiceAudioChunk:a,voiceInterrupted:s,voiceTurnComplete:l,voiceError:c,voiceEmotion:u,voiceUserTranscript:d,voiceUserTranscriptFinal:h,voiceUserTranscriptCorrected:f,voiceModelTranscript:m,voiceModelThinking:b,voiceToolVisual:y,voiceCustomEvent:v,voiceAgentSwitched:i},e.on("voice_ready",o),e.on("voice_audio_chunk",a),e.on("voice_interrupted",s),e.on("voice_turn_complete",l),e.on("voice_error",c),e.on("voice_emotion",u),e.on("voice_user_transcript",d),e.on("voice_user_transcript_final",h),e.on("voice_user_transcript_corrected",f),e.on("voice_model_transcript",m),e.on("voice_model_thinking",b),e.on("voice_tool_visual",y),e.on("custom_event",v),e.on("voice_agent_switched",i),e.on("voice_timeout",()=>{ae.current()});const w=e=>{p?.(e?.reason),N(e=>[...e,{role:"bot",text:"📞 Llamada finalizada."}]);const n=r?.();n?.connected&&setTimeout(()=>{try{n.emit("request_history")}catch{}},1500),setTimeout(()=>{t()},2500)};e.on("voice_call_ended",w),_e.current.voiceCallEnded=w,ee.current=!0},[r,xe,ke]),Ce=s(()=>{const e=r?.();if(!e||!ee.current)return;const t=_e.current;t.voiceReady&&e.off("voice_ready",t.voiceReady),t.voiceAudioChunk&&e.off("voice_audio_chunk",t.voiceAudioChunk),t.voiceInterrupted&&e.off("voice_interrupted",t.voiceInterrupted),t.voiceTurnComplete&&e.off("voice_turn_complete",t.voiceTurnComplete),t.voiceError&&e.off("voice_error",t.voiceError),t.voiceEmotion&&e.off("voice_emotion",t.voiceEmotion),t.voiceUserTranscript&&e.off("voice_user_transcript",t.voiceUserTranscript),t.voiceUserTranscriptFinal&&e.off("voice_user_transcript_final",t.voiceUserTranscriptFinal),t.voiceUserTranscriptCorrected&&e.off("voice_user_transcript_corrected",t.voiceUserTranscriptCorrected),t.voiceModelTranscript&&e.off("voice_model_transcript",t.voiceModelTranscript),t.voiceModelThinking&&e.off("voice_model_thinking",t.voiceModelThinking),t.voiceToolVisual&&e.off("voice_tool_visual",t.voiceToolVisual),t.voiceCustomEvent&&e.off("custom_event",t.voiceCustomEvent),t.voiceAgentSwitched&&e.off("voice_agent_switched",t.voiceAgentSwitched),t.voiceCallEnded&&e.off("voice_call_ended",t.voiceCallEnded),e.off("voice_timeout"),_e.current={},ee.current=!1},[r]),Ee=s(async()=>{const e=r?.();if(!e)return;const t=await navigator.mediaDevices.getUserMedia({audio:lc});K.current=t;const n=!1!==h.vad;ge.current=new Ac(n?h.vad:{energyOnly:!0}),ye.current=1,ve.current=0,n&&async function(e){const t=e.loadVad??Mc;try{const n=await t(),r=(t,n)=>{e.onFrame({speechProb:t?.isSpeech??0,rms:Oc(n)})},o=await n.MicVAD.new(function(e,t){const n={model:e.model??"v5",baseAssetPath:e.assetBaseUrl??Tc,onnxWASMBasePath:e.onnxWasmBaseUrl??"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",startOnLoad:!1,onFrameProcessed:t};if(e.audioContext&&(n.audioContext=e.audioContext),e.stream){const t=e.stream;n.getStream=async()=>t,n.pauseStream=async()=>{},n.resumeStream=async()=>{}}return n}(e,r));return O.info("[VAD] Silero speech detector ready"),new Pc(o)}catch(n){return O.warn("[VAD] Silero unavailable — falling back to energy gate",n),null}}({stream:t,assetBaseUrl:h.vadAssetBaseUrl,onFrame:({speechProb:e})=>{ye.current=e,ve.current=performance.now()}}).then(e=>{if(e){if(K.current)return be.current=e,e.start();e.destroy()}}).catch(()=>{});const o=new AudioContext({sampleRate:16e3});G.current=o,"suspended"===o.state&&await o.resume();const i=o.createMediaStreamSource(t),a=function(e,t){const n=e.createBiquadFilter();n.type="highpass",n.frequency.value=cc,n.Q.value=uc;const r=e.createBiquadFilter();r.type="highpass",r.frequency.value=dc,r.Q.value=pc;const o=e.createBiquadFilter();o.type="peaking",o.frequency.value=hc,o.Q.value=fc,o.gain.value=mc;const i=e.createBiquadFilter();i.type="lowpass",i.frequency.value=gc,i.Q.value=bc;const a=e.createDynamicsCompressor();return a.threshold.value=yc,a.knee.value=vc,a.ratio.value=wc,a.attack.value=xc,a.release.value=kc,t.connect(n),n.connect(r),r.connect(o),o.connect(i),i.connect(a),a}(o,i),s=o.createAnalyser();if(s.fftSize=256,a.connect(s),J.current=s,!te.current){const e=new Blob([Cc(h.voiceGate)],{type:"application/javascript"});te.current=URL.createObjectURL(e)}await o.audioWorklet.addModule(te.current);const l=new AudioWorkletNode(o,"voice-pcm-processor");Y.current=l,l.port.onmessage=t=>{const n=ge.current;if(!n)return;const r=performance.now()-ve.current<600,o=ue.current,i=function(e){return!!e.isPlaying&&!!e.contextRunning&&e.nextPlayTime>e.currentTime}({isPlaying:he.current,contextRunning:"running"===o?.state,nextPlayTime:fe.current,currentTime:o?.currentTime??0}),{frame:a,confirmedSpeech:s}=function(e){return e.botSpeaking&&!e.vadFresh?{frame:{speechProb:0,rms:0,botSpeaking:!0},confirmedSpeech:!1}:{frame:{speechProb:e.vadFresh?e.speechProb:1,rms:e.rms,botSpeaking:e.botSpeaking},confirmedSpeech:e.vadFresh}}({botSpeaking:i,vadFresh:r,speechProb:ye.current,rms:t.data.rms}),{shouldStream:l,event:c}=n.process(a);"barge_in"===c&&ke();const u=function(e){return!e.botSpeaking||e.gateShouldStream}({gateShouldStream:l,botSpeaking:i});if(u&&e.connected&&!k){const n=function(e){return e.confirmedSpeech||!e.vadFresh}({confirmedSpeech:s,vadFresh:r});e.emit("voice_audio_chunk",{data:$c(t.data.pcm),speech:n})}},a.connect(l);const c=()=>{if(!J.current)return;const e=new Uint8Array(J.current.frequencyBinCount);J.current.getByteFrequencyData(e);const t=e.reduce((e,t)=>e+t,0)/e.length;C(t/255),X.current=requestAnimationFrame(c)};c()},[r,k,h.voiceGate,h.vad,h.vadAssetBaseUrl,ke]),ze=s(()=>{cancelAnimationFrame(X.current),be.current?.destroy(),be.current=null,ge.current=null,ye.current=1,ve.current=0,Y.current?.disconnect(),Y.current=null,K.current?.getTracks().forEach(e=>e.stop()),K.current=null,G.current?.close(),G.current=null,J.current=null,C(0)},[]),Ae=s(async()=>{const e=r?.();if(e?.connected){g("connecting"),x(0),N([]),z(null),$(void 0),U(void 0),V(void 0),H(!1),de.current=[],Se(),ue.current&&"closed"!==ue.current.state||(ue.current=new AudioContext({sampleRate:Fc})),ue.current.resume().catch(()=>{});try{await Ee()}catch(t){return console.error("[VoiceCall] Mic error:",t),void g("idle")}e.emit("voice_start",{voice:"Kore"}),Z.current=setInterval(()=>{x(e=>e+1)},1e3),Ie()}else console.error("[VoiceCall] Socket not connected")},[r,Se,Ee]),Ne=s(()=>{ze(),me.current.forEach(e=>{try{e.stop()}catch{}}),me.current=[],de.current=[],fe.current=0,he.current=!1,ue.current?.close(),ue.current=null,Z.current&&(clearInterval(Z.current),Z.current=null),le.current&&(clearInterval(le.current),le.current=null);const e=r?.();e?.connected&&(e.emit("voice_stop"),setTimeout(()=>{try{e.emit("request_history")}catch{}},1500)),Ce(),g("idle"),C(0),x(0),_(!1),N([]),D(!1),R(null),$(void 0),U(void 0),V(void 0),H(!1),t()},[r,ze,Ce,t]);a(()=>{ae.current=Ne},[Ne]);const Te=s(()=>{ce.current=0,D(!1)},[]),Ie=s(()=>{ce.current=0,le.current&&clearInterval(le.current),le.current=setInterval(()=>{ce.current+=1;const e=ce.current;e>=90&&e<120&&D(!0),e>=120&&ae.current()},1e3)},[]),Oe=s(()=>{_(e=>!e)},[]),Me=s(()=>{const e=M.trim();if(!e)return;const t=r?.();t?.connected&&(t.emit("voice_text_input",{text:e}),P(""),I(!1))},[M,r]);if(a(()=>{e&&"idle"===m&&Ae()},[e]),a(()=>{ie.current?.scrollIntoView({behavior:"smooth"})},[A]),a(()=>()=>{ze(),Z.current&&clearInterval(Z.current),Ce()},[]),!e)return null;const Pe="speaking"===m?h.speakingColor:"thinking"===m?h.thinkingColor:"listening"===m?h.listeningColor:n,Le=W?F:o,De=W?B:l,je=(W?q:c)||h.avatar3dUrl;let Re=-1;for(let i=A.length-1;i>=0;i--)if(A[i].quizButtons&&A[i].quizButtons.length>0){Re=i;break}const Fe=Re>=0?A[Re]:null;/* @__PURE__ */
|
|
121
121
|
return y("div",{className:Ot("absolute inset-0 z-50 flex flex-col overflow-hidden","animate-in fade-in duration-300"),style:{backgroundColor:"#0a0a0f",borderRadius:"inherit"},children:[
|
|
122
122
|
/* @__PURE__ */y("div",{className:"absolute inset-0 pointer-events-none",style:{overflow:"hidden"},children:[
|
|
123
123
|
/* @__PURE__ */b("div",{className:"absolute rounded-full",style:{width:"300px",height:"300px",top:"-80px",right:"-60px",background:`radial-gradient(circle, ${Pe}18 0%, transparent 70%)`,transition:"background 1.5s ease",filter:"blur(40px)"}}),
|
|
@@ -216,4 +216,4 @@ return y("div",{className:`relative h-full w-full overflow-hidden ${t}`,children
|
|
|
216
216
|
/* @__PURE__ */b(Kb,{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
218
|
/* @__PURE__ */b(de,{className:"h-5 w-5","aria-hidden":!0}),u&&/* @__PURE__ */b("span",{className:"text-xs",children:u})]})]})}const Xb="https://api.botuyo.com";class ey 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 ty={"--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%"},ny=p(()=>Promise.resolve().then(()=>Vb).then(e=>({default:e.ChatWidgetWithProviders})));class ry{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||Xb},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=R.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(ty).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(ty).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||Xb,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(ny,t));this.root.render(n.createElement(ey,null,n.createElement(D,{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 oy=new ry;window.BotUyoChat=oy;export{Qb as A,ry as B,qb as C,X as L,Wb as P,he as X,q as a,Ot as b,Hb as c,Db as d,Ub as e,D as f,Lt as g,jb as h,oy as i,j,O as l,Jb as s,F as u};
|
|
219
|
-
//# sourceMappingURL=standalone-
|
|
219
|
+
//# sourceMappingURL=standalone-Xxf8KK4I.js.map
|