@eshal-bot/chat-widget 0.1.44 → 0.1.45

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.
@@ -1,4 +1,4 @@
1
- import e,{useMemo as t,useState as n,useRef as r,useEffect as a,useCallback as o,forwardRef as i,createElement as s}from"react";import{createRoot as l}from"react-dom/client";import{Fragment as c,jsx as u,jsxs as d}from"react/jsx-runtime";import{createPortal as p}from"react-dom";function g(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}function m(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?f(Object(n),!0).forEach(function(t){m(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function b(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}const y="processing_start",w="text_chunk",v="processing_end",E="complete",S="error",k="human_decision_required",T=e=>{if(!e||"string"!=typeof e)return null;if("[DONE]"===e||"[PROCESSING]"===e)return null;try{const n=JSON.parse(e);if(!n||"object"!=typeof n)return null;const r=n.type||n.event_type;if(r===w||n.content){var t;const e=n.content||(null===(t=n.choices)||void 0===t||null===(t=t[0])||void 0===t||null===(t=t.delta)||void 0===t?void 0:t.content)||"";return h({type:w,content:e},n)}return r===y||"processing_start"===n.type?h({type:y},n):r===v||"processing_end"===n.type?h({type:v},n):r===E||"complete"===n.type?h({type:E,finalContent:n.finalContent||n.content||""},n):r===S||"error"===n.type?h({type:S,error:n.error||n.message||"Unknown error"},n):r===k||"human_decision_required"===n.type?h({type:k,decisionId:n.decisionId||n.decision_id,question:n.question||"",options:n.options||[],context:n.context||{}},n):r?h({type:r},n):n}catch(e){return null}},A=["prompts"],x=()=>({id:"skeleton-".concat(Date.now()),role:"assistant",content:"",timestamp:new Date,isProcessing:!0}),I=e=>{if(!Array.isArray(e)||0===e.length)return;const t=e.map(e=>({type:e.type||"prompt",text:"string"==typeof e.text?e.text:"",confidence:"number"==typeof e.confidence?e.confidence:void 0})).filter(e=>e.text);return t.length?t:void 0},C=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e(e=>{const r=[...e||[]],a=r[r.length-1];if("assistant"===(null==a?void 0:a.role)){const e=n||{},{prompts:o}=e,i=b(e,A);r[r.length-1]=h(h(h({},a),i),{},{content:t,isProcessing:!1},null!=o&&{prompts:I(o)})}return r})},R=(e,t,n,r,a)=>{var o;if(e&&e.type)switch(e.type){case y:break;case w:a.current||(a.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],x()]}return e}));const i=e.content||(null===(o=e.choices)||void 0===o||null===(o=o[0])||void 0===o||null===(o=o.delta)||void 0===o?void 0:o.content)||"";i&&(n.current+=i,r(n.current));break;case v:(e=>{e(e=>{const t=[...e||[]],n=t[t.length-1];return null!=n&&n.isProcessing&&(t[t.length-1]=h(h({},n),{},{isProcessing:!1})),t})})(t);break;case E:{const r=e.finalContent||n.current,a={};"boolean"==typeof e.conclusionDetected?a.conclusionDetected=e.conclusionDetected:"boolean"==typeof e.conclusion_detected&&(a.conclusionDetected=e.conclusion_detected);const o=h(h({},a),{},{prompts:e.prompts});C(t,r,o);break}case S:((e,t)=>{e(e=>{const n=[...e||[]],r=n[n.length-1];return"assistant"===(null==r?void 0:r.role)&&(n[n.length-1]=h(h({},r),{},{content:(r.content||"")+"\n\nError: ".concat(t),isProcessing:!1})),n})})(t,e.error||"Unknown error occurred");break;case k:{const n={id:"decision-".concat(Date.now()),role:"assistant",content:e.question||"",timestamp:new Date,isProcessing:!1,requiresDecision:!0,decisionData:{decisionId:e.decisionId,question:e.question,options:e.options||[],context:e.context||{}}};t(e=>[...(e||[]).filter(e=>!e.isProcessing||e.content),n]);break}default:console.warn("Unknown stream event type:",e.type)}},N=async(e,t)=>{const n=(e=>{let t=null,n=null,r=0;const a=o=>{if(o-r<16)n=requestAnimationFrame(a);else{if(null!==t){const n=t;t=null,r=o,e(e=>{const t=[...e||[]],r=t[t.length-1];return"assistant"===(null==r?void 0:r.role)&&(t[t.length-1]=h(h({},r),{},{content:n})),t})}n=null}};return e=>{t=e,null===n&&(n=requestAnimationFrame(a))}})(t),r=e.getReader(),a=new TextDecoder;let o="";const i={current:""},s={current:!1};try{for(;;){const{value:e,done:m}=await r.read();if(m)break;o+=a.decode(e,{stream:!0});const f=o.split(/\r?\n\r?\n/);o=f.pop()||"";for(const e of f){var l,c;const r=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);if(0===r.length)continue;const a=r.filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim());if(0===a.length)continue;const o=a.join("\n");if("[DONE]"===o)continue;let m;try{m=JSON.parse(o)}catch(e){continue}if(m){if(m.type){if("processing_start"===m.type||"processing_end"===m.type)continue;if("text_chunk"===m.type){var u;const e=(null===(u=m.choices)||void 0===u||null===(u=u[0])||void 0===u||null===(u=u.delta)||void 0===u?void 0:u.content)||m.content;e&&(s.current||(s.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],x()]}return e})),i.current+=e,n(i.current));continue}if("complete"===m.type){var d,p,g;const e=null!==(d=null!==(p=m.Sources)&&void 0!==p?p:m.sources)&&void 0!==d?d:[],n=Array.isArray(e)?e.map(e=>{var t,n,r,a,o;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"website",source_id:null!==(r=e.sourceid)&&void 0!==r?r:e.source_id,source_name:null!==(a=null!==(o=e.source_name)&&void 0!==o?o:e.sourceName)&&void 0!==a?a:"",url:e.url}}).filter(e=>e.source_id||e.url):[],r=(null===(g=m.choices)||void 0===g||null===(g=g[0])||void 0===g||null===(g=g.delta)||void 0===g?void 0:g.content)||m.finalContent||i.current,a={};"boolean"==typeof m.conclusionDetected?a.conclusionDetected=m.conclusionDetected:"boolean"==typeof m.conclusion_detected&&(a.conclusionDetected=m.conclusion_detected);const o=h(h({},a),{},{prompts:m.prompts});C(t,r,o),n.length>0&&t(e=>{const t=[...e||[]],a=t[t.length-1];return"assistant"===(null==a?void 0:a.role)&&(t[t.length-1]=h(h({},a),{},{sources:n,content:r,isProcessing:!1})),t});continue}if("error"===m.type){t(e=>{const t=[...e||[]],n=t[t.length-1];return"assistant"===(null==n?void 0:n.role)&&(t[t.length-1]=h(h({},n),{},{content:(n.content||"")+"\n\nError: ".concat(m.error||"Unknown error occurred"),isProcessing:!1})),t});continue}const e=T(o);if(e&&e.type){console.log("🔍 Parsed stream event:",e.type,e),R(e,t,i,n,s);continue}}if("chat.completion.chunk"===m.object&&null!==(l=m.choices)&&void 0!==l&&null!==(l=l[0])&&void 0!==l&&null!==(l=l.delta)&&void 0!==l&&l.content)s.current||(s.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],x()]}return e})),i.current+=m.choices[0].delta.content,n(i.current);else if(null!==(c=m.choices)&&void 0!==c&&null!==(c=c[0])&&void 0!==c&&c.finish_reason&&null!==m.choices[0].finish_reason){const e={prompts:m.prompts};C(t,i.current,e)}}}}}finally{r.releaseLock()}};async function _(e){if("undefined"==typeof window)throw new Error("Audio recorder can only run in the browser");const t=new AudioContext({sampleRate:16e3}),n=new Blob(["\n class PCMRecorderProcessor extends AudioWorkletProcessor {\n process(inputs) {\n if (!inputs.length || !inputs[0].length) {\n return true;\n }\n const inputChannel = inputs[0][0];\n this.port.postMessage(new Float32Array(inputChannel));\n return true;\n }\n }\n registerProcessor('pcm-recorder-processor', PCMRecorderProcessor);\n "],{type:"application/javascript"}),r=URL.createObjectURL(n);await t.audioWorklet.addModule(r),URL.revokeObjectURL(r);const a=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1}}),o=t.createMediaStreamSource(a),i=new AudioWorkletNode(t,"pcm-recorder-processor");return i.port.onmessage=t=>{const n=function(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=Math.max(-1,Math.min(1,e[n]))*L;return t.buffer}(t.data);e(n)},o.connect(i),[i,t,a]}function O(e){e&&e.getTracks().forEach(e=>e.stop())}const L=32767;const D=.025,P=200,M=1e3,F=300;function B(e,t){var n,r,a,o;const i=e.sampleRate,s=null!==(n=e.energyThreshold)&&void 0!==n?n:D,l=null!==(r=e.speechStartMs)&&void 0!==r?r:P,c=null!==(a=e.hangoverMs)&&void 0!==a?a:M,u=null!==(o=e.preRollMs)&&void 0!==o?o:F;let d=!1,p=0,g=0,m=[],f=0;return{process:e=>{const n=(e=>e.byteLength/2/i*1e3)(e),r=function(e){const t=new Int16Array(e);if(0===t.length)return 0;let n=0;for(let e=0;e<t.length;e+=1){const r=t[e]/32768;n+=r*r}return Math.sqrt(n/t.length)}(e)>=s;if(d)t.onVoiceFrame(e),r?g=0:(g+=n,g>=c&&(d=!1,p=0,g=0,t.onSpeechEnd()));else{for(m.push({pcm:e,durationMs:n}),f+=n;f>u&&m.length>1;){var a;const e=m.shift();f-=null!==(a=null==e?void 0:e.durationMs)&&void 0!==a?a:0}if(r){if(p+=n,p>=l){d=!0,g=0;for(const e of m)t.onVoiceFrame(e.pcm);m=[],f=0}}else p=0}},reset:()=>{d=!1,p=0,g=0,m=[],f=0},isSpeaking:()=>d}}const U=e=>e.replace(/([\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uff00-\uffef])\s+([\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uff00-\uffef])/g,"$1$2"),z=e=>{const t=(e||"").trim();return t?/^https?:\/\//i.test(t)||/^[a-z][a-z0-9+.-]*:/i.test(t)?t:"https://".concat(t.replace(/^\/+/,"")):""},G=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.filter(Boolean).join(" ")},j={fullname:0,name:0,username:0,email:1,phone:2,mobileno:2},q=e=>{var t;if(!e)return 99;const n=String(e).toLowerCase();return null!==(t=j[n])&&void 0!==t?t:99},H="eshal_chat_session",$="eshal_chat_session_messages";function V(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:50;if(!Array.isArray(e))return[];("number"!=typeof t||t<=0)&&(t=200),("number"!=typeof n||n<=0||n>=t)&&(n=Math.min(50,t-1));let r=e;for(;r.length>t;)r=r.slice(n);return r}const W=(e,t,n,r)=>{if(e&&t)try{const a=null==r?void 0:r.cap,o=null==r?void 0:r.trimBatch,i=function(e){return Array.isArray(e)?e.filter(e=>e&&!e.isWelcome&&(e.content||Array.isArray(e.sources)&&e.sources.length>0)).map(e=>{var t;return h(h(h({id:e.id,role:e.role,content:e.content,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():"string"==typeof e.timestamp?e.timestamp:(new Date).toISOString(),type:null!==(t=e.type)&&void 0!==t?t:null},Array.isArray(e.sources)&&e.sources.length>0?{sources:e.sources}:{}),void 0!==e.feedback?{feedback:e.feedback}:{}),Array.isArray(e.prompts)&&e.prompts.length>0?{prompts:e.prompts}:{})}):[]}(V(n,a,o));localStorage.setItem("".concat($,"_").concat(e,"_").concat(t),JSON.stringify(i))}catch(e){}},Y=(e,t)=>{if(e&&t)try{localStorage.removeItem("".concat($,"_").concat(e,"_").concat(t))}catch(e){}},K=(e,t)=>{if(null==e||!t)return null;const n={MINUTES:6e4,HOURS:36e5,DAYS:864e5}[t.toUpperCase()];return void 0===n?(console.warn("[Session] Unknown timeout unit: ".concat(t)),null):Number(e)*n},Z=e=>{try{const t=localStorage.getItem("".concat(H,"_").concat(e));return t?JSON.parse(t):null}catch(e){return null}},X=(e,t,n)=>{if(!e||!e.lastActivity)return!1;if(null==t||0===t)return!0;if(null!==t&&null!==n){const r=JSON.stringify({value:t,unit:null==n?void 0:n.toUpperCase()});if(e.settingsSnapshot&&e.settingsSnapshot!==r)return console.log("[Session] Timeout settings changed — treating session as invalid."),!1}if(null===e.firstInteractionAt)return!0;const r=K(t,n);if(!r)return!0;const a=new Date(e.lastActivity).getTime(),o=Date.now()-a,i=o<r;return i||console.log("[Session] Session expired. Elapsed: ".concat(Math.floor(o/1e3),"s, Timeout: ").concat(Math.floor(r/1e3),"s")),i},Q=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{const r=(new Date).toISOString();console.log("[Session] Saving new session: ".concat(t," for org: ").concat(e)),localStorage.setItem("".concat(H,"_").concat(e),JSON.stringify(h({conversationId:t,lastActivity:r,createdAt:r,firstInteractionAt:null},n)))}catch(e){}},J=e=>{try{const t=Z(e);if(!t)return;const n=(new Date).toISOString();t.lastActivity=n,t.firstInteractionAt||(t.firstInteractionAt=n),localStorage.setItem("".concat(H,"_").concat(e),JSON.stringify(t))}catch(e){}},ee=(e,t)=>{try{if(!e)return;if(!Array.isArray(t)||0===t.length)return void localStorage.removeItem("".concat(H,"_prompts_").concat(e));localStorage.setItem("".concat(H,"_prompts_").concat(e),JSON.stringify(t))}catch(e){}},te=e=>{let{id:t,role:n,content:r,isProcessing:a=!1,metadata:o}=e;return{id:t,role:n,content:r,timestamp:new Date,isProcessing:a,metadata:o}},ne=e=>e&&e.length>0?e:[],re=e=>{let{welcomeMessage:i,quickQuestions:s=[],apiBaseUrl:l,apiKey:c,organizationId:u,autoOpen:d,openDelay:p,darkMode:g,enableVoiceInteraction:m=!1,provideCitations:f=!0,onboardingQuestions:b=[],onboardingEnabled:y=!1,collectionPrompt:w,inactivityTimeoutValue:v,inactivityTimeoutUnit:E,messageLimits:S}=e;const k=t(()=>({cap:"number"==typeof(null==S?void 0:S.cap)&&S.cap>0?S.cap:200,trimBatch:"number"==typeof(null==S?void 0:S.trimBatch)&&S.trimBatch>0?S.trimBatch:50}),[null==S?void 0:S.cap,null==S?void 0:S.trimBatch]),[T,A]=n(d),[x,I]=n(!1),[C,R]=n(g),[L,D]=n(()=>{try{const e=Z(u);if(void 0!==v&&e&&X(e,v,E))return[]}catch(e){}return i?[h(h({},te({id:Date.now().toString(),role:"assistant",content:i})),{},{isWelcome:!0})]:[]}),[P,M]=n(""),[F,z]=n(!1),G=r(null),j=r(1),[re,ae]=n(null),[oe,ie]=n(null),se=r(null);a(()=>{se.current=oe},[oe]);const[le,ce]=n(null),ue=r(null);a(()=>{ue.current=le},[le]);const[de,pe]=n(!1),[ge,me]=n(()=>{try{const e=Z(u);if(e&&e.onboardingCompleted)return!0}catch(e){}return!1}),[fe,he]=n(null),[be,ye]=n({}),we=r(!1),[ve,Ee]=n(!1),[Se,ke]=n(!1),[Te,Ae]=n([]),[xe,Ie]=n("idle"),[Ce,Re]=n(null),[Ne,_e]=n(!1),[Oe,Le]=n(()=>{try{const e=Z(u);if(void 0!==v&&e&&X(e,v,E))return e.conversationId}catch(e){}return"widget-session-".concat(Math.random().toString(36).slice(2,9))}),De=r(null),Pe=r(null),Me=r(null),Fe=r(null),Be=r(null),Ue=r(null),ze=r(null),Ge=r(null),je=r(null),qe=r(!1),He=r(!1);r(null);const $e=r(null);r(null);const Ve=r(!1),We=r(null),Ye=r(!1),Ke=r(!1),Ze=r(null),Xe=r(null),Qe=r(null),Je=r(null),et=t(()=>{if(!u)return null;const e=(e=>{if(!e)return"wss://dev.eshal.ai/voice/ws";try{const t=new URL(e);return t.protocol=t.protocol.replace(/^http/,"ws"),t.pathname="/voice/ws",t.toString().replace(/\/$/,"")}catch(e){return console.error("Invalid API base URL provided for WebSocket:",e),"wss://dev.eshal.ai/voice/ws"}})(l);return"".concat(e,"/").concat(u,"/").concat(Oe)},[l,u,Oe]),tt=o(()=>{const e="msg-".concat(j.current);return j.current+=1,e},[]);a(()=>{if(d&&p>0){const e=setTimeout(()=>A(!0),p);return()=>clearTimeout(e)}},[d,p]),a(()=>{let e=!1;return(async()=>{try{const{default:t}=await Promise.resolve().then(function(){return LE}),n=new t({cache:!0,onError:()=>{}}),r=await n.init();if(e)return;if(null!=r&&r.fingerprintId&&(Qe.current=r.fingerprintId),null!=r&&r.geo||null!=r&&r.ip){const e=r.geo||{};Je.current={ip:r.ip||e.ip||null,country:e.country||null,countryCode:e.countryCode||null,region:e.region||null,city:e.city||null,timezone:e.timezone||null}}}catch(e){}})(),()=>{e=!0}},[]),a(()=>{R(g)},[g]);const nt=r(!1),rt=r(!1),at=r(!1),ot=r({value:null,unit:null});a(()=>{if(!u||!Oe||void 0===v)return;const e=Z(u);if(e&&X(e,v,E)){if(Oe!==e.conversationId)return void Le(e.conversationId);if(!nt.current){nt.current=!0;const e=((e,t)=>{if(!e||!t)return[];try{const n=localStorage.getItem("".concat($,"_").concat(e,"_").concat(t));if(!n)return[];const r=JSON.parse(n);return Array.isArray(r)?r.map(e=>h(h({},e),{},{timestamp:e.timestamp?new Date(e.timestamp):new Date})):[]}catch(e){return[]}})(u,Oe);if(e.length>0){if(rt.current=!0,i){var t;const n=null===(t=e[0])||void 0===t?void 0:t.timestamp,r=n instanceof Date?n.getTime():n?new Date(n).getTime():Date.now(),a=h(h({},te({id:"welcome-restored",role:"assistant",content:i})),{},{isWelcome:!0,timestamp:new Date(r-1)});D([a,...e])}else D(e);if(!e.some(e=>"assistant"===e.role&&Array.isArray(e.prompts)&&e.prompts.length>0)){const e=(e=>{try{const t=localStorage.getItem("".concat(H,"_prompts_").concat(e));return t&&JSON.parse(t)||[]}catch(e){return[]}})(u);e.length>0&&D(t=>{const n=[...t];for(let t=n.length-1;t>=0;t-=1)if("assistant"===n[t].role){n[t]=h(h({},n[t]),{},{prompts:e});break}return n})}}}}else if(nt.current||(nt.current=!0),e&&Oe===e.conversationId){const e="widget-session-".concat(Math.random().toString(36).slice(2,9));console.warn("[Session] Rotating expired ID ".concat(Oe," -> ").concat(e)),Y(u,Oe),Le(e)}else null!=e&&e.conversationId&&e.conversationId!==Oe&&Y(u,e.conversationId),e&&e.conversationId===Oe||Q(u,Oe,{settingsSnapshot:JSON.stringify({value:v,unit:null==E?void 0:E.toUpperCase()})})},[u,Oe,l,v,E]),a(()=>{if(u&&L&&0!==L.length)for(let e=L.length-1;e>=0;e-=1){const t=L[e];if("assistant"===(null==t?void 0:t.role)&&Array.isArray(t.prompts)&&t.prompts.length>0)return void ee(u,t.prompts)}},[L,u]),a(()=>{ve||F||L.length<=k.cap||D(e=>V(e,k.cap,k.trimBatch))},[L.length,ve,F,k.cap,k.trimBatch]),a(()=>{u&&Oe&&(ve||F||W(u,Oe,L,k))},[L,u,Oe,ve,F,k]),a(()=>{if(!y||ge)return;ne(b).length>0&&pe(!0)},[y,ge,b]),a(()=>{i&&!rt.current&&D(e=>{if(!e.length)return[h(h({},te({id:Date.now().toString(),role:"assistant",content:i})),{},{isWelcome:!0})];const[t,...n]=e;return t.isWelcome?[h(h({},t),{},{content:i}),...n]:e})},[i]),o(e=>{D(t=>t.map(t=>t.id===e.id?h(h({},t),e.update(t)):t))},[]);const it=o(function(e){if(!e)return;const t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).replaceMarker||null;D(n=>[...t?(n||[]).filter(e=>{var n;return(null==e||null===(n=e.metadata)||void 0===n?void 0:n.synthesizedKind)!==t}):n||[],te({id:tt(),role:"assistant",content:e,metadata:t?{synthesizedKind:t}:void 0})])},[tt]),st=o(async(e,t,n)=>{const r=e.trim();if(!r)return{success:!1,error:"Message cannot be empty"};if(t&&!["inquiry","complaint","technical"].includes((t||"").toLowerCase())||(ue.current=r,ce(r)),!l)return D(e=>[...e||[],te({id:tt(),role:"assistant",content:"Sorry, I'm having trouble connecting right now. Please try again.",isProcessing:!1})]),console.error("Chat widget configuration error: apiBaseUrl is required for streaming."),{success:!1,error:"API base URL is required"};const a=["inquiry","complaint","technical","userName","email","phone","fullname","mobileno"];let o="inquiry";if(t){const e=t.toLowerCase();"fullname"===e||"name"===e?o="userName":"email"===e?o="email":"phone"===e||"mobileno"===e?o="phone":a.includes(e)&&(o=e)}if("inquiry"===o||"complaint"===o||"technical"===o){const e=te({id:tt(),role:"user",content:r});D(t=>{const r=(t||[]).map(e=>{var t;return"assistant"===e.role&&null!==(t=e.prompts)&&void 0!==t&&t.length?h(h({},e),{},{prompts:void 0}):e});return n&&n.skipUserAppend?r:[...r,e]}),M(""),z(!0)}else M("");try{const e=h(h(h(h(h({message:r,type:o,conversationId:Oe,enable_citation:null==f||f,channel:"WIDGET"},Qe.current?{fingerprintId:Qe.current}:{}),Je.current?{visitor:Je.current}:{}),re&&(re.category||re.tags&&re.tags.length)?{filter:re}:{}),se.current?{routing:se.current}:{}),{},{messageHistory:L.filter(e=>!e.isProcessing&&e.content&&e.content.trim()&&!["userName","email","phone"].includes(e.type)).map(e=>{let t;return t=e.timestamp instanceof Date?e.timestamp.toISOString():"string"==typeof e.timestamp?e.timestamp:e.timestamp?new Date(e.timestamp).toISOString():(new Date).toISOString(),{id:e.id,role:e.role,content:e.content,timestamp:t,isProcessing:!1}})}),t=await(async(e,t,n)=>{const r={"Content-Type":"application/json",Accept:"text/event-stream"};n&&(r["x-eshal-org"]=n);const a=await fetch("".concat(t.replace(/\/$/,""),"/api/v1/support"),{method:"POST",headers:r,credentials:"include",body:JSON.stringify(e)});if(!a.ok)throw new Error("HTTP error! status: ".concat(a.status));if(!a.body)throw new Error("Response body is null");return a.body})(e,l,u);if("userName"===o||"email"===o||"phone"===o){const e=t.getReader(),n=new TextDecoder;for(;;){const{done:t,value:r}=await e.read();if(t)break;n.decode(r)}return{success:!0}}return"inquiry"===o||"complaint"===o||"technical"===o?(await N(t,D),J(u),{success:!0}):(J(u),{success:!0})}catch(e){return console.error("Error sending message:",e),"inquiry"!==o&&"complaint"!==o&&"technical"!==o||(z(!1),D(e=>[...(e||[]).filter(e=>!e.isProcessing),te({id:tt(),role:"assistant",content:"Sorry, I'm having trouble connecting right now. Please try again.",isProcessing:!1})])),{success:!1,error:e instanceof Error?e.message:"Failed to send message"}}finally{"inquiry"!==o&&"complaint"!==o&&"technical"!==o||z(!1)}},[l,c,tt,u,L,Oe,oe,re,f]),lt=o(async e=>{const t=ne(b);if(0===t.length)return;const n=[...t].sort((e,t)=>q(e.fieldType)-q(t.fieldType));for(const t of n){var r;const n=t.fieldType||"question",a=(null!==(r=e[n])&&void 0!==r?r:"").trim();if(!a)continue;const o=await st(a,n);if(null==o||!o.success){const e=te({id:tt(),role:"assistant",content:(null==o?void 0:o.error)||"Something went wrong. Please try again.",isProcessing:!1});return void D(t=>[...t,e])}}pe(!1),me(!0),(e=>{try{const t=Z(e);if(!t)return;t.onboardingCompleted=!0,localStorage.setItem("".concat(H,"_").concat(e),JSON.stringify(t))}catch(e){}})(u),ye(t=>h(h({},t),e)),fe&&!we.current&&(we.current=!0,setTimeout(()=>{M(fe),he(null)},500))},[b,st,tt,fe,u]),ct=o(async()=>{const e=P.trim();e&&await st(e)},[P,st]),ut=o(async()=>{await ct()},[ct]),dt=o(async e=>{const t=null==e?void 0:e.trim();t&&await st(t)},[st]),pt=o(async(e,t,n)=>{if(D(t=>t.filter(t=>{var n;return(null===(n=t.decisionData)||void 0===n?void 0:n.decisionId)!==e})),"routing-clarification"===e){const e=String(n||"").toLowerCase(),r="database"===t||"knowledge"===t?t:"database"===e||"knowledge"===e?e:null;if(r){se.current=r,ie(r);const e=ue.current;ue.current=null,ce(null),e&&e.trim()&&setTimeout(()=>{st(e,"inquiry",{skipUserAppend:!0}).catch(e=>console.warn("[routing-clarification] re-send failed:",e))},0)}return}if("connect_agent"===n){const e=te({id:tt(),role:"assistant",content:"Great! I'm setting up a connection with a live customer service agent. Please hold on for a moment while I transfer you."});D(t=>[...t,e])}else if("decline"===n){const e=te({id:tt(),role:"assistant",content:"I understand. I apologize that I don't have specific information about your query in my knowledge base. Is there anything else I can help you with?"});D(t=>[...t,e])}},[tt,st,le]);o(()=>{Ge.current&&(Ae(e=>e.map(e=>e.id===Ge.current?h(h({},e),{},{isProcessing:!1}):e)),Ge.current=null)},[]);const gt=o(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(Ye.current=!0,!e||"string"==typeof e&&!e.trim())return void(t&&Ge.current&&(Ae(e=>e.map(e=>e.id===Ge.current?h(h({},e),{},{isProcessing:!1}):e)),Ge.current=null));const n=U(e);Ae(e=>{const r=e.length;let a=[...e];if(Ge.current){if(a.some(e=>e.id===Ge.current))a=a.map(e=>{if(e.id!==Ge.current)return e;const r=U("".concat(e.content||"").concat(n));return h(h({},e),{},{content:r,isProcessing:!t,metadata:h(h({},e.metadata),{},{transcriptionType:"input"})})});else{console.error("[BIDI] appendUserTranscription: ERROR - user message not found!",{expectedId:Ge.current,existingIds:a.map(e=>e.id)});const e="bidi-input-".concat(Date.now());Ge.current=e;const r=te({id:e,role:"user",content:n,isProcessing:!t,metadata:{source:"bidi",transcriptionType:"input"}});a=[...a,r],console.log("[BIDI] appendUserTranscription: recreated lost user message",{messageId:e})}}else{const r="bidi-input-".concat(Date.now()),o=Date.now(),i=e.filter(e=>{var t;return"assistant"===e.role&&"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)}).sort((e,t)=>{const n=e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime();return(t.timestamp instanceof Date?t.timestamp.getTime():new Date(t.timestamp).getTime())-n})[0];let s;if(i){const e=i.timestamp instanceof Date?i.timestamp.getTime():new Date(i.timestamp).getTime();s=new Date(e-1)}else s=new Date(o);const l=te({id:r,role:"user",content:n,isProcessing:!t,timestamp:s,metadata:{source:"bidi",transcriptionType:"input"}});a.some(e=>e.id===r)?(console.warn("[BIDI] appendUserTranscription: message already exists, updating instead",{messageId:r}),Ge.current=r,a=a.map(e=>e.id===r?h(h({},e),{},{content:"".concat(e.content||"").concat(n),isProcessing:!t}):e)):(a=[...a,l],Ge.current=r)}return a.length<r?(console.error("[BIDI] appendUserTranscription: CRITICAL ERROR - losing messages!",{prevLength:r,resultLength:a.length,prevIds:e.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}}),resultIds:a.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}})}),e):a}),t&&(Ge.current=null,z(!0))},[]),mt=o(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(z(!1),console.log("[BIDI] appendAssistantContent called",{text:null==e?void 0:e.substring(0,50),finished:t,currentAssistantId:je.current,currentInputId:Ge.current}),!e||"string"==typeof e&&!e.trim())return console.log("[BIDI] appendAssistantContent: skipping empty text"),void(t&&je.current&&(Ae(e=>e.map(e=>e.id!==je.current?e:h(h({},e),{},{isProcessing:!1}))),je.current=null,$e.current=null));const n="".concat(je.current||"new","-").concat(e.substring(0,100),"-").concat(t);if(Ve.current&&We.current===n)return;Ve.current=!0,We.current=n;const r=Ge.current;if(Ae(n=>{const a=n.length;let o=[...n];if(console.log("[BIDI] appendAssistantContent: starting update",{prevLength:a,prevMessageIds:n.map(e=>e.id),inputMessageIdToFinalize:r,currentAssistantId:je.current,textLength:e.length}),r){o.some(e=>e.id===r)?o=o.map(e=>e.id===r?h(h({},e),{},{isProcessing:!1}):e):console.warn("[BIDI] appendAssistantContent: input message not found for finalization",{inputMessageId:r,existingIds:o.map(e=>e.id)})}if(je.current){if(o.some(e=>e.id===je.current))o=o.map(n=>{var r;if(n.id!==je.current)return n;const a="".concat(n.content||"").concat(e);return console.log("[BIDI] appendAssistantContent: updating existing message",{messageId:n.id,oldContentLength:(null===(r=n.content)||void 0===r?void 0:r.length)||0,newContentLength:a.length,textLength:e.length}),h(h({},n),{},{content:a,isProcessing:!t},Array.isArray(Xe.current)&&Xe.current.length>0?{sources:Xe.current}:{})}),Array.isArray(Xe.current)&&Xe.current.length>0&&(Xe.current=null);else{console.error("[BIDI] appendAssistantContent: ERROR - assistant message not found!",{expectedId:je.current,existingIds:o.map(e=>e.id)});const n="bidi-assistant-".concat(Date.now());je.current=n;const r=te({id:n,role:"assistant",content:e,isProcessing:!t,metadata:{source:"bidi"}});Array.isArray(Xe.current)&&Xe.current.length>0&&(r.sources=Xe.current,Xe.current=null),o=[...o,r],console.log("[BIDI] appendAssistantContent: recreated lost assistant message",{messageId:n})}}else{const n="bidi-assistant-".concat(Date.now()),a=Date.now(),i=r?new Date(a):new Date(a+1e3),s=te({id:n,role:"assistant",content:e,isProcessing:!t,timestamp:i,metadata:{source:"bidi"}});Array.isArray(Xe.current)&&Xe.current.length>0&&(s.sources=Xe.current,Xe.current=null);o.some(e=>e.id===n)?(console.error("[BIDI] appendAssistantContent: ERROR - message ID collision!",{messageId:n,existingIds:o.map(e=>e.id)}),o=o.map(r=>r.id===n?h(h({},r),{},{content:"".concat(r.content||"").concat(e),isProcessing:!t},Array.isArray(Xe.current)&&Xe.current.length>0?{sources:Xe.current}:{}):r),Array.isArray(Xe.current)&&Xe.current.length>0&&(Xe.current=null),je.current=n):(o=[...o,s],je.current=n)}return console.log("[BIDI] appendAssistantContent: atomic state update complete",{prevLength:a,newLength:o.length,finished:t,messageIds:o.map(e=>e.id),messageRoles:o.map(e=>e.role)}),o.length<a?(console.error("[BIDI] appendAssistantContent: CRITICAL ERROR - losing messages!",{prevLength:a,resultLength:o.length,prevIds:n.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}}),resultIds:o.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}})}),n):o}),r&&(Ge.current=null),t)console.log("[BIDI] appendAssistantContent: finalizing message",{messageId:je.current}),je.current=null,$e.current=null;else{const e=updateKey;Promise.resolve().then(()=>{$e.current===e&&($e.current=null)})}},[]),ft=o(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(console.log("[BIDI] handleContentParts called",{partsCount:null==e?void 0:e.length,finished:t,audioOnly:n}),!e||!Array.isArray(e))return void console.warn("[BIDI] handleContentParts: invalid parts",e);let r="";e.forEach((e,t)=>{var a,o;null!==(a=e.inlineData)&&void 0!==a&&a.data&&null!==(o=e.inlineData.mimeType)&&void 0!==o&&o.startsWith("audio/pcm")&&(console.log("[BIDI] handleContentParts: sending audio data to player"),Pe.current?Pe.current.port.postMessage((e=>{if("undefined"==typeof window)return new ArrayBuffer(0);let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";const n=window.atob(t),r=n.length,a=new Uint8Array(r);for(let e=0;e<r;e+=1)a[e]=n.charCodeAt(e);return a.buffer})(e.inlineData.data)):console.warn("[BIDI] handleContentParts: audioPlayerNodeRef is null")),!n&&e.text&&(r+=e.text,console.log("[BIDI] handleContentParts: accumulated text part",{text:e.text.substring(0,50),index:t,totalAccumulated:r.length}))}),r&&(console.log("[BIDI] handleContentParts: calling appendAssistantContent once",{textLength:r.length,finished:t}),mt(r,t))},[mt]),ht=o(()=>{z(!1),console.log("[BIDI] handleTurnComplete called",{currentAssistantId:je.current,currentInputId:Ge.current}),Ae(e=>{const t=e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing?h(h({},e),{},{isProcessing:!1}):e});return console.log("[BIDI] handleTurnComplete: state update",{prevLength:e.length,newLength:t.length,finalizedCount:e.filter(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing}).length}),t}),je.current=null,Ge.current=null,Ke.current=!1,Xe.current=null},[]),bt=o(()=>{z(!1),Pe.current&&Pe.current.port.postMessage({command:"endOfAudio"}),je.current=null,Ge.current=null,Xe.current=null,Ae(e=>e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)?h(h({},e),{},{isProcessing:!1,metadata:h(h({},e.metadata),{},{interrupted:!0})}):e}))},[]),yt=o(()=>{var e,t,n,r,a;ke(!1),z(!1),He.current=!1,Ie("idle"),Re(null),Ye.current=!1,Xe.current=null,De.current&&De.current.readyState===WebSocket.OPEN&&De.current.close(),De.current=null,null===(e=Pe.current)||void 0===e||e.disconnect(),null===(t=Me.current)||void 0===t||t.close(),Pe.current=null,Me.current=null,null===(n=Fe.current)||void 0===n||n.disconnect(),null===(r=Be.current)||void 0===r||r.close(),Fe.current=null,Be.current=null,O(Ue.current),Ue.current=null,null===(a=ze.current)||void 0===a||a.reset(),ze.current=null,qe.current=!1},[]),wt=o(e=>{var t,n,r,a,o;if(console.log("[BIDI] handleBidiEvent called",{event:e,isVoiceSessionActive:He.current,hasTurnComplete:!(null==e||!e.turnComplete),hasInterrupted:!(null==e||!e.interrupted),hasInputTranscription:!(null==e||!e.inputTranscription),hasOutputTranscription:!(null==e||!e.outputTranscription),hasContentParts:!(null==e||null===(t=e.content)||void 0===t||!t.parts)}),!e)return void console.warn("[BIDI] handleBidiEvent: received null/undefined event");const i=null!==(n=e.conclusion_detected)&&void 0!==n?n:e.conclusionDetected;var s;"boolean"==typeof i&&i&&(null===(s=Ze.current)||void 0===s||s.call(Ze),_e(!0));if("boolean"==typeof i&&i)return yt(),void Ae(e=>{const t=[...e];for(let e=t.length-1;e>=0;e--)if("assistant"===t[e].role){t[e]=h(h({},t[e]),{},{conclusionDetected:!0});break}return t});if(e.interrupted)return console.log("[BIDI] handleBidiEvent: processing interrupted"),void bt();if(e.inputTranscription){const t=e.inputTranscription.text||"",n=Boolean(e.inputTranscription.finished);console.log("[BIDI] handleBidiEvent: processing inputTranscription",{text:t.substring(0,50),textLength:t.length,finished:n,hasText:!!t}),t||n?(J(u),gt(t,n)):console.warn("[BIDI] handleBidiEvent: inputTranscription event has no text and not finished",e.inputTranscription)}const l=null!==(r=e.sources)&&void 0!==r?r:e.Sources;if(Array.isArray(l)&&l.length>0){const e=l.map(e=>{var t,n,r,a,o,i;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"file",source_id:null!==(r=null!==(a=e.source_id)&&void 0!==a?a:e.sourceid)&&void 0!==r?r:e.sourceId,source_name:null!==(o=null!==(i=e.source_name)&&void 0!==i?i:e.sourceName)&&void 0!==o?o:"",url:e.url}}).filter(e=>e.source_id||e.url);if(0===e.length)return;Ae(t=>{const n=[...t];let r=!1;for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=h(h({},n[t]),{},{sources:e}),r=!0;break}return r||(Xe.current=e),n})}var c,d;if(!Ye.current&&(null!==(c=e.outputTranscription)&&void 0!==c&&c.text||null!==(d=e.content)&&void 0!==d&&d.parts))return void(e.turnComplete&&ht());if(null!==(a=e.outputTranscription)&&void 0!==a&&a.text&&(Ke.current=!0,mt(e.outputTranscription.text,Boolean(e.outputTranscription.finished))),null!==(o=e.content)&&void 0!==o&&o.parts){var p;const t=(null===(p=e.content)||void 0===p?void 0:p.finished)||e.finished||!1;ft(e.content.parts,t,Ke.current)}if(e.prompts&&Array.isArray(e.prompts)&&e.prompts.length>0){console.log("[BIDI] handleBidiEvent: attaching prompts to last assistant message",{count:e.prompts.length}),Ae(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=h(h({},n[t]),{},{prompts:e.prompts});break}return n});try{ee(u,e.prompts)}catch(e){}}e.turnComplete?ht():e.interrupted||e.inputTranscription||e.outputTranscription||e.content||e.prompts||console.warn("[BIDI] handleBidiEvent: event had no recognized fields",e)},[mt,gt,ft,bt,ht,yt]),vt=o(e=>{if(!He.current)return;const t=ze.current;if(t)return void t.process(e);const n=De.current;n&&n.readyState===WebSocket.OPEN&&n.send(e)},[]),Et=o(async()=>{if(!qe.current&&"undefined"!=typeof window)try{const[e,t]=await async function(){if("undefined"==typeof window)throw new Error("Audio player can only be initialized in the browser");const e=new AudioContext({sampleRate:24e3}),t=new Blob(["\n class PCMPlayerProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.bufferSize = 24000 * 180;\n this.buffer = new Float32Array(this.bufferSize);\n this.writeIndex = 0;\n this.readIndex = 0;\n this.port.onmessage = (event) => {\n if (event.data?.command === 'endOfAudio') {\n this.readIndex = this.writeIndex;\n return;\n }\n const int16Samples = new Int16Array(event.data);\n this.enqueue(int16Samples);\n };\n }\n\n enqueue(samples) {\n for (let i = 0; i < samples.length; i += 1) {\n const floatVal = samples[i] / 32768;\n this.buffer[this.writeIndex] = floatVal;\n this.writeIndex = (this.writeIndex + 1) % this.bufferSize;\n if (this.writeIndex === this.readIndex) {\n this.readIndex = (this.readIndex + 1) % this.bufferSize;\n }\n }\n }\n\n process(inputs, outputs) {\n const output = outputs[0];\n const framesPerBlock = output[0].length;\n for (let frame = 0; frame < framesPerBlock; frame += 1) {\n output[0][frame] = this.buffer[this.readIndex];\n if (output.length > 1) {\n output[1][frame] = this.buffer[this.readIndex];\n }\n if (this.readIndex !== this.writeIndex) {\n this.readIndex = (this.readIndex + 1) % this.bufferSize;\n }\n }\n return true;\n }\n }\n\n registerProcessor('pcm-player-processor', PCMPlayerProcessor);\n "],{type:"application/javascript"}),n=URL.createObjectURL(t);await e.audioWorklet.addModule(n);const r=new AudioWorkletNode(e,"pcm-player-processor");return r.connect(e.destination),URL.revokeObjectURL(n),[r,e]}();Pe.current=e,Me.current=t,await t.resume();const n=e=>{const t=De.current;t&&t.readyState===WebSocket.OPEN&&t.send(e)};ze.current=B({sampleRate:16e3},{onVoiceFrame:n,onSpeechEnd:()=>{const e=De.current;e&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"audio_end"}))}});const[r,a,o]=await _(vt);Fe.current=r,Be.current=a,Ue.current=o,await a.resume(),qe.current=!0}catch(e){throw console.error("Failed to initialize audio pipeline",e),e}},[vt]),St=o(()=>{if("undefined"!=typeof window&&et&&(!De.current||De.current.readyState!==WebSocket.OPEN)){Ie("connecting"),Re(null);try{const e=new WebSocket(et);De.current=e,e.onopen=()=>{Ie("connected")},e.onmessage=e=>{try{var t,n;const r="string"==typeof e.data?e.data.substring(0,200):"binary";console.log("[BIDI] WebSocket message received",{dataLength:null===(t=e.data)||void 0===t?void 0:t.length,dataPreview:r});const a=JSON.parse(e.data);console.log("[BIDI] WebSocket message parsed",{hasTurnComplete:!!a.turnComplete,hasInterrupted:!!a.interrupted,hasInputTranscription:!!a.inputTranscription,hasOutputTranscription:!!a.outputTranscription,hasContentParts:!(null===(n=a.content)||void 0===n||!n.parts),payload:a}),wt(a)}catch(t){console.error("[BIDI] Failed to parse WebSocket event",{error:t,data:e.data})}},e.onerror=()=>{Ie("error"),Re("Voice session connection error"),z(!1)},e.onclose=()=>{De.current=null,Ie("idle"),z(!1),He.current&&setTimeout(()=>{St()},5e3)}}catch(e){console.error("Failed to open voice websocket",e),Ie("error"),Re(e instanceof Error?e.message:"Unable to start voice session")}}},[wt,et]),kt=o(async()=>{if(m&&u){Re(null),Ie(e=>"connected"===e?e:"connecting"),ke(!0),He.current=!0,_e(!1),Ye.current=!1,Ae(e=>{if(e.length>0||L.length>0)return e;if(!i||""===i.trim())return[];return[te({id:"bidi-welcome-".concat(Date.now()),role:"assistant",content:i,metadata:{source:"bidi"}})]}),St();try{await Et()}catch(e){console.error("Failed to start audio pipeline",e),Re(e instanceof Error?e.message:"Unable to access microphone"),Ie("error")}}},[m,u,i,St,Et,L]),Tt=o(()=>{Se?yt():"connecting"!==xe&&kt()},[Se,kt,yt,xe]),At=o(e=>{const t=e.trim();if(!t)return;Ye.current=!0;const n=De.current;if(!n||n.readyState!==WebSocket.OPEN)return void Re("Voice session is not connected yet");n.send(JSON.stringify({type:"text",text:t})),J(u),z(!0);const r=te({id:"bidi-user-".concat(Date.now()),role:"user",content:t,metadata:{source:"bidi"}});Ae(e=>[...e,r]),M("")},[]);a(()=>{He.current=Se},[Se]),a(()=>()=>{var e,t,n,r;De.current&&De.current.readyState===WebSocket.OPEN&&De.current.close(),null===(e=Pe.current)||void 0===e||e.disconnect(),null===(t=Me.current)||void 0===t||t.close(),null===(n=Fe.current)||void 0===n||n.disconnect(),null===(r=Be.current)||void 0===r||r.close(),O(Ue.current),Ue.current=null,qe.current=!1},[]);const xt=o(()=>{(e=>{try{const t=Z(e);localStorage.removeItem("".concat(H,"_").concat(e)),null!=t&&t.conversationId&&Y(e,t.conversationId)}catch(e){}})(u),ee(u,[]),ae(null),ie(null),ce(null),se.current=null,ue.current=null,D([]),Ae([]),Y(u,Oe),pe(!1),me(!1),ye({}),he(null),we.current=!1,Ye.current=!1,nt.current=!1,rt.current=!1;const e="widget-session-".concat(Math.random().toString(36).slice(2,9));if(Q(u,e,{settingsSnapshot:JSON.stringify({value:v,unit:null==E?void 0:E.toUpperCase()})}),Le(e),i&&""!==i.trim()&&D([h(h({},te({id:Date.now().toString(),role:"assistant",content:i})),{},{isWelcome:!0})]),y){ne(b).length>0&&pe(!0)}},[u,Oe,i,y,b,v,E]),It=r(xt);a(()=>{It.current=xt},[xt]),a(()=>{at.current=!1,ot.current={value:null,unit:null}},[u]),a(()=>{if(!u||!v)return;const e=K(v,E);if(!e)return;const t=ot.current,n=at.current&&(t.value!==v||t.unit!==E);if(at.current=!0,ot.current={value:v,unit:E},n)return console.warn("[Session] Inactivity timeout config changed — resetting conversation."),void It.current();let r=null;const a=()=>{const t=Z(u);if(!t)return;if(!t.firstInteractionAt)return void(r=setTimeout(a,e));const n=new Date(t.lastActivity).getTime(),o=Date.now()-n,i=e-o;if(i<=0)return console.warn("[Session] Inactivity timeout reached! Resetting conversation immediately."),void It.current();r=setTimeout(a,i)};return a(),()=>{r&&clearTimeout(r)}},[u,v,E,Oe]);const Ct=t(()=>s,[s]),Rt=t(()=>{const e=[...L.map(e=>h(h({},e),{},{metadata:e.metadata||{source:"sse"}})),...Te];return Array.from(new Map(e.map(e=>[e.id,e])).values()).sort((e,t)=>(e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime())-(t.timestamp instanceof Date?t.timestamp.getTime():new Date(t.timestamp).getTime()))},[Te,L]);return a(()=>{Se&&console.log("[BIDI] bidiMessages state changed",{count:Te.length,messages:Te.map(e=>{var t,n;return{id:e.id,role:e.role,contentLength:(null===(t=e.content)||void 0===t?void 0:t.length)||0,isProcessing:e.isProcessing,hasContent:!!e.content,contentPreview:null===(n=e.content)||void 0===n?void 0:n.substring(0,50)}})})},[Te,Se]),{conversationId:Oe,isOpen:T,isMinimized:x,isDark:C,messages:Rt,inputValue:P,isLoading:F,isConversationLoading:ve,widgetRef:G,quickQuestions:Ct,isVoiceSessionActive:Se,voiceStatus:xe,voiceError:Ce,voiceConclusionForCsat:Ne,onboardingQuestions:b,onboardingActive:de,onboardingCompleted:ge,handleOnboardingFormSubmit:lt,widgetFilter:re,setWidgetFilter:ae,addAssistantMessage:it,setInputValue:M,handleSend:ut,handleQuickQuestion:dt,sendMessage:st,toggleChat:()=>{A(e=>!e),I(!1)},toggleTheme:()=>{R(e=>!e)},toggleMinimize:()=>{I(e=>!e)},closeChat:()=>{A(!1)},handleDecision:pt,handleVoiceToggle:Tt,sendBidiTextMessage:At,resetConversation:xt}},ae=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim(),oe=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ie=e=>{const t=(e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()))(e);return t.charAt(0).toUpperCase()+t.slice(1)};
1
+ import e,{useMemo as t,useState as n,useRef as r,useEffect as a,useCallback as o,forwardRef as i,createElement as s}from"react";import{createRoot as l}from"react-dom/client";import{Fragment as c,jsx as u,jsxs as d}from"react/jsx-runtime";import{createPortal as p}from"react-dom";function g(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}function m(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?f(Object(n),!0).forEach(function(t){m(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function b(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}const y="processing_start",w="text_chunk",v="processing_end",E="complete",S="error",k="human_decision_required",T=e=>{if(!e||"string"!=typeof e)return null;if("[DONE]"===e||"[PROCESSING]"===e)return null;try{const n=JSON.parse(e);if(!n||"object"!=typeof n)return null;const r=n.type||n.event_type;if(r===w||n.content){var t;const e=n.content||(null===(t=n.choices)||void 0===t||null===(t=t[0])||void 0===t||null===(t=t.delta)||void 0===t?void 0:t.content)||"";return h({type:w,content:e},n)}return r===y||"processing_start"===n.type?h({type:y},n):r===v||"processing_end"===n.type?h({type:v},n):r===E||"complete"===n.type?h({type:E,finalContent:n.finalContent||n.content||""},n):r===S||"error"===n.type?h({type:S,error:n.error||n.message||"Unknown error"},n):r===k||"human_decision_required"===n.type?h({type:k,decisionId:n.decisionId||n.decision_id,question:n.question||"",options:n.options||[],context:n.context||{}},n):r?h({type:r},n):n}catch(e){return null}},A=["prompts"],x=()=>({id:"skeleton-".concat(Date.now()),role:"assistant",content:"",timestamp:new Date,isProcessing:!0}),I=e=>{if(!Array.isArray(e)||0===e.length)return;const t=e.map(e=>({type:e.type||"prompt",text:"string"==typeof e.text?e.text:"",confidence:"number"==typeof e.confidence?e.confidence:void 0})).filter(e=>e.text);return t.length?t:void 0},C=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e(e=>{const r=[...e||[]],a=r[r.length-1];if("assistant"===(null==a?void 0:a.role)){const e=n||{},{prompts:o}=e,i=b(e,A);r[r.length-1]=h(h(h({},a),i),{},{content:t,isProcessing:!1},null!=o&&{prompts:I(o)})}return r})},R=(e,t,n,r,a)=>{var o;if(e&&e.type)switch(e.type){case y:break;case w:a.current||(a.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],x()]}return e}));const i=e.content||(null===(o=e.choices)||void 0===o||null===(o=o[0])||void 0===o||null===(o=o.delta)||void 0===o?void 0:o.content)||"";i&&(n.current+=i,r(n.current));break;case v:(e=>{e(e=>{const t=[...e||[]],n=t[t.length-1];return null!=n&&n.isProcessing&&(t[t.length-1]=h(h({},n),{},{isProcessing:!1})),t})})(t);break;case E:{const r=e.finalContent||n.current,a={};"boolean"==typeof e.conclusionDetected?a.conclusionDetected=e.conclusionDetected:"boolean"==typeof e.conclusion_detected&&(a.conclusionDetected=e.conclusion_detected);const o=h(h({},a),{},{prompts:e.prompts});C(t,r,o);break}case S:((e,t)=>{e(e=>{const n=[...e||[]],r=n[n.length-1];return"assistant"===(null==r?void 0:r.role)&&(n[n.length-1]=h(h({},r),{},{content:(r.content||"")+"\n\nError: ".concat(t),isProcessing:!1})),n})})(t,e.error||"Unknown error occurred");break;case k:{const n={id:"decision-".concat(Date.now()),role:"assistant",content:e.question||"",timestamp:new Date,isProcessing:!1,requiresDecision:!0,decisionData:{decisionId:e.decisionId,question:e.question,options:e.options||[],context:e.context||{}}};t(e=>[...(e||[]).filter(e=>!e.isProcessing||e.content),n]);break}default:console.warn("Unknown stream event type:",e.type)}},N=async(e,t)=>{const n=(e=>{let t=null,n=null,r=0;const a=o=>{if(o-r<16)n=requestAnimationFrame(a);else{if(null!==t){const n=t;t=null,r=o,e(e=>{const t=[...e||[]],r=t[t.length-1];return"assistant"===(null==r?void 0:r.role)&&(t[t.length-1]=h(h({},r),{},{content:n})),t})}n=null}};return e=>{t=e,null===n&&(n=requestAnimationFrame(a))}})(t),r=e.getReader(),a=new TextDecoder;let o="";const i={current:""},s={current:!1};try{for(;;){const{value:e,done:m}=await r.read();if(m)break;o+=a.decode(e,{stream:!0});const f=o.split(/\r?\n\r?\n/);o=f.pop()||"";for(const e of f){var l,c;const r=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);if(0===r.length)continue;const a=r.filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim());if(0===a.length)continue;const o=a.join("\n");if("[DONE]"===o)continue;let m;try{m=JSON.parse(o)}catch(e){continue}if(m){if(m.type){if("processing_start"===m.type||"processing_end"===m.type)continue;if("text_chunk"===m.type){var u;const e=(null===(u=m.choices)||void 0===u||null===(u=u[0])||void 0===u||null===(u=u.delta)||void 0===u?void 0:u.content)||m.content;e&&(s.current||(s.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],x()]}return e})),i.current+=e,n(i.current));continue}if("complete"===m.type){var d,p,g;const e=null!==(d=null!==(p=m.Sources)&&void 0!==p?p:m.sources)&&void 0!==d?d:[],n=Array.isArray(e)?e.map(e=>{var t,n,r,a,o;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"website",source_id:null!==(r=e.sourceid)&&void 0!==r?r:e.source_id,source_name:null!==(a=null!==(o=e.source_name)&&void 0!==o?o:e.sourceName)&&void 0!==a?a:"",url:e.url}}).filter(e=>e.source_id||e.url):[],r=(null===(g=m.choices)||void 0===g||null===(g=g[0])||void 0===g||null===(g=g.delta)||void 0===g?void 0:g.content)||m.finalContent||i.current,a={};"boolean"==typeof m.conclusionDetected?a.conclusionDetected=m.conclusionDetected:"boolean"==typeof m.conclusion_detected&&(a.conclusionDetected=m.conclusion_detected);const o=h(h({},a),{},{prompts:m.prompts});C(t,r,o),n.length>0&&t(e=>{const t=[...e||[]],a=t[t.length-1];return"assistant"===(null==a?void 0:a.role)&&(t[t.length-1]=h(h({},a),{},{sources:n,content:r,isProcessing:!1})),t});continue}if("error"===m.type){t(e=>{const t=[...e||[]],n=t[t.length-1];return"assistant"===(null==n?void 0:n.role)&&(t[t.length-1]=h(h({},n),{},{content:(n.content||"")+"\n\nError: ".concat(m.error||"Unknown error occurred"),isProcessing:!1})),t});continue}const e=T(o);if(e&&e.type){console.log("🔍 Parsed stream event:",e.type,e),R(e,t,i,n,s);continue}}if("chat.completion.chunk"===m.object&&null!==(l=m.choices)&&void 0!==l&&null!==(l=l[0])&&void 0!==l&&null!==(l=l.delta)&&void 0!==l&&l.content)s.current||(s.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],x()]}return e})),i.current+=m.choices[0].delta.content,n(i.current);else if(null!==(c=m.choices)&&void 0!==c&&null!==(c=c[0])&&void 0!==c&&c.finish_reason&&null!==m.choices[0].finish_reason){const e={prompts:m.prompts};C(t,i.current,e)}}}}}finally{r.releaseLock()}};async function _(e){if("undefined"==typeof window)throw new Error("Audio recorder can only run in the browser");const t=new AudioContext({sampleRate:16e3}),n=new Blob(["\n class PCMRecorderProcessor extends AudioWorkletProcessor {\n process(inputs) {\n if (!inputs.length || !inputs[0].length) {\n return true;\n }\n const inputChannel = inputs[0][0];\n this.port.postMessage(new Float32Array(inputChannel));\n return true;\n }\n }\n registerProcessor('pcm-recorder-processor', PCMRecorderProcessor);\n "],{type:"application/javascript"}),r=URL.createObjectURL(n);await t.audioWorklet.addModule(r),URL.revokeObjectURL(r);const a=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1}}),o=t.createMediaStreamSource(a),i=new AudioWorkletNode(t,"pcm-recorder-processor");return i.port.onmessage=t=>{const n=function(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=Math.max(-1,Math.min(1,e[n]))*L;return t.buffer}(t.data);e(n)},o.connect(i),[i,t,a]}function O(e){e&&e.getTracks().forEach(e=>e.stop())}const L=32767;const D=.025,P=200,M=1e3,F=300;function B(e,t){var n,r,a,o;const i=e.sampleRate,s=null!==(n=e.energyThreshold)&&void 0!==n?n:D,l=null!==(r=e.speechStartMs)&&void 0!==r?r:P,c=null!==(a=e.hangoverMs)&&void 0!==a?a:M,u=null!==(o=e.preRollMs)&&void 0!==o?o:F;let d=!1,p=0,g=0,m=[],f=0;return{process:e=>{const n=(e=>e.byteLength/2/i*1e3)(e),r=function(e){const t=new Int16Array(e);if(0===t.length)return 0;let n=0;for(let e=0;e<t.length;e+=1){const r=t[e]/32768;n+=r*r}return Math.sqrt(n/t.length)}(e)>=s;if(d)t.onVoiceFrame(e),r?g=0:(g+=n,g>=c&&(d=!1,p=0,g=0,t.onSpeechEnd()));else{for(m.push({pcm:e,durationMs:n}),f+=n;f>u&&m.length>1;){var a;const e=m.shift();f-=null!==(a=null==e?void 0:e.durationMs)&&void 0!==a?a:0}if(r){if(p+=n,p>=l){var o;d=!0,g=0,null===(o=t.onSpeechStart)||void 0===o||o.call(t);for(const e of m)t.onVoiceFrame(e.pcm);m=[],f=0}}else p=0}},reset:()=>{d=!1,p=0,g=0,m=[],f=0},isSpeaking:()=>d}}const U=e=>e.replace(/([\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uff00-\uffef])\s+([\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uff00-\uffef])/g,"$1$2"),z=e=>{const t=(e||"").trim();return t?/^https?:\/\//i.test(t)||/^[a-z][a-z0-9+.-]*:/i.test(t)?t:"https://".concat(t.replace(/^\/+/,"")):""},G=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.filter(Boolean).join(" ")},j={fullname:0,name:0,username:0,email:1,phone:2,mobileno:2},q=e=>{var t;if(!e)return 99;const n=String(e).toLowerCase();return null!==(t=j[n])&&void 0!==t?t:99},H="eshal_chat_session",$="eshal_chat_session_messages";function V(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:50;if(!Array.isArray(e))return[];("number"!=typeof t||t<=0)&&(t=200),("number"!=typeof n||n<=0||n>=t)&&(n=Math.min(50,t-1));let r=e;for(;r.length>t;)r=r.slice(n);return r}const W=(e,t,n,r)=>{if(e&&t)try{const a=null==r?void 0:r.cap,o=null==r?void 0:r.trimBatch,i=function(e){return Array.isArray(e)?e.filter(e=>e&&!e.isWelcome&&(e.content||Array.isArray(e.sources)&&e.sources.length>0)).map(e=>{var t;return h(h(h({id:e.id,role:e.role,content:e.content,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():"string"==typeof e.timestamp?e.timestamp:(new Date).toISOString(),type:null!==(t=e.type)&&void 0!==t?t:null},Array.isArray(e.sources)&&e.sources.length>0?{sources:e.sources}:{}),void 0!==e.feedback?{feedback:e.feedback}:{}),Array.isArray(e.prompts)&&e.prompts.length>0?{prompts:e.prompts}:{})}):[]}(V(n,a,o));localStorage.setItem("".concat($,"_").concat(e,"_").concat(t),JSON.stringify(i))}catch(e){}},Y=(e,t)=>{if(e&&t)try{localStorage.removeItem("".concat($,"_").concat(e,"_").concat(t))}catch(e){}},K=(e,t)=>{if(null==e||!t)return null;const n={MINUTES:6e4,HOURS:36e5,DAYS:864e5}[t.toUpperCase()];return void 0===n?(console.warn("[Session] Unknown timeout unit: ".concat(t)),null):Number(e)*n},Z=e=>{try{const t=localStorage.getItem("".concat(H,"_").concat(e));return t?JSON.parse(t):null}catch(e){return null}},X=(e,t,n)=>{if(!e||!e.lastActivity)return!1;if(null==t||0===t)return!0;if(null!==t&&null!==n){const r=JSON.stringify({value:t,unit:null==n?void 0:n.toUpperCase()});if(e.settingsSnapshot&&e.settingsSnapshot!==r)return console.log("[Session] Timeout settings changed — treating session as invalid."),!1}if(null===e.firstInteractionAt)return!0;const r=K(t,n);if(!r)return!0;const a=new Date(e.lastActivity).getTime(),o=Date.now()-a,i=o<r;return i||console.log("[Session] Session expired. Elapsed: ".concat(Math.floor(o/1e3),"s, Timeout: ").concat(Math.floor(r/1e3),"s")),i},Q=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{const r=(new Date).toISOString();console.log("[Session] Saving new session: ".concat(t," for org: ").concat(e)),localStorage.setItem("".concat(H,"_").concat(e),JSON.stringify(h({conversationId:t,lastActivity:r,createdAt:r,firstInteractionAt:null},n)))}catch(e){}},J=e=>{try{const t=Z(e);if(!t)return;const n=(new Date).toISOString();t.lastActivity=n,t.firstInteractionAt||(t.firstInteractionAt=n),localStorage.setItem("".concat(H,"_").concat(e),JSON.stringify(t))}catch(e){}},ee=(e,t)=>{try{if(!e)return;if(!Array.isArray(t)||0===t.length)return void localStorage.removeItem("".concat(H,"_prompts_").concat(e));localStorage.setItem("".concat(H,"_prompts_").concat(e),JSON.stringify(t))}catch(e){}},te=e=>{let{id:t,role:n,content:r,isProcessing:a=!1,metadata:o}=e;return{id:t,role:n,content:r,timestamp:new Date,isProcessing:a,metadata:o}},ne=e=>e&&e.length>0?e:[],re=e=>{let{welcomeMessage:i,quickQuestions:s=[],apiBaseUrl:l,apiKey:c,organizationId:u,autoOpen:d,openDelay:p,darkMode:g,enableVoiceInteraction:m=!1,provideCitations:f=!0,onboardingQuestions:b=[],onboardingEnabled:y=!1,collectionPrompt:w,inactivityTimeoutValue:v,inactivityTimeoutUnit:E,messageLimits:S}=e;const k=t(()=>({cap:"number"==typeof(null==S?void 0:S.cap)&&S.cap>0?S.cap:200,trimBatch:"number"==typeof(null==S?void 0:S.trimBatch)&&S.trimBatch>0?S.trimBatch:50}),[null==S?void 0:S.cap,null==S?void 0:S.trimBatch]),[T,A]=n(d),[x,I]=n(!1),[C,R]=n(g),[L,D]=n(()=>{try{const e=Z(u);if(void 0!==v&&e&&X(e,v,E))return[]}catch(e){}return i?[h(h({},te({id:Date.now().toString(),role:"assistant",content:i})),{},{isWelcome:!0})]:[]}),[P,M]=n(""),[F,z]=n(!1),G=r(null),j=r(1),[re,ae]=n(null),[oe,ie]=n(null),se=r(null);a(()=>{se.current=oe},[oe]);const[le,ce]=n(null),ue=r(null);a(()=>{ue.current=le},[le]);const[de,pe]=n(!1),[ge,me]=n(()=>{try{const e=Z(u);if(e&&e.onboardingCompleted)return!0}catch(e){}return!1}),[fe,he]=n(null),[be,ye]=n({}),we=r(!1),[ve,Ee]=n(!1),[Se,ke]=n(!1),[Te,Ae]=n([]),[xe,Ie]=n("idle"),[Ce,Re]=n(null),[Ne,_e]=n(!1),[Oe,Le]=n(()=>{try{const e=Z(u);if(void 0!==v&&e&&X(e,v,E))return e.conversationId}catch(e){}return"widget-session-".concat(Math.random().toString(36).slice(2,9))}),De=r(null),Pe=r(null),Me=r(null),Fe=r(null),Be=r(null),Ue=r(null),ze=r(null),Ge=r(null),je=r(null),qe=r(!1),He=r(!1);r(null);const $e=r(null);r(null);const Ve=r(!1),We=r(null),Ye=r(!1),Ke=r(!1),Ze=r(null),Xe=r(null),Qe=r(null),Je=r(null),et=t(()=>{if(!u)return null;const e=(e=>{if(!e)return"wss://dev.eshal.ai/voice/ws";try{const t=new URL(e);return t.protocol=t.protocol.replace(/^http/,"ws"),t.pathname="/voice/ws",t.toString().replace(/\/$/,"")}catch(e){return console.error("Invalid API base URL provided for WebSocket:",e),"wss://dev.eshal.ai/voice/ws"}})(l);return"".concat(e,"/").concat(u,"/").concat(Oe)},[l,u,Oe]),tt=o(()=>{const e="msg-".concat(j.current);return j.current+=1,e},[]);a(()=>{if(d&&p>0){const e=setTimeout(()=>A(!0),p);return()=>clearTimeout(e)}},[d,p]),a(()=>{let e=!1;return(async()=>{try{const{default:t}=await Promise.resolve().then(function(){return LE}),n=new t({cache:!0,onError:()=>{}}),r=await n.init();if(e)return;if(null!=r&&r.fingerprintId&&(Qe.current=r.fingerprintId),null!=r&&r.geo||null!=r&&r.ip){const e=r.geo||{};Je.current={ip:r.ip||e.ip||null,country:e.country||null,countryCode:e.countryCode||null,region:e.region||null,city:e.city||null,timezone:e.timezone||null}}}catch(e){}})(),()=>{e=!0}},[]),a(()=>{R(g)},[g]);const nt=r(!1),rt=r(!1),at=r(!1),ot=r({value:null,unit:null});a(()=>{if(!u||!Oe||void 0===v)return;const e=Z(u);if(e&&X(e,v,E)){if(Oe!==e.conversationId)return void Le(e.conversationId);if(!nt.current){nt.current=!0;const e=((e,t)=>{if(!e||!t)return[];try{const n=localStorage.getItem("".concat($,"_").concat(e,"_").concat(t));if(!n)return[];const r=JSON.parse(n);return Array.isArray(r)?r.map(e=>h(h({},e),{},{timestamp:e.timestamp?new Date(e.timestamp):new Date})):[]}catch(e){return[]}})(u,Oe);if(e.length>0){if(rt.current=!0,i){var t;const n=null===(t=e[0])||void 0===t?void 0:t.timestamp,r=n instanceof Date?n.getTime():n?new Date(n).getTime():Date.now(),a=h(h({},te({id:"welcome-restored",role:"assistant",content:i})),{},{isWelcome:!0,timestamp:new Date(r-1)});D([a,...e])}else D(e);if(!e.some(e=>"assistant"===e.role&&Array.isArray(e.prompts)&&e.prompts.length>0)){const e=(e=>{try{const t=localStorage.getItem("".concat(H,"_prompts_").concat(e));return t&&JSON.parse(t)||[]}catch(e){return[]}})(u);e.length>0&&D(t=>{const n=[...t];for(let t=n.length-1;t>=0;t-=1)if("assistant"===n[t].role){n[t]=h(h({},n[t]),{},{prompts:e});break}return n})}}}}else if(nt.current||(nt.current=!0),e&&Oe===e.conversationId){const e="widget-session-".concat(Math.random().toString(36).slice(2,9));console.warn("[Session] Rotating expired ID ".concat(Oe," -> ").concat(e)),Y(u,Oe),Le(e)}else null!=e&&e.conversationId&&e.conversationId!==Oe&&Y(u,e.conversationId),e&&e.conversationId===Oe||Q(u,Oe,{settingsSnapshot:JSON.stringify({value:v,unit:null==E?void 0:E.toUpperCase()})})},[u,Oe,l,v,E]),a(()=>{if(u&&L&&0!==L.length)for(let e=L.length-1;e>=0;e-=1){const t=L[e];if("assistant"===(null==t?void 0:t.role)&&Array.isArray(t.prompts)&&t.prompts.length>0)return void ee(u,t.prompts)}},[L,u]),a(()=>{ve||F||L.length<=k.cap||D(e=>V(e,k.cap,k.trimBatch))},[L.length,ve,F,k.cap,k.trimBatch]),a(()=>{u&&Oe&&(ve||F||W(u,Oe,L,k))},[L,u,Oe,ve,F,k]),a(()=>{if(!y||ge)return;ne(b).length>0&&pe(!0)},[y,ge,b]),a(()=>{i&&!rt.current&&D(e=>{if(!e.length)return[h(h({},te({id:Date.now().toString(),role:"assistant",content:i})),{},{isWelcome:!0})];const[t,...n]=e;return t.isWelcome?[h(h({},t),{},{content:i}),...n]:e})},[i]),o(e=>{D(t=>t.map(t=>t.id===e.id?h(h({},t),e.update(t)):t))},[]);const it=o(function(e){if(!e)return;const t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).replaceMarker||null;D(n=>[...t?(n||[]).filter(e=>{var n;return(null==e||null===(n=e.metadata)||void 0===n?void 0:n.synthesizedKind)!==t}):n||[],te({id:tt(),role:"assistant",content:e,metadata:t?{synthesizedKind:t}:void 0})])},[tt]),st=o(async(e,t,n)=>{const r=e.trim();if(!r)return{success:!1,error:"Message cannot be empty"};if(t&&!["inquiry","complaint","technical"].includes((t||"").toLowerCase())||(ue.current=r,ce(r)),!l)return D(e=>[...e||[],te({id:tt(),role:"assistant",content:"Sorry, I'm having trouble connecting right now. Please try again.",isProcessing:!1})]),console.error("Chat widget configuration error: apiBaseUrl is required for streaming."),{success:!1,error:"API base URL is required"};const a=["inquiry","complaint","technical","userName","email","phone","fullname","mobileno"];let o="inquiry";if(t){const e=t.toLowerCase();"fullname"===e||"name"===e?o="userName":"email"===e?o="email":"phone"===e||"mobileno"===e?o="phone":a.includes(e)&&(o=e)}if("inquiry"===o||"complaint"===o||"technical"===o){const e=te({id:tt(),role:"user",content:r});D(t=>{const r=(t||[]).map(e=>{var t;return"assistant"===e.role&&null!==(t=e.prompts)&&void 0!==t&&t.length?h(h({},e),{},{prompts:void 0}):e});return n&&n.skipUserAppend?r:[...r,e]}),M(""),z(!0)}else M("");try{const e=h(h(h(h(h({message:r,type:o,conversationId:Oe,enable_citation:null==f||f,channel:"WIDGET"},Qe.current?{fingerprintId:Qe.current}:{}),Je.current?{visitor:Je.current}:{}),re&&(re.category||re.tags&&re.tags.length)?{filter:re}:{}),se.current?{routing:se.current}:{}),{},{messageHistory:L.filter(e=>!e.isProcessing&&e.content&&e.content.trim()&&!["userName","email","phone"].includes(e.type)).map(e=>{let t;return t=e.timestamp instanceof Date?e.timestamp.toISOString():"string"==typeof e.timestamp?e.timestamp:e.timestamp?new Date(e.timestamp).toISOString():(new Date).toISOString(),{id:e.id,role:e.role,content:e.content,timestamp:t,isProcessing:!1}})}),t=await(async(e,t,n)=>{const r={"Content-Type":"application/json",Accept:"text/event-stream"};n&&(r["x-eshal-org"]=n);const a=await fetch("".concat(t.replace(/\/$/,""),"/api/v1/support"),{method:"POST",headers:r,credentials:"include",body:JSON.stringify(e)});if(!a.ok)throw new Error("HTTP error! status: ".concat(a.status));if(!a.body)throw new Error("Response body is null");return a.body})(e,l,u);if("userName"===o||"email"===o||"phone"===o){const e=t.getReader(),n=new TextDecoder;for(;;){const{done:t,value:r}=await e.read();if(t)break;n.decode(r)}return{success:!0}}return"inquiry"===o||"complaint"===o||"technical"===o?(await N(t,D),J(u),{success:!0}):(J(u),{success:!0})}catch(e){return console.error("Error sending message:",e),"inquiry"!==o&&"complaint"!==o&&"technical"!==o||(z(!1),D(e=>[...(e||[]).filter(e=>!e.isProcessing),te({id:tt(),role:"assistant",content:"Sorry, I'm having trouble connecting right now. Please try again.",isProcessing:!1})])),{success:!1,error:e instanceof Error?e.message:"Failed to send message"}}finally{"inquiry"!==o&&"complaint"!==o&&"technical"!==o||z(!1)}},[l,c,tt,u,L,Oe,oe,re,f]),lt=o(async e=>{const t=ne(b);if(0===t.length)return;const n=[...t].sort((e,t)=>q(e.fieldType)-q(t.fieldType));for(const t of n){var r;const n=t.fieldType||"question",a=(null!==(r=e[n])&&void 0!==r?r:"").trim();if(!a)continue;const o=await st(a,n);if(null==o||!o.success){const e=te({id:tt(),role:"assistant",content:(null==o?void 0:o.error)||"Something went wrong. Please try again.",isProcessing:!1});return void D(t=>[...t,e])}}pe(!1),me(!0),(e=>{try{const t=Z(e);if(!t)return;t.onboardingCompleted=!0,localStorage.setItem("".concat(H,"_").concat(e),JSON.stringify(t))}catch(e){}})(u),ye(t=>h(h({},t),e)),fe&&!we.current&&(we.current=!0,setTimeout(()=>{M(fe),he(null)},500))},[b,st,tt,fe,u]),ct=o(async()=>{const e=P.trim();e&&await st(e)},[P,st]),ut=o(async()=>{await ct()},[ct]),dt=o(async e=>{const t=null==e?void 0:e.trim();t&&await st(t)},[st]),pt=o(async(e,t,n)=>{if(D(t=>t.filter(t=>{var n;return(null===(n=t.decisionData)||void 0===n?void 0:n.decisionId)!==e})),"routing-clarification"===e){const e=String(n||"").toLowerCase(),r="database"===t||"knowledge"===t?t:"database"===e||"knowledge"===e?e:null;if(r){se.current=r,ie(r);const e=ue.current;ue.current=null,ce(null),e&&e.trim()&&setTimeout(()=>{st(e,"inquiry",{skipUserAppend:!0}).catch(e=>console.warn("[routing-clarification] re-send failed:",e))},0)}return}if("connect_agent"===n){const e=te({id:tt(),role:"assistant",content:"Great! I'm setting up a connection with a live customer service agent. Please hold on for a moment while I transfer you."});D(t=>[...t,e])}else if("decline"===n){const e=te({id:tt(),role:"assistant",content:"I understand. I apologize that I don't have specific information about your query in my knowledge base. Is there anything else I can help you with?"});D(t=>[...t,e])}},[tt,st,le]);o(()=>{Ge.current&&(Ae(e=>e.map(e=>e.id===Ge.current?h(h({},e),{},{isProcessing:!1}):e)),Ge.current=null)},[]);const gt=o(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(Ye.current=!0,!e||"string"==typeof e&&!e.trim())return void(t&&Ge.current&&(Ae(e=>e.map(e=>e.id===Ge.current?h(h({},e),{},{isProcessing:!1}):e)),Ge.current=null));const n=U(e);Ae(e=>{const r=e.length;let a=[...e];if(Ge.current){if(a.some(e=>e.id===Ge.current))a=a.map(e=>{if(e.id!==Ge.current)return e;const r=U("".concat(e.content||"").concat(n));return h(h({},e),{},{content:r,isProcessing:!t,metadata:h(h({},e.metadata),{},{transcriptionType:"input"})})});else{console.error("[BIDI] appendUserTranscription: ERROR - user message not found!",{expectedId:Ge.current,existingIds:a.map(e=>e.id)});const e="bidi-input-".concat(Date.now());Ge.current=e;const r=te({id:e,role:"user",content:n,isProcessing:!t,metadata:{source:"bidi",transcriptionType:"input"}});a=[...a,r],console.log("[BIDI] appendUserTranscription: recreated lost user message",{messageId:e})}}else{const r="bidi-input-".concat(Date.now()),o=Date.now(),i=e.filter(e=>{var t;return"assistant"===e.role&&"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)}).sort((e,t)=>{const n=e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime();return(t.timestamp instanceof Date?t.timestamp.getTime():new Date(t.timestamp).getTime())-n})[0];let s;if(i){const e=i.timestamp instanceof Date?i.timestamp.getTime():new Date(i.timestamp).getTime();s=new Date(e-1)}else s=new Date(o);const l=te({id:r,role:"user",content:n,isProcessing:!t,timestamp:s,metadata:{source:"bidi",transcriptionType:"input"}});a.some(e=>e.id===r)?(console.warn("[BIDI] appendUserTranscription: message already exists, updating instead",{messageId:r}),Ge.current=r,a=a.map(e=>e.id===r?h(h({},e),{},{content:"".concat(e.content||"").concat(n),isProcessing:!t}):e)):(a=[...a,l],Ge.current=r)}return a.length<r?(console.error("[BIDI] appendUserTranscription: CRITICAL ERROR - losing messages!",{prevLength:r,resultLength:a.length,prevIds:e.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}}),resultIds:a.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}})}),e):a}),t&&(Ge.current=null,z(!0))},[]),mt=o(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(z(!1),console.log("[BIDI] appendAssistantContent called",{text:null==e?void 0:e.substring(0,50),finished:t,currentAssistantId:je.current,currentInputId:Ge.current}),!e||"string"==typeof e&&!e.trim())return console.log("[BIDI] appendAssistantContent: skipping empty text"),void(t&&je.current&&(Ae(e=>e.map(e=>e.id!==je.current?e:h(h({},e),{},{isProcessing:!1}))),je.current=null,$e.current=null));const n="".concat(je.current||"new","-").concat(e.substring(0,100),"-").concat(t);if(Ve.current&&We.current===n)return;Ve.current=!0,We.current=n;const r=Ge.current;if(Ae(n=>{const a=n.length;let o=[...n];if(console.log("[BIDI] appendAssistantContent: starting update",{prevLength:a,prevMessageIds:n.map(e=>e.id),inputMessageIdToFinalize:r,currentAssistantId:je.current,textLength:e.length}),r){o.some(e=>e.id===r)?o=o.map(e=>e.id===r?h(h({},e),{},{isProcessing:!1}):e):console.warn("[BIDI] appendAssistantContent: input message not found for finalization",{inputMessageId:r,existingIds:o.map(e=>e.id)})}if(je.current){if(o.some(e=>e.id===je.current))o=o.map(n=>{var r;if(n.id!==je.current)return n;const a="".concat(n.content||"").concat(e);return console.log("[BIDI] appendAssistantContent: updating existing message",{messageId:n.id,oldContentLength:(null===(r=n.content)||void 0===r?void 0:r.length)||0,newContentLength:a.length,textLength:e.length}),h(h({},n),{},{content:a,isProcessing:!t},Array.isArray(Xe.current)&&Xe.current.length>0?{sources:Xe.current}:{})}),Array.isArray(Xe.current)&&Xe.current.length>0&&(Xe.current=null);else{console.error("[BIDI] appendAssistantContent: ERROR - assistant message not found!",{expectedId:je.current,existingIds:o.map(e=>e.id)});const n="bidi-assistant-".concat(Date.now());je.current=n;const r=te({id:n,role:"assistant",content:e,isProcessing:!t,metadata:{source:"bidi"}});Array.isArray(Xe.current)&&Xe.current.length>0&&(r.sources=Xe.current,Xe.current=null),o=[...o,r],console.log("[BIDI] appendAssistantContent: recreated lost assistant message",{messageId:n})}}else{const n="bidi-assistant-".concat(Date.now()),a=Date.now(),i=r?new Date(a):new Date(a+1e3),s=te({id:n,role:"assistant",content:e,isProcessing:!t,timestamp:i,metadata:{source:"bidi"}});Array.isArray(Xe.current)&&Xe.current.length>0&&(s.sources=Xe.current,Xe.current=null);o.some(e=>e.id===n)?(console.error("[BIDI] appendAssistantContent: ERROR - message ID collision!",{messageId:n,existingIds:o.map(e=>e.id)}),o=o.map(r=>r.id===n?h(h({},r),{},{content:"".concat(r.content||"").concat(e),isProcessing:!t},Array.isArray(Xe.current)&&Xe.current.length>0?{sources:Xe.current}:{}):r),Array.isArray(Xe.current)&&Xe.current.length>0&&(Xe.current=null),je.current=n):(o=[...o,s],je.current=n)}return console.log("[BIDI] appendAssistantContent: atomic state update complete",{prevLength:a,newLength:o.length,finished:t,messageIds:o.map(e=>e.id),messageRoles:o.map(e=>e.role)}),o.length<a?(console.error("[BIDI] appendAssistantContent: CRITICAL ERROR - losing messages!",{prevLength:a,resultLength:o.length,prevIds:n.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}}),resultIds:o.map(e=>{var t;return{id:e.id,role:e.role,content:null===(t=e.content)||void 0===t?void 0:t.substring(0,30)}})}),n):o}),r&&(Ge.current=null),t)console.log("[BIDI] appendAssistantContent: finalizing message",{messageId:je.current}),je.current=null,$e.current=null;else{const e=updateKey;Promise.resolve().then(()=>{$e.current===e&&($e.current=null)})}},[]),ft=o(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(console.log("[BIDI] handleContentParts called",{partsCount:null==e?void 0:e.length,finished:t,audioOnly:n}),!e||!Array.isArray(e))return void console.warn("[BIDI] handleContentParts: invalid parts",e);let r="";e.forEach((e,t)=>{var a,o;null!==(a=e.inlineData)&&void 0!==a&&a.data&&null!==(o=e.inlineData.mimeType)&&void 0!==o&&o.startsWith("audio/pcm")&&(console.log("[BIDI] handleContentParts: sending audio data to player"),Pe.current?Pe.current.port.postMessage((e=>{if("undefined"==typeof window)return new ArrayBuffer(0);let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";const n=window.atob(t),r=n.length,a=new Uint8Array(r);for(let e=0;e<r;e+=1)a[e]=n.charCodeAt(e);return a.buffer})(e.inlineData.data)):console.warn("[BIDI] handleContentParts: audioPlayerNodeRef is null")),!n&&e.text&&(r+=e.text,console.log("[BIDI] handleContentParts: accumulated text part",{text:e.text.substring(0,50),index:t,totalAccumulated:r.length}))}),r&&(console.log("[BIDI] handleContentParts: calling appendAssistantContent once",{textLength:r.length,finished:t}),mt(r,t))},[mt]),ht=o(()=>{z(!1),console.log("[BIDI] handleTurnComplete called",{currentAssistantId:je.current,currentInputId:Ge.current}),Ae(e=>{const t=e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing?h(h({},e),{},{isProcessing:!1}):e});return console.log("[BIDI] handleTurnComplete: state update",{prevLength:e.length,newLength:t.length,finalizedCount:e.filter(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing}).length}),t}),je.current=null,Ge.current=null,Ke.current=!1,Xe.current=null},[]),bt=o(()=>{z(!1),Pe.current&&Pe.current.port.postMessage({command:"endOfAudio"}),je.current=null,Ge.current=null,Xe.current=null,Ae(e=>e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)?h(h({},e),{},{isProcessing:!1,metadata:h(h({},e.metadata),{},{interrupted:!0})}):e}))},[]),yt=o(()=>{var e,t,n,r,a;ke(!1),z(!1),He.current=!1,Ie("idle"),Re(null),Ye.current=!1,Xe.current=null,De.current&&De.current.readyState===WebSocket.OPEN&&De.current.close(),De.current=null,null===(e=Pe.current)||void 0===e||e.disconnect(),null===(t=Me.current)||void 0===t||t.close(),Pe.current=null,Me.current=null,null===(n=Fe.current)||void 0===n||n.disconnect(),null===(r=Be.current)||void 0===r||r.close(),Fe.current=null,Be.current=null,O(Ue.current),Ue.current=null,null===(a=ze.current)||void 0===a||a.reset(),ze.current=null,qe.current=!1},[]),wt=o(e=>{var t,n,r,a,o;if(console.log("[BIDI] handleBidiEvent called",{event:e,isVoiceSessionActive:He.current,hasTurnComplete:!(null==e||!e.turnComplete),hasInterrupted:!(null==e||!e.interrupted),hasInputTranscription:!(null==e||!e.inputTranscription),hasOutputTranscription:!(null==e||!e.outputTranscription),hasContentParts:!(null==e||null===(t=e.content)||void 0===t||!t.parts)}),!e)return void console.warn("[BIDI] handleBidiEvent: received null/undefined event");const i=null!==(n=e.conclusion_detected)&&void 0!==n?n:e.conclusionDetected;var s;"boolean"==typeof i&&i&&(null===(s=Ze.current)||void 0===s||s.call(Ze),_e(!0));if("boolean"==typeof i&&i)return yt(),void Ae(e=>{const t=[...e];for(let e=t.length-1;e>=0;e--)if("assistant"===t[e].role){t[e]=h(h({},t[e]),{},{conclusionDetected:!0});break}return t});if(e.interrupted)return console.log("[BIDI] handleBidiEvent: processing interrupted"),void bt();if(e.inputTranscription){const t=e.inputTranscription.text||"",n=Boolean(e.inputTranscription.finished);console.log("[BIDI] handleBidiEvent: processing inputTranscription",{text:t.substring(0,50),textLength:t.length,finished:n,hasText:!!t}),t||n?(J(u),gt(t,n)):console.warn("[BIDI] handleBidiEvent: inputTranscription event has no text and not finished",e.inputTranscription)}const l=null!==(r=e.sources)&&void 0!==r?r:e.Sources;if(Array.isArray(l)&&l.length>0){const e=l.map(e=>{var t,n,r,a,o,i;return{source_type:null!==(t=null!==(n=e.source_type)&&void 0!==n?n:e.sourceType)&&void 0!==t?t:"file",source_id:null!==(r=null!==(a=e.source_id)&&void 0!==a?a:e.sourceid)&&void 0!==r?r:e.sourceId,source_name:null!==(o=null!==(i=e.source_name)&&void 0!==i?i:e.sourceName)&&void 0!==o?o:"",url:e.url}}).filter(e=>e.source_id||e.url);if(0===e.length)return;Ae(t=>{const n=[...t];let r=!1;for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=h(h({},n[t]),{},{sources:e}),r=!0;break}return r||(Xe.current=e),n})}var c,d;if(!Ye.current&&(null!==(c=e.outputTranscription)&&void 0!==c&&c.text||null!==(d=e.content)&&void 0!==d&&d.parts))return void(e.turnComplete&&ht());if(null!==(a=e.outputTranscription)&&void 0!==a&&a.text&&(Ke.current=!0,mt(e.outputTranscription.text,Boolean(e.outputTranscription.finished))),null!==(o=e.content)&&void 0!==o&&o.parts){var p;const t=(null===(p=e.content)||void 0===p?void 0:p.finished)||e.finished||!1;ft(e.content.parts,t,Ke.current)}if(e.prompts&&Array.isArray(e.prompts)&&e.prompts.length>0){console.log("[BIDI] handleBidiEvent: attaching prompts to last assistant message",{count:e.prompts.length}),Ae(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=h(h({},n[t]),{},{prompts:e.prompts});break}return n});try{ee(u,e.prompts)}catch(e){}}e.turnComplete?ht():e.interrupted||e.inputTranscription||e.outputTranscription||e.content||e.prompts||console.warn("[BIDI] handleBidiEvent: event had no recognized fields",e)},[mt,gt,ft,bt,ht,yt]),vt=o(e=>{if(!He.current)return;const t=ze.current;if(t)return void t.process(e);const n=De.current;n&&n.readyState===WebSocket.OPEN&&n.send(e)},[]),Et=o(async()=>{if(!qe.current&&"undefined"!=typeof window)try{const[e,t]=await async function(){if("undefined"==typeof window)throw new Error("Audio player can only be initialized in the browser");const e=new AudioContext({sampleRate:24e3}),t=new Blob(["\n class PCMPlayerProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.bufferSize = 24000 * 180;\n this.buffer = new Float32Array(this.bufferSize);\n this.writeIndex = 0;\n this.readIndex = 0;\n this.port.onmessage = (event) => {\n if (event.data?.command === 'endOfAudio') {\n this.readIndex = this.writeIndex;\n return;\n }\n const int16Samples = new Int16Array(event.data);\n this.enqueue(int16Samples);\n };\n }\n\n enqueue(samples) {\n for (let i = 0; i < samples.length; i += 1) {\n const floatVal = samples[i] / 32768;\n this.buffer[this.writeIndex] = floatVal;\n this.writeIndex = (this.writeIndex + 1) % this.bufferSize;\n if (this.writeIndex === this.readIndex) {\n this.readIndex = (this.readIndex + 1) % this.bufferSize;\n }\n }\n }\n\n process(inputs, outputs) {\n const output = outputs[0];\n const framesPerBlock = output[0].length;\n for (let frame = 0; frame < framesPerBlock; frame += 1) {\n output[0][frame] = this.buffer[this.readIndex];\n if (output.length > 1) {\n output[1][frame] = this.buffer[this.readIndex];\n }\n if (this.readIndex !== this.writeIndex) {\n this.readIndex = (this.readIndex + 1) % this.bufferSize;\n }\n }\n return true;\n }\n }\n\n registerProcessor('pcm-player-processor', PCMPlayerProcessor);\n "],{type:"application/javascript"}),n=URL.createObjectURL(t);await e.audioWorklet.addModule(n);const r=new AudioWorkletNode(e,"pcm-player-processor");return r.connect(e.destination),URL.revokeObjectURL(n),[r,e]}();Pe.current=e,Me.current=t,await t.resume();const n=e=>{const t=De.current;t&&t.readyState===WebSocket.OPEN&&t.send(e)};ze.current=B({sampleRate:16e3},{onSpeechStart:()=>{var e;null===(e=Pe.current)||void 0===e||e.port.postMessage({command:"endOfAudio"});const t=De.current;t&&t.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"interrupt"}))},onVoiceFrame:n,onSpeechEnd:()=>{const e=De.current;e&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"audio_end"}))}});const[r,a,o]=await _(vt);Fe.current=r,Be.current=a,Ue.current=o,await a.resume(),qe.current=!0}catch(e){throw console.error("Failed to initialize audio pipeline",e),e}},[vt]),St=o(()=>{if("undefined"!=typeof window&&et&&(!De.current||De.current.readyState!==WebSocket.OPEN)){Ie("connecting"),Re(null);try{const e=new WebSocket(et);De.current=e,e.onopen=()=>{Ie("connected")},e.onmessage=e=>{try{var t,n;const r="string"==typeof e.data?e.data.substring(0,200):"binary";console.log("[BIDI] WebSocket message received",{dataLength:null===(t=e.data)||void 0===t?void 0:t.length,dataPreview:r});const a=JSON.parse(e.data);console.log("[BIDI] WebSocket message parsed",{hasTurnComplete:!!a.turnComplete,hasInterrupted:!!a.interrupted,hasInputTranscription:!!a.inputTranscription,hasOutputTranscription:!!a.outputTranscription,hasContentParts:!(null===(n=a.content)||void 0===n||!n.parts),payload:a}),wt(a)}catch(t){console.error("[BIDI] Failed to parse WebSocket event",{error:t,data:e.data})}},e.onerror=()=>{Ie("error"),Re("Voice session connection error"),z(!1)},e.onclose=()=>{De.current=null,Ie("idle"),z(!1),He.current&&setTimeout(()=>{St()},5e3)}}catch(e){console.error("Failed to open voice websocket",e),Ie("error"),Re(e instanceof Error?e.message:"Unable to start voice session")}}},[wt,et]),kt=o(async()=>{if(m&&u){Re(null),Ie(e=>"connected"===e?e:"connecting"),ke(!0),He.current=!0,_e(!1),Ye.current=!1,Ae(e=>{if(e.length>0||L.length>0)return e;if(!i||""===i.trim())return[];return[te({id:"bidi-welcome-".concat(Date.now()),role:"assistant",content:i,metadata:{source:"bidi"}})]}),St();try{await Et()}catch(e){console.error("Failed to start audio pipeline",e),Re(e instanceof Error?e.message:"Unable to access microphone"),Ie("error")}}},[m,u,i,St,Et,L]),Tt=o(()=>{Se?yt():"connecting"!==xe&&kt()},[Se,kt,yt,xe]),At=o(e=>{const t=e.trim();if(!t)return;Ye.current=!0;const n=De.current;if(!n||n.readyState!==WebSocket.OPEN)return void Re("Voice session is not connected yet");n.send(JSON.stringify({type:"text",text:t})),J(u),z(!0);const r=te({id:"bidi-user-".concat(Date.now()),role:"user",content:t,metadata:{source:"bidi"}});Ae(e=>[...e,r]),M("")},[]);a(()=>{He.current=Se},[Se]),a(()=>()=>{var e,t,n,r;De.current&&De.current.readyState===WebSocket.OPEN&&De.current.close(),null===(e=Pe.current)||void 0===e||e.disconnect(),null===(t=Me.current)||void 0===t||t.close(),null===(n=Fe.current)||void 0===n||n.disconnect(),null===(r=Be.current)||void 0===r||r.close(),O(Ue.current),Ue.current=null,qe.current=!1},[]);const xt=o(()=>{(e=>{try{const t=Z(e);localStorage.removeItem("".concat(H,"_").concat(e)),null!=t&&t.conversationId&&Y(e,t.conversationId)}catch(e){}})(u),ee(u,[]),ae(null),ie(null),ce(null),se.current=null,ue.current=null,D([]),Ae([]),Y(u,Oe),pe(!1),me(!1),ye({}),he(null),we.current=!1,Ye.current=!1,nt.current=!1,rt.current=!1;const e="widget-session-".concat(Math.random().toString(36).slice(2,9));if(Q(u,e,{settingsSnapshot:JSON.stringify({value:v,unit:null==E?void 0:E.toUpperCase()})}),Le(e),i&&""!==i.trim()&&D([h(h({},te({id:Date.now().toString(),role:"assistant",content:i})),{},{isWelcome:!0})]),y){ne(b).length>0&&pe(!0)}},[u,Oe,i,y,b,v,E]),It=r(xt);a(()=>{It.current=xt},[xt]),a(()=>{at.current=!1,ot.current={value:null,unit:null}},[u]),a(()=>{if(!u||!v)return;const e=K(v,E);if(!e)return;const t=ot.current,n=at.current&&(t.value!==v||t.unit!==E);if(at.current=!0,ot.current={value:v,unit:E},n)return console.warn("[Session] Inactivity timeout config changed — resetting conversation."),void It.current();let r=null;const a=()=>{const t=Z(u);if(!t)return;if(!t.firstInteractionAt)return void(r=setTimeout(a,e));const n=new Date(t.lastActivity).getTime(),o=Date.now()-n,i=e-o;if(i<=0)return console.warn("[Session] Inactivity timeout reached! Resetting conversation immediately."),void It.current();r=setTimeout(a,i)};return a(),()=>{r&&clearTimeout(r)}},[u,v,E,Oe]);const Ct=t(()=>s,[s]),Rt=t(()=>{const e=[...L.map(e=>h(h({},e),{},{metadata:e.metadata||{source:"sse"}})),...Te];return Array.from(new Map(e.map(e=>[e.id,e])).values()).sort((e,t)=>(e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime())-(t.timestamp instanceof Date?t.timestamp.getTime():new Date(t.timestamp).getTime()))},[Te,L]);return a(()=>{Se&&console.log("[BIDI] bidiMessages state changed",{count:Te.length,messages:Te.map(e=>{var t,n;return{id:e.id,role:e.role,contentLength:(null===(t=e.content)||void 0===t?void 0:t.length)||0,isProcessing:e.isProcessing,hasContent:!!e.content,contentPreview:null===(n=e.content)||void 0===n?void 0:n.substring(0,50)}})})},[Te,Se]),{conversationId:Oe,isOpen:T,isMinimized:x,isDark:C,messages:Rt,inputValue:P,isLoading:F,isConversationLoading:ve,widgetRef:G,quickQuestions:Ct,isVoiceSessionActive:Se,voiceStatus:xe,voiceError:Ce,voiceConclusionForCsat:Ne,onboardingQuestions:b,onboardingActive:de,onboardingCompleted:ge,handleOnboardingFormSubmit:lt,widgetFilter:re,setWidgetFilter:ae,addAssistantMessage:it,setInputValue:M,handleSend:ut,handleQuickQuestion:dt,sendMessage:st,toggleChat:()=>{A(e=>!e),I(!1)},toggleTheme:()=>{R(e=>!e)},toggleMinimize:()=>{I(e=>!e)},closeChat:()=>{A(!1)},handleDecision:pt,handleVoiceToggle:Tt,sendBidiTextMessage:At,resetConversation:xt}},ae=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim(),oe=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ie=e=>{const t=(e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()))(e);return t.charAt(0).toUpperCase()+t.slice(1)};
2
2
  /**
3
3
  * @license lucide-react v0.575.0 - ISC
4
4
  *
@@ -8589,7 +8589,10 @@
8589
8589
  * DEFAULT_SPEECH_GATE_CONFIG.
8590
8590
  *
8591
8591
  * @param {{ sampleRate: number, energyThreshold?: number, speechStartMs?: number, hangoverMs?: number, preRollMs?: number }} config
8592
- * @param {{ onVoiceFrame: (pcm: ArrayBuffer) => void, onSpeechEnd: () => void }} callbacks
8592
+ * @param {{ onSpeechStart?: () => void, onVoiceFrame: (pcm: ArrayBuffer) => void, onSpeechEnd: () => void }} callbacks
8593
+ * onSpeechStart fires the instant a turn opens — use it for barge-in
8594
+ * (stop any assistant TTS still playing). onVoiceFrame emits each voiced
8595
+ * PCM frame; onSpeechEnd fires when the turn closes after the hangover.
8593
8596
  */
8594
8597
  function createSpeechGate(config, callbacks) {
8595
8598
  var _config$energyThresho, _config$speechStartMs, _config$hangoverMs, _config$preRollMs;
@@ -8637,10 +8640,14 @@
8637
8640
  if (voiced) {
8638
8641
  voicedRunMs += durationMs;
8639
8642
  if (voicedRunMs >= cfg.speechStartMs) {
8640
- // Confirmed speech — open the turn and flush the pre-roll (which
8641
- // contains the voiced onset) before going live.
8643
+ var _callbacks$onSpeechSt;
8644
+ // Confirmed speech — open the turn. Fire onSpeechStart FIRST so the
8645
+ // caller can barge in (stop assistant TTS still playing) before we
8646
+ // start streaming this utterance, then flush the pre-roll (which
8647
+ // contains the voiced onset) and go live.
8642
8648
  speaking = true;
8643
8649
  silenceRunMs = 0;
8650
+ (_callbacks$onSpeechSt = callbacks.onSpeechStart) === null || _callbacks$onSpeechSt === void 0 || _callbacks$onSpeechSt.call(callbacks);
8644
8651
  for (const frame of preRoll) callbacks.onVoiceFrame(frame.pcm);
8645
8652
  preRoll = [];
8646
8653
  preRollMsBuffered = 0;
@@ -10581,6 +10588,25 @@
10581
10588
  speechGateRef.current = createSpeechGate({
10582
10589
  sampleRate: 16000
10583
10590
  }, {
10591
+ // Barge-in: the instant the user starts talking, stop any assistant
10592
+ // TTS still playing so we don't talk over them. endOfAudio drops the
10593
+ // player's buffered audio immediately (readIndex → writeIndex). No-op
10594
+ // when nothing is playing (e.g. the user's first utterance).
10595
+ onSpeechStart: () => {
10596
+ var _audioPlayerNodeRef$c2;
10597
+ // Barge-in: user started talking → (1) stop assistant TTS already
10598
+ // buffered locally, and (2) tell the backend to cancel the in-flight
10599
+ // reply so its remaining TTS doesn't clobber the next turn's audio.
10600
+ (_audioPlayerNodeRef$c2 = audioPlayerNodeRef.current) === null || _audioPlayerNodeRef$c2 === void 0 || _audioPlayerNodeRef$c2.port.postMessage({
10601
+ command: "endOfAudio"
10602
+ });
10603
+ const ws = websocketRef.current;
10604
+ if (ws && ws.readyState === WebSocket.OPEN) {
10605
+ ws.send(JSON.stringify({
10606
+ type: "interrupt"
10607
+ }));
10608
+ }
10609
+ },
10584
10610
  onVoiceFrame: sendVoicePcm,
10585
10611
  onSpeechEnd: () => {
10586
10612
  const ws = websocketRef.current;
@@ -10753,11 +10779,11 @@
10753
10779
  }, [isVoiceSessionActive]);
10754
10780
  reactExports.useEffect(() => {
10755
10781
  return () => {
10756
- var _audioPlayerNodeRef$c2, _audioPlayerContextRe2, _audioRecorderNodeRef2, _audioRecorderContext2;
10782
+ var _audioPlayerNodeRef$c3, _audioPlayerContextRe2, _audioRecorderNodeRef2, _audioRecorderContext2;
10757
10783
  if (websocketRef.current && websocketRef.current.readyState === WebSocket.OPEN) {
10758
10784
  websocketRef.current.close();
10759
10785
  }
10760
- (_audioPlayerNodeRef$c2 = audioPlayerNodeRef.current) === null || _audioPlayerNodeRef$c2 === void 0 || _audioPlayerNodeRef$c2.disconnect();
10786
+ (_audioPlayerNodeRef$c3 = audioPlayerNodeRef.current) === null || _audioPlayerNodeRef$c3 === void 0 || _audioPlayerNodeRef$c3.disconnect();
10761
10787
  (_audioPlayerContextRe2 = audioPlayerContextRef.current) === null || _audioPlayerContextRe2 === void 0 || _audioPlayerContextRe2.close();
10762
10788
  (_audioRecorderNodeRef2 = audioRecorderNodeRef.current) === null || _audioRecorderNodeRef2 === void 0 || _audioRecorderNodeRef2.disconnect();
10763
10789
  (_audioRecorderContext2 = audioRecorderContextRef.current) === null || _audioRecorderContext2 === void 0 || _audioRecorderContext2.close();