@eshal-bot/chat-widget 0.1.65 → 0.1.67

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*as e from"react";import t,{useMemo as n,useState as r,useRef as o,useEffect as a,useCallback as i,forwardRef as s,createElement as l,isValidElement as c,Children as u,PureComponent as d,useImperativeHandle as p,cloneElement as f,useContext as g,createContext as h,Component as m}from"react";import{createRoot as b}from"react-dom/client";import{Fragment as y,jsx as v,jsxs as w}from"react/jsx-runtime";import{createPortal as S}from"react-dom";function E(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 k(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 x(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 A(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?x(Object(n),!0).forEach(function(t){k(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):x(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function T(e,t){if(null==e)return{};var n,r,o=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 a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}const O="processing_start",C="text_chunk",I="processing_end",N="complete",_="error",R="human_decision_required",P=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===C||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 A({type:C,content:e},n)}return r===O||"processing_start"===n.type?A({type:O},n):r===I||"processing_end"===n.type?A({type:I},n):r===N||"complete"===n.type?A({type:N,finalContent:n.finalContent||n.content||""},n):r===_||"error"===n.type?A({type:_,error:n.error||n.message||"Unknown error"},n):r===R||"human_decision_required"===n.type?A({type:R,decisionId:n.decisionId||n.decision_id,question:n.question||"",options:n.options||[],context:n.context||{}},n):r?A({type:r},n):n}catch(e){return null}},L=["prompts"];class D extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SSE stream ended before completion"),this.name="IncompleteStreamError"}}const M=async(e,t,n,r)=>{const o={"Content-Type":"application/json",Accept:"text/event-stream"};r?o["x-eshal-key"]=r:n&&(o["x-eshal-org"]=n);const a=await fetch("".concat(t.replace(/\/$/,""),"/api/v1/support"),{method:"POST",headers:o,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},F=()=>({id:"skeleton-".concat(Date.now()),role:"assistant",content:"",timestamp:new Date,isProcessing:!0}),j=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},B=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e(e=>{const r=[...e||[]],o=r[r.length-1];if("assistant"===(null==o?void 0:o.role)){const e=n||{},{prompts:a}=e,i=T(e,L);r[r.length-1]=A(A(A({},o),i),{},{content:t,isProcessing:!1},null!=a&&{prompts:j(a)})}return r})},U=(e,t,n,r,o)=>{var a;if(e&&e.type)switch(e.type){case O:break;case C:o.current||(o.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],F()]}return e}));const i=e.content||(null===(a=e.choices)||void 0===a||null===(a=a[0])||void 0===a||null===(a=a.delta)||void 0===a?void 0:a.content)||"";i&&(n.current+=i,r(n.current));break;case I:(e=>{e(e=>{const t=[...e||[]],n=t[t.length-1];return null!=n&&n.isProcessing&&(t[t.length-1]=A(A({},n),{},{isProcessing:!1})),t})})(t);break;case N:{const r=e.finalContent||n.current,o={};"boolean"==typeof e.conclusionDetected?o.conclusionDetected=e.conclusionDetected:"boolean"==typeof e.conclusion_detected&&(o.conclusionDetected=e.conclusion_detected);const a=A(A({},o),{},{prompts:e.prompts});B(t,r,a);break}case _:((e,t)=>{e(e=>{const n=[...e||[]],r=n[n.length-1];return"assistant"===(null==r?void 0:r.role)&&(n[n.length-1]=A(A({},r),{},{content:(r.content||"")+"\n\nError: ".concat(t),isProcessing:!1})),n})})(t,e.error||"Unknown error occurred");break;case R:{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)}},z=async(e,t)=>{const n=(e=>{let t=null,n=null,r=0;const o=a=>{if(a-r<16)n=requestAnimationFrame(o);else{if(null!==t){const n=t;t=null,r=a,e(e=>{const t=[...e||[]],r=t[t.length-1];return"assistant"===(null==r?void 0:r.role)&&(t[t.length-1]=A(A({},r),{},{content:n})),t})}n=null}};return e=>{t=e,null===n&&(n=requestAnimationFrame(o))}})(t),r=e.getReader(),o=new TextDecoder;let a="";const i={current:""},s={current:!1};let l=!1;try{for(;;){const{value:e,done:h}=await r.read();if(h)break;a+=o.decode(e,{stream:!0});const m=a.split(/\r?\n\r?\n/);a=m.pop()||"";for(const e of m){var c,u;const r=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);if(0===r.length)continue;const o=r.filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim());if(0===o.length)continue;const a=o.join("\n");if("[DONE]"===a)continue;let h;try{h=JSON.parse(a)}catch(e){continue}if(h){if(h.type){if("processing_start"===h.type||"processing_end"===h.type)continue;if("text_chunk"===h.type){var d;const e=(null===(d=h.choices)||void 0===d||null===(d=d[0])||void 0===d||null===(d=d.delta)||void 0===d?void 0:d.content)||h.content;e&&(s.current||(s.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],F()]}return e})),i.current+=e,n(i.current));continue}if("complete"===h.type){var p,f,g;l=!0;const e=null!==(p=null!==(f=h.Sources)&&void 0!==f?f:h.sources)&&void 0!==p?p:[],n=Array.isArray(e)?e.map(e=>{var t,n,r,o,a;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!==(o=null!==(a=e.source_name)&&void 0!==a?a:e.sourceName)&&void 0!==o?o:"",url:e.url}}).filter(e=>e.source_id||e.url):[],r=(null===(g=h.choices)||void 0===g||null===(g=g[0])||void 0===g||null===(g=g.delta)||void 0===g?void 0:g.content)||h.finalContent||i.current,o={};"boolean"==typeof h.conclusionDetected?o.conclusionDetected=h.conclusionDetected:"boolean"==typeof h.conclusion_detected&&(o.conclusionDetected=h.conclusion_detected);const a=A(A({},o),{},{prompts:h.prompts});B(t,r,a),n.length>0&&t(e=>{const t=[...e||[]],o=t[t.length-1];return"assistant"===(null==o?void 0:o.role)&&(t[t.length-1]=A(A({},o),{},{sources:n,content:r,isProcessing:!1})),t});continue}if("error"===h.type){t(e=>{const t=[...e||[]],n=t[t.length-1];return"assistant"===(null==n?void 0:n.role)&&(t[t.length-1]=A(A({},n),{},{content:(n.content||"")+"\n\nError: ".concat(h.error||"Unknown error occurred"),isProcessing:!1})),t});continue}const e=P(a);if(e&&e.type){console.log("🔍 Parsed stream event:",e.type,e),U(e,t,i,n,s);continue}}if("chat.completion.chunk"===h.object&&null!==(c=h.choices)&&void 0!==c&&null!==(c=c[0])&&void 0!==c&&null!==(c=c.delta)&&void 0!==c&&c.content)s.current||(s.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],F()]}return e})),i.current+=h.choices[0].delta.content,n(i.current);else if(null!==(u=h.choices)&&void 0!==u&&null!==(u=u[0])&&void 0!==u&&u.finish_reason&&null!==h.choices[0].finish_reason){l=!0;const e={prompts:h.prompts};B(t,i.current,e)}}}}}finally{r.releaseLock()}if(!l)throw new D(i.current?"Stream ended mid-response — partial content received":"Stream ended before any content was received")};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 o=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1}}),a=t.createMediaStreamSource(o),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]))*q;return t.buffer}(t.data);e(n)},a.connect(i),[i,t,o]}function G(e){e&&e.getTracks().forEach(e=>e.stop())}const q=32767;const H=.025,V=200,W=1e3,Y=300;function K(e,t){var n,r,o,a;const i=e.sampleRate,s=null!==(n=e.energyThreshold)&&void 0!==n?n:H,l=null!==(r=e.speechStartMs)&&void 0!==r?r:V,c=null!==(o=e.hangoverMs)&&void 0!==o?o:W,u=null!==(a=e.preRollMs)&&void 0!==a?a:Y;let d=!1,p=0,f=0,g=[],h=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?f=0:(f+=n,f>=c&&(d=!1,p=0,f=0,t.onSpeechEnd()));else{for(g.push({pcm:e,durationMs:n}),h+=n;h>u&&g.length>1;){var o;const e=g.shift();h-=null!==(o=null==e?void 0:e.durationMs)&&void 0!==o?o:0}if(r){if(p+=n,p>=l){var a;d=!0,f=0,null===(a=t.onSpeechStart)||void 0===a||a.call(t);for(const e of g)t.onVoiceFrame(e.pcm);g=[],h=0}}else p=0}},reset:()=>{d=!1,p=0,f=0,g=[],h=0},isSpeaking:()=>d}}const X=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(/^\/+/,"")):""},Q=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},ee=e=>{var t;if(!e)return 99;const n=String(e).toLowerCase();return null!==(t=J[n])&&void 0!==t?t:99},te="eshal_chat_session",ne="eshal_chat_session_messages";function re(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 oe=(e,t,n,r)=>{if(e&&t)try{const o=null==r?void 0:r.cap,a=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 A(A(A({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}:{})}):[]}(re(n,o,a));localStorage.setItem("".concat(ne,"_").concat(e,"_").concat(t),JSON.stringify(i))}catch(e){}},ae=(e,t)=>{if(e&&t)try{localStorage.removeItem("".concat(ne,"_").concat(e,"_").concat(t))}catch(e){}},ie=(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},se=e=>{try{const t=localStorage.getItem("".concat(te,"_").concat(e));return t?JSON.parse(t):null}catch(e){return null}},le=(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=ie(t,n);if(!r)return!0;const o=new Date(e.lastActivity).getTime(),a=Date.now()-o,i=a<r;return i||console.log("[Session] Session expired. Elapsed: ".concat(Math.floor(a/1e3),"s, Timeout: ").concat(Math.floor(r/1e3),"s")),i},ce=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(te,"_").concat(e),JSON.stringify(A({conversationId:t,lastActivity:r,createdAt:r,firstInteractionAt:null},n)))}catch(e){}},ue=e=>{try{const t=se(e);if(!t)return;const n=(new Date).toISOString();t.lastActivity=n,t.firstInteractionAt||(t.firstInteractionAt=n),localStorage.setItem("".concat(te,"_").concat(e),JSON.stringify(t))}catch(e){}},de=(e,t)=>{try{if(!e)return;if(!Array.isArray(t)||0===t.length)return void localStorage.removeItem("".concat(te,"_prompts_").concat(e));localStorage.setItem("".concat(te,"_prompts_").concat(e),JSON.stringify(t))}catch(e){}},pe=e=>{let{id:t,role:n,content:r,isProcessing:o=!1,metadata:a}=e;return{id:t,role:n,content:r,timestamp:new Date,isProcessing:o,metadata:a}},fe=(e,t)=>{const n=[...e.map(e=>A(A({},e),{},{metadata:e.metadata||{source:"sse"}})),...t];return Array.from(new Map(n.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()))},ge=e=>e&&e.length>0?e:[],he=e=>{let{welcomeMessage:t,quickQuestions:s=[],apiBaseUrl:l,apiKey:c,organizationId:u,secretKey:d,autoOpen:p,openDelay:f,darkMode:g,enableVoiceInteraction:h=!1,provideCitations:m=!0,onboardingQuestions:b=[],onboardingEnabled:y=!1,collectionPrompt:v,inactivityTimeoutValue:w,inactivityTimeoutUnit:S,messageLimits:E}=e;const k=n(()=>({cap:"number"==typeof(null==E?void 0:E.cap)&&E.cap>0?E.cap:200,trimBatch:"number"==typeof(null==E?void 0:E.trimBatch)&&E.trimBatch>0?E.trimBatch:50}),[null==E?void 0:E.cap,null==E?void 0:E.trimBatch]),[x,T]=r(p),[O,C]=r(!1),[I,N]=r(g),[_,R]=r(()=>{try{const e=se(u);if(void 0!==w&&e&&le(e,w,S))return[]}catch(e){}return t?[A(A({},pe({id:Date.now().toString(),role:"assistant",content:t})),{},{isWelcome:!0})]:[]}),[P,L]=r(""),[F,j]=r(!1),B=o(null),U=o(1),[q,H]=r(null),[V,W]=r(null),Y=o(null);a(()=>{Y.current=V},[V]);const[Z,Q]=r(null),J=o(null);a(()=>{J.current=Z},[Z]);const[he,me]=r(!1),[be,ye]=r(()=>{try{const e=se(u);if(e&&e.onboardingCompleted)return!0}catch(e){}return!1}),[ve,we]=r(null),[Se,Ee]=r({}),ke=o(!1),xe=o(!1),[Ae,Te]=r(!1),[Oe,Ce]=r(!1),[Ie,Ne]=r([]),[_e,Re]=r("idle"),[Pe,Le]=r(null),[De,Me]=r(!1),[Fe,je]=r(()=>{try{const e=se(u);if(void 0!==w&&e&&le(e,w,S))return e.conversationId}catch(e){}return"widget-session-".concat(Math.random().toString(36).slice(2,9))}),Be=o(null),Ue=o(null),ze=o(null),$e=o(null),Ge=o(null),qe=o(null),He=o(null),Ve=o(null),We=o(null),Ye=o(!1),Ke=o(!1);o(null);const Xe=o(null);o(null);const Ze=o(!1),Qe=o(null),Je=o(!1),et=o(!1),tt=o(null),nt=o(null),rt=o(null),ot=o(null),at=n(()=>{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(Fe)},[l,u,Fe]),it=i(()=>{const e="msg-".concat(U.current);return U.current+=1,e},[]);a(()=>{if(p&&f>0){const e=setTimeout(()=>T(!0),f);return()=>clearTimeout(e)}},[p,f]),a(()=>{let e=!1;return(async()=>{try{const{default:t}=await Promise.resolve().then(function(){return R1}),n=new t({cache:!0,geoFromBrowser:!0,onError:()=>{}}),r=await n.init();if(e)return;if(null!=r&&r.fingerprintId&&(rt.current=r.fingerprintId),null!=r&&r.geo||null!=r&&r.ip){const e=r.geo||{};ot.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(()=>{N(g)},[g]);const st=o(!1),lt=o(!1),ct=o(!1),ut=o({value:null,unit:null});a(()=>{if(!u||!Fe||void 0===w)return;const e=se(u);if(e&&le(e,w,S)){if(Fe!==e.conversationId)return void je(e.conversationId);if(!st.current){st.current=!0;const e=((e,t)=>{if(!e||!t)return[];try{const n=localStorage.getItem("".concat(ne,"_").concat(e,"_").concat(t));if(!n)return[];const r=JSON.parse(n);return Array.isArray(r)?r.map(e=>A(A({},e),{},{timestamp:e.timestamp?new Date(e.timestamp):new Date})):[]}catch(e){return[]}})(u,Fe);if(e.length>0){if(lt.current=!0,t){var n;const r=null===(n=e[0])||void 0===n?void 0:n.timestamp,o=r instanceof Date?r.getTime():r?new Date(r).getTime():Date.now(),a=A(A({},pe({id:"welcome-restored",role:"assistant",content:t})),{},{isWelcome:!0,timestamp:new Date(o-1)});R([a,...e])}else R(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(te,"_prompts_").concat(e));return t&&JSON.parse(t)||[]}catch(e){return[]}})(u);e.length>0&&R(t=>{const n=[...t];for(let t=n.length-1;t>=0;t-=1)if("assistant"===n[t].role){n[t]=A(A({},n[t]),{},{prompts:e});break}return n})}}}}else if(st.current||(st.current=!0),e&&Fe===e.conversationId){const e="widget-session-".concat(Math.random().toString(36).slice(2,9));console.warn("[Session] Rotating expired ID ".concat(Fe," -> ").concat(e)),ae(u,Fe),je(e)}else null!=e&&e.conversationId&&e.conversationId!==Fe&&ae(u,e.conversationId),e&&e.conversationId===Fe||ce(u,Fe,{settingsSnapshot:JSON.stringify({value:w,unit:null==S?void 0:S.toUpperCase()})})},[u,Fe,l,w,S]),a(()=>{if(u&&_&&0!==_.length)for(let e=_.length-1;e>=0;e-=1){const t=_[e];if("assistant"===(null==t?void 0:t.role)&&Array.isArray(t.prompts)&&t.prompts.length>0)return void de(u,t.prompts)}},[_,u]),a(()=>{Ae||F||_.length<=k.cap||R(e=>re(e,k.cap,k.trimBatch))},[_.length,Ae,F,k.cap,k.trimBatch]),a(()=>{u&&Fe&&(Ae||F||oe(u,Fe,fe(_,Ie),k))},[_,Ie,u,Fe,Ae,F,k]),a(()=>{if(!y||be)return;ge(b).length>0&&me(!0)},[y,be,b]),a(()=>{t&&!lt.current&&R(e=>{if(!e.length)return[A(A({},pe({id:Date.now().toString(),role:"assistant",content:t})),{},{isWelcome:!0})];const[n,...r]=e;return n.isWelcome?[A(A({},n),{},{content:t}),...r]:e})},[t]),i(e=>{R(t=>t.map(t=>t.id===e.id?A(A({},t),e.update(t)):t))},[]);const dt=i(function(e){if(!e)return;const t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).replaceMarker||null;R(n=>[...t?(n||[]).filter(e=>{var n;return(null==e||null===(n=e.metadata)||void 0===n?void 0:n.synthesizedKind)!==t}):n||[],pe({id:it(),role:"assistant",content:e,metadata:t?{synthesizedKind:t}:void 0})])},[it]),pt=i(async(e,t,n)=>{const r=e.trim();if(!r)return{success:!1,error:"Message cannot be empty"};if(xe.current)return{success:!1,error:"A message is already being sent"};if(xe.current=!0,t&&!["inquiry","complaint","technical"].includes((t||"").toLowerCase())||(J.current=r,Q(r)),!l)return xe.current=!1,R(e=>[...e||[],pe({id:it(),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 o=["inquiry","complaint","technical","userName","email","phone","fullname","mobileno"];let a="inquiry";if(t){const e=t.toLowerCase();"fullname"===e||"name"===e?a="userName":"email"===e?a="email":"phone"===e||"mobileno"===e?a="phone":o.includes(e)&&(a=e)}if("inquiry"===a||"complaint"===a||"technical"===a){const e=pe({id:it(),role:"user",content:r});R(t=>{const r=(t||[]).map(e=>{var t;return"assistant"===e.role&&null!==(t=e.prompts)&&void 0!==t&&t.length?A(A({},e),{},{prompts:void 0}):e});return n&&n.skipUserAppend?r:[...r,e]}),L(""),j(!0)}else L("");try{const e=A(A(A(A(A({message:r,type:a,conversationId:Fe,enable_citation:null==m||m,channel:"WIDGET"},rt.current?{fingerprintId:rt.current}:{}),ot.current?{visitor:ot.current}:{}),q&&(q.category||q.tags&&q.tags.length)?{filter:q}:{}),Y.current?{routing:Y.current}:{}),{},{messageHistory:_.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=[500,1500];if("userName"===a||"email"===a||"phone"===a){const t=(await M(e,l,u,d)).getReader(),n=new TextDecoder;for(;;){const{done:e,value:r}=await t.read();if(e)break;n.decode(r)}return{success:!0}}if("inquiry"===a||"complaint"===a||"technical"===a){let n;for(let r=0;r<=t.length;r+=1)try{const t=await M(e,l,u,d);return await z(t,R),ue(u),{success:!0}}catch(e){if(n=e,e instanceof D&&r<t.length){R(e=>(e||[]).filter(e=>!e.isProcessing));const n=t[r];console.warn("[chat] stream dropped (attempt ".concat(r+1,"); retrying in ").concat(n,"ms — ").concat(e.message)),await new Promise(e=>setTimeout(e,n));continue}throw e}throw n}return await M(e,l,u),ue(u),{success:!0}}catch(e){return console.error("Error sending message:",e),"inquiry"!==a&&"complaint"!==a&&"technical"!==a||(j(!1),R(e=>[...(e||[]).filter(e=>!e.isProcessing),pe({id:it(),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{j(!1),xe.current=!1}},[l,c,it,u,_,Fe,V,q,m]),ft=i(async e=>{const t=ge(b);if(0===t.length)return;const n=[...t].sort((e,t)=>ee(e.fieldType)-ee(t.fieldType));for(const t of n){var r;const n=t.fieldType||"question",o=(null!==(r=e[n])&&void 0!==r?r:"").trim();if(!o)continue;const a=await pt(o,n);if(null==a||!a.success){const e=pe({id:it(),role:"assistant",content:(null==a?void 0:a.error)||"Something went wrong. Please try again.",isProcessing:!1});return void R(t=>[...t,e])}}me(!1),ye(!0),(e=>{try{const t=se(e);if(!t)return;t.onboardingCompleted=!0,localStorage.setItem("".concat(te,"_").concat(e),JSON.stringify(t))}catch(e){}})(u),Ee(t=>A(A({},t),e)),ve&&!ke.current&&(ke.current=!0,setTimeout(()=>{L(ve),we(null)},500))},[b,pt,it,ve,u]),gt=i(async()=>{const e=P.trim();e&&await pt(e)},[P,pt]),ht=i(async()=>{await gt()},[gt]),mt=i(async e=>{const t=null==e?void 0:e.trim();t&&await pt(t)},[pt]),bt=i(async(e,t,n)=>{if(R(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){Y.current=r,W(r);const e=J.current;J.current=null,Q(null),e&&e.trim()&&setTimeout(()=>{pt(e,"inquiry",{skipUserAppend:!0}).catch(e=>console.warn("[routing-clarification] re-send failed:",e))},0)}return}if("connect_agent"===n){const e=pe({id:it(),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."});R(t=>[...t,e])}else if("decline"===n){const e=pe({id:it(),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?"});R(t=>[...t,e])}},[it,pt,Z]);i(()=>{Ve.current&&(Ne(e=>e.map(e=>e.id===Ve.current?A(A({},e),{},{isProcessing:!1}):e)),Ve.current=null)},[]);const yt=i(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(Je.current=!0,!e||"string"==typeof e&&!e.trim())return void(t&&Ve.current&&(Ne(e=>e.map(e=>e.id===Ve.current?A(A({},e),{},{isProcessing:!1}):e)),Ve.current=null));const n=X(e);Ne(e=>{const r=e.length;let o=[...e];if(Ve.current){if(o.some(e=>e.id===Ve.current))o=o.map(e=>{if(e.id!==Ve.current)return e;const r=X("".concat(e.content||"").concat(n));return A(A({},e),{},{content:r,isProcessing:!t,metadata:A(A({},e.metadata),{},{transcriptionType:"input"})})});else{console.error("[BIDI] appendUserTranscription: ERROR - user message not found!",{expectedId:Ve.current,existingIds:o.map(e=>e.id)});const e="bidi-input-".concat(Date.now());Ve.current=e;const r=pe({id:e,role:"user",content:n,isProcessing:!t,metadata:{source:"bidi",transcriptionType:"input"}});o=[...o,r],console.log("[BIDI] appendUserTranscription: recreated lost user message",{messageId:e})}}else{const r="bidi-input-".concat(Date.now()),a=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(a);const l=pe({id:r,role:"user",content:n,isProcessing:!t,timestamp:s,metadata:{source:"bidi",transcriptionType:"input"}});o.some(e=>e.id===r)?(console.warn("[BIDI] appendUserTranscription: message already exists, updating instead",{messageId:r}),Ve.current=r,o=o.map(e=>e.id===r?A(A({},e),{},{content:"".concat(e.content||"").concat(n),isProcessing:!t}):e)):(o=[...o,l],Ve.current=r)}return o.length<r?(console.error("[BIDI] appendUserTranscription: CRITICAL ERROR - losing messages!",{prevLength:r,resultLength:o.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: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)}})}),e):o}),t&&(Ve.current=null,j(!0))},[]),vt=i(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(j(!1),console.log("[BIDI] appendAssistantContent called",{text:null==e?void 0:e.substring(0,50),finished:t,currentAssistantId:We.current,currentInputId:Ve.current}),!e||"string"==typeof e&&!e.trim())return console.log("[BIDI] appendAssistantContent: skipping empty text"),void(t&&We.current&&(Ne(e=>e.map(e=>e.id!==We.current?e:A(A({},e),{},{isProcessing:!1}))),We.current=null,Xe.current=null));const n="".concat(We.current||"new","-").concat(e.substring(0,100),"-").concat(t);if(Ze.current&&Qe.current===n)return;Ze.current=!0,Qe.current=n;const r=Ve.current;if(Ne(n=>{const o=n.length;let a=[...n];if(console.log("[BIDI] appendAssistantContent: starting update",{prevLength:o,prevMessageIds:n.map(e=>e.id),inputMessageIdToFinalize:r,currentAssistantId:We.current,textLength:e.length}),r){a.some(e=>e.id===r)?a=a.map(e=>e.id===r?A(A({},e),{},{isProcessing:!1}):e):console.warn("[BIDI] appendAssistantContent: input message not found for finalization",{inputMessageId:r,existingIds:a.map(e=>e.id)})}if(We.current){if(a.some(e=>e.id===We.current))a=a.map(n=>{var r;if(n.id!==We.current)return n;const o="".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:o.length,textLength:e.length}),A(A({},n),{},{content:o,isProcessing:!t},Array.isArray(nt.current)&&nt.current.length>0?{sources:nt.current}:{})}),Array.isArray(nt.current)&&nt.current.length>0&&(nt.current=null);else{console.error("[BIDI] appendAssistantContent: ERROR - assistant message not found!",{expectedId:We.current,existingIds:a.map(e=>e.id)});const n="bidi-assistant-".concat(Date.now());We.current=n;const r=pe({id:n,role:"assistant",content:e,isProcessing:!t,metadata:{source:"bidi"}});Array.isArray(nt.current)&&nt.current.length>0&&(r.sources=nt.current,nt.current=null),a=[...a,r],console.log("[BIDI] appendAssistantContent: recreated lost assistant message",{messageId:n})}}else{const n="bidi-assistant-".concat(Date.now()),o=Date.now(),i=r?new Date(o):new Date(o+1e3),s=pe({id:n,role:"assistant",content:e,isProcessing:!t,timestamp:i,metadata:{source:"bidi"}});Array.isArray(nt.current)&&nt.current.length>0&&(s.sources=nt.current,nt.current=null);a.some(e=>e.id===n)?(console.error("[BIDI] appendAssistantContent: ERROR - message ID collision!",{messageId:n,existingIds:a.map(e=>e.id)}),a=a.map(r=>r.id===n?A(A({},r),{},{content:"".concat(r.content||"").concat(e),isProcessing:!t},Array.isArray(nt.current)&&nt.current.length>0?{sources:nt.current}:{}):r),Array.isArray(nt.current)&&nt.current.length>0&&(nt.current=null),We.current=n):(a=[...a,s],We.current=n)}return console.log("[BIDI] appendAssistantContent: atomic state update complete",{prevLength:o,newLength:a.length,finished:t,messageIds:a.map(e=>e.id),messageRoles:a.map(e=>e.role)}),a.length<o?(console.error("[BIDI] appendAssistantContent: CRITICAL ERROR - losing messages!",{prevLength:o,resultLength:a.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: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)}})}),n):a}),r&&(Ve.current=null),t)console.log("[BIDI] appendAssistantContent: finalizing message",{messageId:We.current}),We.current=null,Xe.current=null;else{const e=updateKey;Promise.resolve().then(()=>{Xe.current===e&&(Xe.current=null)})}},[]),wt=i(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 o,a;null!==(o=e.inlineData)&&void 0!==o&&o.data&&null!==(a=e.inlineData.mimeType)&&void 0!==a&&a.startsWith("audio/pcm")&&(console.log("[BIDI] handleContentParts: sending audio data to player"),Ue.current?Ue.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,o=new Uint8Array(r);for(let e=0;e<r;e+=1)o[e]=n.charCodeAt(e);return o.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}),vt(r,t))},[vt]),St=i(()=>{j(!1),console.log("[BIDI] handleTurnComplete called",{currentAssistantId:We.current,currentInputId:Ve.current}),Ne(e=>{const t=e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing?A(A({},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}),We.current=null,Ve.current=null,et.current=!1,nt.current=null},[]),Et=i(()=>{j(!1),Ue.current&&Ue.current.port.postMessage({command:"endOfAudio"}),We.current=null,Ve.current=null,nt.current=null,Ne(e=>e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)?A(A({},e),{},{isProcessing:!1,metadata:A(A({},e.metadata),{},{interrupted:!0})}):e}))},[]),kt=i(()=>{var e,t,n,r,o;Ce(!1),j(!1),Ke.current=!1,Re("idle"),Le(null),Je.current=!1,nt.current=null,Be.current&&Be.current.readyState===WebSocket.OPEN&&Be.current.close(),Be.current=null,null===(e=Ue.current)||void 0===e||e.disconnect(),null===(t=ze.current)||void 0===t||t.close(),Ue.current=null,ze.current=null,null===(n=$e.current)||void 0===n||n.disconnect(),null===(r=Ge.current)||void 0===r||r.close(),$e.current=null,Ge.current=null,G(qe.current),qe.current=null,null===(o=He.current)||void 0===o||o.reset(),He.current=null,Ye.current=!1},[]),xt=i(e=>{var t,n,r,o,a;if(console.log("[BIDI] handleBidiEvent called",{event:e,isVoiceSessionActive:Ke.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=tt.current)||void 0===s||s.call(tt),Me(!0));if("boolean"==typeof i&&i)return kt(),void Ne(e=>{const t=[...e];for(let e=t.length-1;e>=0;e--)if("assistant"===t[e].role){t[e]=A(A({},t[e]),{},{conclusionDetected:!0});break}return t});if(e.interrupted)return console.log("[BIDI] handleBidiEvent: processing interrupted"),void Et();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?(ue(u),yt(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,o,a,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!==(o=e.source_id)&&void 0!==o?o:e.sourceid)&&void 0!==r?r:e.sourceId,source_name:null!==(a=null!==(i=e.source_name)&&void 0!==i?i:e.sourceName)&&void 0!==a?a:"",url:e.url}}).filter(e=>e.source_id||e.url);if(0===e.length)return;Ne(t=>{const n=[...t];let r=!1;for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=A(A({},n[t]),{},{sources:e}),r=!0;break}return r||(nt.current=e),n})}var c,d;if(!Je.current&&(null!==(c=e.outputTranscription)&&void 0!==c&&c.text||null!==(d=e.content)&&void 0!==d&&d.parts))return void(e.turnComplete&&St());if(null!==(o=e.outputTranscription)&&void 0!==o&&o.text&&(et.current=!0,vt(e.outputTranscription.text,Boolean(e.outputTranscription.finished))),null!==(a=e.content)&&void 0!==a&&a.parts){var p;const t=(null===(p=e.content)||void 0===p?void 0:p.finished)||e.finished||!1;wt(e.content.parts,t,et.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}),Ne(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=A(A({},n[t]),{},{prompts:e.prompts});break}return n});try{de(u,e.prompts)}catch(e){}}e.turnComplete?St():e.interrupted||e.inputTranscription||e.outputTranscription||e.content||e.prompts||console.warn("[BIDI] handleBidiEvent: event had no recognized fields",e)},[vt,yt,wt,Et,St,kt]),At=i(e=>{if(!Ke.current)return;const t=He.current;if(t)return void t.process(e);const n=Be.current;n&&n.readyState===WebSocket.OPEN&&n.send(e)},[]),Tt=i(async()=>{if(!Ye.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]}();Ue.current=e,ze.current=t,await t.resume();const n=e=>{const t=Be.current;t&&t.readyState===WebSocket.OPEN&&t.send(e)};He.current=K({sampleRate:16e3},{onSpeechStart:()=>{var e;null===(e=Ue.current)||void 0===e||e.port.postMessage({command:"endOfAudio"});const t=Be.current;t&&t.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"interrupt"}))},onVoiceFrame:n,onSpeechEnd:()=>{const e=Be.current;e&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"audio_end"}))}});const[r,o,a]=await $(At);$e.current=r,Ge.current=o,qe.current=a,await o.resume(),Ye.current=!0}catch(e){throw console.error("Failed to initialize audio pipeline",e),e}},[At]),Ot=i(()=>{if("undefined"!=typeof window&&at&&(!Be.current||Be.current.readyState!==WebSocket.OPEN)){Re("connecting"),Le(null);try{const e=new WebSocket(at);Be.current=e,e.onopen=()=>{Re("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 o=JSON.parse(e.data);console.log("[BIDI] WebSocket message parsed",{hasTurnComplete:!!o.turnComplete,hasInterrupted:!!o.interrupted,hasInputTranscription:!!o.inputTranscription,hasOutputTranscription:!!o.outputTranscription,hasContentParts:!(null===(n=o.content)||void 0===n||!n.parts),payload:o}),xt(o)}catch(t){console.error("[BIDI] Failed to parse WebSocket event",{error:t,data:e.data})}},e.onerror=()=>{Re("error"),Le("Voice session connection error"),j(!1)},e.onclose=()=>{Be.current=null,Re("idle"),j(!1),Ke.current&&setTimeout(()=>{Ot()},5e3)}}catch(e){console.error("Failed to open voice websocket",e),Re("error"),Le(e instanceof Error?e.message:"Unable to start voice session")}}},[xt,at]),Ct=i(async()=>{if(h&&u){Le(null),Re(e=>"connected"===e?e:"connecting"),Ce(!0),Ke.current=!0,Me(!1),Je.current=!1,Ne(e=>{if(e.length>0||_.length>0)return e;if(!t||""===t.trim())return[];return[pe({id:"bidi-welcome-".concat(Date.now()),role:"assistant",content:t,metadata:{source:"bidi"}})]}),Ot();try{await Tt()}catch(e){console.error("Failed to start audio pipeline",e),Le(e instanceof Error?e.message:"Unable to access microphone"),Re("error")}}},[h,u,t,Ot,Tt,_]),It=i(()=>{Oe?kt():"connecting"!==_e&&Ct()},[Oe,Ct,kt,_e]),Nt=i(e=>{const t=e.trim();if(!t)return;Je.current=!0;const n=Be.current;if(!n||n.readyState!==WebSocket.OPEN)return void Le("Voice session is not connected yet");n.send(JSON.stringify({type:"text",text:t})),ue(u),j(!0);const r=pe({id:"bidi-user-".concat(Date.now()),role:"user",content:t,metadata:{source:"bidi"}});Ne(e=>[...e,r]),L("")},[]);a(()=>{Ke.current=Oe},[Oe]),a(()=>()=>{var e,t,n,r;Be.current&&Be.current.readyState===WebSocket.OPEN&&Be.current.close(),null===(e=Ue.current)||void 0===e||e.disconnect(),null===(t=ze.current)||void 0===t||t.close(),null===(n=$e.current)||void 0===n||n.disconnect(),null===(r=Ge.current)||void 0===r||r.close(),G(qe.current),qe.current=null,Ye.current=!1},[]);const _t=i(()=>{(e=>{try{const t=se(e);localStorage.removeItem("".concat(te,"_").concat(e)),null!=t&&t.conversationId&&ae(e,t.conversationId)}catch(e){}})(u),de(u,[]),H(null),W(null),Q(null),Y.current=null,J.current=null,R([]),Ne([]),ae(u,Fe),me(!1),ye(!1),Ee({}),we(null),ke.current=!1,Je.current=!1,st.current=!1,lt.current=!1;const e="widget-session-".concat(Math.random().toString(36).slice(2,9));if(ce(u,e,{settingsSnapshot:JSON.stringify({value:w,unit:null==S?void 0:S.toUpperCase()})}),je(e),t&&""!==t.trim()&&R([A(A({},pe({id:Date.now().toString(),role:"assistant",content:t})),{},{isWelcome:!0})]),y){ge(b).length>0&&me(!0)}},[u,Fe,t,y,b,w,S]),Rt=o(_t);a(()=>{Rt.current=_t},[_t]),a(()=>{ct.current=!1,ut.current={value:null,unit:null}},[u]),a(()=>{if(!u||!w)return;const e=ie(w,S);if(!e)return;const t=ut.current,n=ct.current&&(t.value!==w||t.unit!==S);if(ct.current=!0,ut.current={value:w,unit:S},n)return console.warn("[Session] Inactivity timeout config changed — resetting conversation."),void Rt.current();let r=null;const o=()=>{const t=se(u);if(!t)return;if(!t.firstInteractionAt)return void(r=setTimeout(o,e));const n=new Date(t.lastActivity).getTime(),a=Date.now()-n,i=e-a;if(i<=0)return console.warn("[Session] Inactivity timeout reached! Resetting conversation immediately."),void Rt.current();r=setTimeout(o,i)};return o(),()=>{r&&clearTimeout(r)}},[u,w,S,Fe]);const Pt=n(()=>s,[s]),Lt=n(()=>fe(_,Ie),[Ie,_]);a(()=>{Oe&&console.log("[BIDI] bidiMessages state changed",{count:Ie.length,messages:Ie.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)}})})},[Ie,Oe]);const Dt=i((e,t)=>{R(n=>n.map(n=>"assistant"===n.role&&n.content===e?A(A({},n),{},{feedback:t}):n))},[]);return{conversationId:Fe,isOpen:x,isMinimized:O,isDark:I,messages:Lt,inputValue:P,isLoading:F,isConversationLoading:Ae,widgetRef:B,quickQuestions:Pt,isVoiceSessionActive:Oe,voiceStatus:_e,voiceError:Pe,voiceConclusionForCsat:De,onboardingQuestions:b,onboardingActive:he,onboardingCompleted:be,handleOnboardingFormSubmit:ft,widgetFilter:q,setWidgetFilter:H,addAssistantMessage:dt,setInputValue:L,handleSend:ht,handleQuickQuestion:mt,sendMessage:pt,toggleChat:()=>{T(e=>!e),C(!1)},toggleTheme:()=>{N(e=>!e)},toggleMinimize:()=>{C(e=>!e)},closeChat:()=>{T(!1)},handleDecision:bt,handleVoiceToggle:It,sendBidiTextMessage:Nt,resetConversation:_t,updateMessageFeedback:Dt}},me=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim(),be=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ye=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*as e from"react";import t,{useMemo as n,useState as r,useRef as o,useEffect as a,useCallback as i,forwardRef as s,createElement as l,isValidElement as c,Children as u,PureComponent as d,useImperativeHandle as p,cloneElement as f,useContext as g,createContext as h,Component as m}from"react";import{createRoot as b}from"react-dom/client";import{Fragment as y,jsx as v,jsxs as w}from"react/jsx-runtime";import{createPortal as S}from"react-dom";function E(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 k(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 x(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 A(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?x(Object(n),!0).forEach(function(t){k(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):x(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function T(e,t){if(null==e)return{};var n,r,o=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 a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}const O="processing_start",C="text_chunk",I="processing_end",N="complete",_="error",R="human_decision_required",P=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===C||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 A({type:C,content:e},n)}return r===O||"processing_start"===n.type?A({type:O},n):r===I||"processing_end"===n.type?A({type:I},n):r===N||"complete"===n.type?A({type:N,finalContent:n.finalContent||n.content||""},n):r===_||"error"===n.type?A({type:_,error:n.error||n.message||"Unknown error"},n):r===R||"human_decision_required"===n.type?A({type:R,decisionId:n.decisionId||n.decision_id,question:n.question||"",options:n.options||[],context:n.context||{}},n):r?A({type:r},n):n}catch(e){return null}},L=["prompts"];class D extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SSE stream ended before completion"),this.name="IncompleteStreamError"}}const M=async(e,t,n,r)=>{const o={"Content-Type":"application/json",Accept:"text/event-stream"};r?o["x-eshal-key"]=r:n&&(o["x-eshal-org"]=n);const a=await fetch("".concat(t.replace(/\/$/,""),"/api/v1/support"),{method:"POST",headers:o,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},F=()=>({id:"skeleton-".concat(Date.now()),role:"assistant",content:"",timestamp:new Date,isProcessing:!0}),j=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},B=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e(e=>{const r=[...e||[]],o=r[r.length-1];if("assistant"===(null==o?void 0:o.role)){const e=n||{},{prompts:a}=e,i=T(e,L);r[r.length-1]=A(A(A({},o),i),{},{content:t,isProcessing:!1},null!=a&&{prompts:j(a)})}return r})},U=(e,t,n,r,o)=>{var a;if(e&&e.type)switch(e.type){case O:break;case C:o.current||(o.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],F()]}return e}));const i=e.content||(null===(a=e.choices)||void 0===a||null===(a=a[0])||void 0===a||null===(a=a.delta)||void 0===a?void 0:a.content)||"";i&&(n.current+=i,r(n.current));break;case I:(e=>{e(e=>{const t=[...e||[]],n=t[t.length-1];return null!=n&&n.isProcessing&&(t[t.length-1]=A(A({},n),{},{isProcessing:!1})),t})})(t);break;case N:{const r=e.finalContent||n.current,o={};"boolean"==typeof e.conclusionDetected?o.conclusionDetected=e.conclusionDetected:"boolean"==typeof e.conclusion_detected&&(o.conclusionDetected=e.conclusion_detected);const a=A(A({},o),{},{prompts:e.prompts});B(t,r,a);break}case _:((e,t)=>{e(e=>{const n=[...e||[]],r=n[n.length-1];return"assistant"===(null==r?void 0:r.role)&&(n[n.length-1]=A(A({},r),{},{content:(r.content||"")+"\n\nError: ".concat(t),isProcessing:!1})),n})})(t,e.error||"Unknown error occurred");break;case R:{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)}},z=async(e,t)=>{const n=(e=>{let t=null,n=null,r=0;const o=a=>{if(a-r<16)n=requestAnimationFrame(o);else{if(null!==t){const n=t;t=null,r=a,e(e=>{const t=[...e||[]],r=t[t.length-1];return"assistant"===(null==r?void 0:r.role)&&(t[t.length-1]=A(A({},r),{},{content:n})),t})}n=null}};return e=>{t=e,null===n&&(n=requestAnimationFrame(o))}})(t),r=e.getReader(),o=new TextDecoder;let a="";const i={current:""},s={current:!1};let l=!1;try{for(;;){const{value:e,done:h}=await r.read();if(h)break;a+=o.decode(e,{stream:!0});const m=a.split(/\r?\n\r?\n/);a=m.pop()||"";for(const e of m){var c,u;const r=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);if(0===r.length)continue;const o=r.filter(e=>e.startsWith("data:")).map(e=>e.slice(5).trim());if(0===o.length)continue;const a=o.join("\n");if("[DONE]"===a)continue;let h;try{h=JSON.parse(a)}catch(e){continue}if(h){if(h.type){if("processing_start"===h.type||"processing_end"===h.type)continue;if("text_chunk"===h.type){var d;s.current||(s.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],F()]}return e}));const e=(null===(d=h.choices)||void 0===d||null===(d=d[0])||void 0===d||null===(d=d.delta)||void 0===d?void 0:d.content)||h.content;e&&(i.current+=e,n(i.current));continue}if("complete"===h.type){var p,f,g;l=!0;const e=null!==(p=null!==(f=h.Sources)&&void 0!==f?f:h.sources)&&void 0!==p?p:[],n=Array.isArray(e)?e.map(e=>{var t,n,r,o,a;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!==(o=null!==(a=e.source_name)&&void 0!==a?a:e.sourceName)&&void 0!==o?o:"",url:e.url}}).filter(e=>e.source_id||e.url):[],r=(null===(g=h.choices)||void 0===g||null===(g=g[0])||void 0===g||null===(g=g.delta)||void 0===g?void 0:g.content)||h.finalContent||i.current,o={};"boolean"==typeof h.conclusionDetected?o.conclusionDetected=h.conclusionDetected:"boolean"==typeof h.conclusion_detected&&(o.conclusionDetected=h.conclusion_detected);const a=A(A({},o),{},{prompts:h.prompts});B(t,r,a),n.length>0&&t(e=>{const t=[...e||[]],o=t[t.length-1];return"assistant"===(null==o?void 0:o.role)&&(t[t.length-1]=A(A({},o),{},{sources:n,content:r,isProcessing:!1})),t});continue}if("error"===h.type){t(e=>{const t=[...e||[]],n=t[t.length-1];return"assistant"===(null==n?void 0:n.role)&&(t[t.length-1]=A(A({},n),{},{content:(n.content||"")+"\n\nError: ".concat(h.error||"Unknown error occurred"),isProcessing:!1})),t});continue}const e=P(a);if(e&&e.type){console.log("🔍 Parsed stream event:",e.type,e),U(e,t,i,n,s);continue}}if("chat.completion.chunk"===h.object&&null!==(c=h.choices)&&void 0!==c&&null!==(c=c[0])&&void 0!==c&&null!==(c=c.delta)&&void 0!==c&&c.content)s.current||(s.current=!0,t(e=>{const t=e[e.length-1];if(!t||"assistant"!==t.role||!t.isProcessing){return[...e||[],F()]}return e})),i.current+=h.choices[0].delta.content,n(i.current);else if(null!==(u=h.choices)&&void 0!==u&&null!==(u=u[0])&&void 0!==u&&u.finish_reason&&null!==h.choices[0].finish_reason){l=!0;const e={prompts:h.prompts};B(t,i.current,e)}}}}}finally{r.releaseLock()}if(!l)throw new D(i.current?"Stream ended mid-response — partial content received":"Stream ended before any content was received")};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 o=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1}}),a=t.createMediaStreamSource(o),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]))*q;return t.buffer}(t.data);e(n)},a.connect(i),[i,t,o]}function G(e){e&&e.getTracks().forEach(e=>e.stop())}const q=32767;const H=.025,V=200,W=1e3,Y=300;function K(e,t){var n,r,o,a;const i=e.sampleRate,s=null!==(n=e.energyThreshold)&&void 0!==n?n:H,l=null!==(r=e.speechStartMs)&&void 0!==r?r:V,c=null!==(o=e.hangoverMs)&&void 0!==o?o:W,u=null!==(a=e.preRollMs)&&void 0!==a?a:Y;let d=!1,p=0,f=0,g=[],h=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?f=0:(f+=n,f>=c&&(d=!1,p=0,f=0,t.onSpeechEnd()));else{for(g.push({pcm:e,durationMs:n}),h+=n;h>u&&g.length>1;){var o;const e=g.shift();h-=null!==(o=null==e?void 0:e.durationMs)&&void 0!==o?o:0}if(r){if(p+=n,p>=l){var a;d=!0,f=0,null===(a=t.onSpeechStart)||void 0===a||a.call(t);for(const e of g)t.onVoiceFrame(e.pcm);g=[],h=0}}else p=0}},reset:()=>{d=!1,p=0,f=0,g=[],h=0},isSpeaking:()=>d}}const X=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(/^\/+/,"")):""},Q=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},ee=e=>{var t;if(!e)return 99;const n=String(e).toLowerCase();return null!==(t=J[n])&&void 0!==t?t:99},te="eshal_chat_session",ne="eshal_chat_session_messages";function re(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 oe=(e,t,n,r)=>{if(e&&t)try{const o=null==r?void 0:r.cap,a=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 A(A(A({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}:{})}):[]}(re(n,o,a));localStorage.setItem("".concat(ne,"_").concat(e,"_").concat(t),JSON.stringify(i))}catch(e){}},ae=(e,t)=>{if(e&&t)try{localStorage.removeItem("".concat(ne,"_").concat(e,"_").concat(t))}catch(e){}},ie=(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},se=e=>{try{const t=localStorage.getItem("".concat(te,"_").concat(e));return t?JSON.parse(t):null}catch(e){return null}},le=(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=ie(t,n);if(!r)return!0;const o=new Date(e.lastActivity).getTime(),a=Date.now()-o,i=a<r;return i||console.log("[Session] Session expired. Elapsed: ".concat(Math.floor(a/1e3),"s, Timeout: ").concat(Math.floor(r/1e3),"s")),i},ce=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(te,"_").concat(e),JSON.stringify(A({conversationId:t,lastActivity:r,createdAt:r,firstInteractionAt:null},n)))}catch(e){}},ue=e=>{try{const t=se(e);if(!t)return;const n=(new Date).toISOString();t.lastActivity=n,t.firstInteractionAt||(t.firstInteractionAt=n),localStorage.setItem("".concat(te,"_").concat(e),JSON.stringify(t))}catch(e){}},de=(e,t)=>{try{if(!e)return;if(!Array.isArray(t)||0===t.length)return void localStorage.removeItem("".concat(te,"_prompts_").concat(e));localStorage.setItem("".concat(te,"_prompts_").concat(e),JSON.stringify(t))}catch(e){}},pe=e=>{let{id:t,role:n,content:r,isProcessing:o=!1,metadata:a}=e;return{id:t,role:n,content:r,timestamp:new Date,isProcessing:o,metadata:a}},fe=(e,t)=>{const n=[...e.map(e=>A(A({},e),{},{metadata:e.metadata||{source:"sse"}})),...t];return Array.from(new Map(n.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()))},ge=e=>e&&e.length>0?e:[],he=e=>{let{welcomeMessage:t,quickQuestions:s=[],apiBaseUrl:l,apiKey:c,organizationId:u,secretKey:d,autoOpen:p,openDelay:f,darkMode:g,enableVoiceInteraction:h=!1,provideCitations:m=!0,onboardingQuestions:b=[],onboardingEnabled:y=!1,collectionPrompt:v,inactivityTimeoutValue:w,inactivityTimeoutUnit:S,messageLimits:E}=e;const k=n(()=>({cap:"number"==typeof(null==E?void 0:E.cap)&&E.cap>0?E.cap:200,trimBatch:"number"==typeof(null==E?void 0:E.trimBatch)&&E.trimBatch>0?E.trimBatch:50}),[null==E?void 0:E.cap,null==E?void 0:E.trimBatch]),[x,T]=r(p),[O,C]=r(!1),[I,N]=r(g),[_,R]=r(()=>{try{const e=se(u);if(void 0!==w&&e&&le(e,w,S))return[]}catch(e){}return t?[A(A({},pe({id:Date.now().toString(),role:"assistant",content:t})),{},{isWelcome:!0})]:[]}),[P,L]=r(""),[F,j]=r(!1),B=o(null),U=o(1),[q,H]=r(null),[V,W]=r(null),Y=o(null);a(()=>{Y.current=V},[V]);const[Z,Q]=r(null),J=o(null);a(()=>{J.current=Z},[Z]);const[he,me]=r(!1),[be,ye]=r(()=>{try{const e=se(u);if(e&&e.onboardingCompleted)return!0}catch(e){}return!1}),[ve,we]=r(null),[Se,Ee]=r({}),ke=o(!1),xe=o(!1),[Ae,Te]=r(!1),[Oe,Ce]=r(!1),[Ie,Ne]=r([]),[_e,Re]=r("idle"),[Pe,Le]=r(null),[De,Me]=r(!1),[Fe,je]=r(()=>{try{const e=se(u);if(void 0!==w&&e&&le(e,w,S))return e.conversationId}catch(e){}return"widget-session-".concat(Math.random().toString(36).slice(2,9))}),Be=o(null),Ue=o(null),ze=o(null),$e=o(null),Ge=o(null),qe=o(null),He=o(null),Ve=o(null),We=o(null),Ye=o(!1),Ke=o(!1);o(null);const Xe=o(null);o(null);const Ze=o(!1),Qe=o(null),Je=o(!1),et=o(!1),tt=o(null),nt=o(null),rt=o(null),ot=o(null),at=n(()=>{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(Fe)},[l,u,Fe]),it=i(()=>{const e="msg-".concat(U.current);return U.current+=1,e},[]);a(()=>{if(p&&f>0){const e=setTimeout(()=>T(!0),f);return()=>clearTimeout(e)}},[p,f]),a(()=>{let e=!1;return(async()=>{try{const{default:t}=await Promise.resolve().then(function(){return R1}),n=new t({cache:!0,geoFromBrowser:!0,onError:()=>{}}),r=await n.init();if(e)return;if(null!=r&&r.fingerprintId&&(rt.current=r.fingerprintId),null!=r&&r.geo||null!=r&&r.ip){const e=r.geo||{};ot.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(()=>{N(g)},[g]);const st=o(!1),lt=o(!1),ct=o(!1),ut=o({value:null,unit:null});a(()=>{if(!u||!Fe||void 0===w)return;const e=se(u);if(e&&le(e,w,S)){if(Fe!==e.conversationId)return void je(e.conversationId);if(!st.current){st.current=!0;const e=((e,t)=>{if(!e||!t)return[];try{const n=localStorage.getItem("".concat(ne,"_").concat(e,"_").concat(t));if(!n)return[];const r=JSON.parse(n);return Array.isArray(r)?r.map(e=>A(A({},e),{},{timestamp:e.timestamp?new Date(e.timestamp):new Date})):[]}catch(e){return[]}})(u,Fe);if(e.length>0){if(lt.current=!0,t){var n;const r=null===(n=e[0])||void 0===n?void 0:n.timestamp,o=r instanceof Date?r.getTime():r?new Date(r).getTime():Date.now(),a=A(A({},pe({id:"welcome-restored",role:"assistant",content:t})),{},{isWelcome:!0,timestamp:new Date(o-1)});R([a,...e])}else R(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(te,"_prompts_").concat(e));return t&&JSON.parse(t)||[]}catch(e){return[]}})(u);e.length>0&&R(t=>{const n=[...t];for(let t=n.length-1;t>=0;t-=1)if("assistant"===n[t].role){n[t]=A(A({},n[t]),{},{prompts:e});break}return n})}}}}else if(st.current||(st.current=!0),e&&Fe===e.conversationId){const e="widget-session-".concat(Math.random().toString(36).slice(2,9));console.warn("[Session] Rotating expired ID ".concat(Fe," -> ").concat(e)),ae(u,Fe),je(e)}else null!=e&&e.conversationId&&e.conversationId!==Fe&&ae(u,e.conversationId),e&&e.conversationId===Fe||ce(u,Fe,{settingsSnapshot:JSON.stringify({value:w,unit:null==S?void 0:S.toUpperCase()})})},[u,Fe,l,w,S]),a(()=>{if(u&&_&&0!==_.length)for(let e=_.length-1;e>=0;e-=1){const t=_[e];if("assistant"===(null==t?void 0:t.role)&&Array.isArray(t.prompts)&&t.prompts.length>0)return void de(u,t.prompts)}},[_,u]),a(()=>{Ae||F||_.length<=k.cap||R(e=>re(e,k.cap,k.trimBatch))},[_.length,Ae,F,k.cap,k.trimBatch]),a(()=>{u&&Fe&&(Ae||F||oe(u,Fe,fe(_,Ie),k))},[_,Ie,u,Fe,Ae,F,k]),a(()=>{if(!y||be)return;ge(b).length>0&&me(!0)},[y,be,b]),a(()=>{t&&!lt.current&&R(e=>{if(!e.length)return[A(A({},pe({id:Date.now().toString(),role:"assistant",content:t})),{},{isWelcome:!0})];const[n,...r]=e;return n.isWelcome?[A(A({},n),{},{content:t}),...r]:e})},[t]),i(e=>{R(t=>t.map(t=>t.id===e.id?A(A({},t),e.update(t)):t))},[]);const dt=i(function(e){if(!e)return;const t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).replaceMarker||null;R(n=>[...t?(n||[]).filter(e=>{var n;return(null==e||null===(n=e.metadata)||void 0===n?void 0:n.synthesizedKind)!==t}):n||[],pe({id:it(),role:"assistant",content:e,metadata:t?{synthesizedKind:t}:void 0})])},[it]),pt=i(async(e,t,n)=>{const r=e.trim();if(!r)return{success:!1,error:"Message cannot be empty"};if(xe.current)return{success:!1,error:"A message is already being sent"};if(xe.current=!0,t&&!["inquiry","complaint","technical"].includes((t||"").toLowerCase())||(J.current=r,Q(r)),!l)return xe.current=!1,R(e=>[...e||[],pe({id:it(),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 o=["inquiry","complaint","technical","userName","email","phone","fullname","mobileno"];let a="inquiry";if(t){const e=t.toLowerCase();"fullname"===e||"name"===e?a="userName":"email"===e?a="email":"phone"===e||"mobileno"===e?a="phone":o.includes(e)&&(a=e)}if("inquiry"===a||"complaint"===a||"technical"===a){const e=pe({id:it(),role:"user",content:r});R(t=>{const r=(t||[]).map(e=>{var t;return"assistant"===e.role&&null!==(t=e.prompts)&&void 0!==t&&t.length?A(A({},e),{},{prompts:void 0}):e});return n&&n.skipUserAppend?r:[...r,e]}),L(""),j(!0)}else L("");try{const e=A(A(A(A(A({message:r,type:a,conversationId:Fe,enable_citation:null==m||m,channel:"WIDGET"},rt.current?{fingerprintId:rt.current}:{}),ot.current?{visitor:ot.current}:{}),q&&(q.category||q.tags&&q.tags.length)?{filter:q}:{}),Y.current?{routing:Y.current}:{}),{},{messageHistory:_.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=[500,1500];if("userName"===a||"email"===a||"phone"===a){const t=(await M(e,l,u,d)).getReader(),n=new TextDecoder;for(;;){const{done:e,value:r}=await t.read();if(e)break;n.decode(r)}return{success:!0}}if("inquiry"===a||"complaint"===a||"technical"===a){let n;for(let r=0;r<=t.length;r+=1)try{const t=await M(e,l,u,d);return await z(t,R),ue(u),{success:!0}}catch(e){if(n=e,e instanceof D&&r<t.length){R(e=>(e||[]).filter(e=>!e.isProcessing));const n=t[r];console.warn("[chat] stream dropped (attempt ".concat(r+1,"); retrying in ").concat(n,"ms — ").concat(e.message)),await new Promise(e=>setTimeout(e,n));continue}throw e}throw n}return await M(e,l,u),ue(u),{success:!0}}catch(e){return console.error("Error sending message:",e),"inquiry"!==a&&"complaint"!==a&&"technical"!==a||(j(!1),R(e=>[...(e||[]).filter(e=>!e.isProcessing),pe({id:it(),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{j(!1),xe.current=!1}},[l,c,it,u,_,Fe,V,q,m]),ft=i(async e=>{const t=ge(b);if(0===t.length)return;const n=[...t].sort((e,t)=>ee(e.fieldType)-ee(t.fieldType));for(const t of n){var r;const n=t.fieldType||"question",o=(null!==(r=e[n])&&void 0!==r?r:"").trim();if(!o)continue;const a=await pt(o,n);if(null==a||!a.success){const e=pe({id:it(),role:"assistant",content:(null==a?void 0:a.error)||"Something went wrong. Please try again.",isProcessing:!1});return void R(t=>[...t,e])}}me(!1),ye(!0),(e=>{try{const t=se(e);if(!t)return;t.onboardingCompleted=!0,localStorage.setItem("".concat(te,"_").concat(e),JSON.stringify(t))}catch(e){}})(u),Ee(t=>A(A({},t),e)),ve&&!ke.current&&(ke.current=!0,setTimeout(()=>{L(ve),we(null)},500))},[b,pt,it,ve,u]),gt=i(async()=>{const e=P.trim();e&&await pt(e)},[P,pt]),ht=i(async()=>{await gt()},[gt]),mt=i(async e=>{const t=null==e?void 0:e.trim();t&&await pt(t)},[pt]),bt=i(async(e,t,n)=>{if(R(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){Y.current=r,W(r);const e=J.current;J.current=null,Q(null),e&&e.trim()&&setTimeout(()=>{pt(e,"inquiry",{skipUserAppend:!0}).catch(e=>console.warn("[routing-clarification] re-send failed:",e))},0)}return}if("connect_agent"===n){const e=pe({id:it(),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."});R(t=>[...t,e])}else if("decline"===n){const e=pe({id:it(),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?"});R(t=>[...t,e])}},[it,pt,Z]);i(()=>{Ve.current&&(Ne(e=>e.map(e=>e.id===Ve.current?A(A({},e),{},{isProcessing:!1}):e)),Ve.current=null)},[]);const yt=i(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(Je.current=!0,!e||"string"==typeof e&&!e.trim())return void(t&&Ve.current&&(Ne(e=>e.map(e=>e.id===Ve.current?A(A({},e),{},{isProcessing:!1}):e)),Ve.current=null));const n=X(e);Ne(e=>{const r=e.length;let o=[...e];if(Ve.current){if(o.some(e=>e.id===Ve.current))o=o.map(e=>{if(e.id!==Ve.current)return e;const r=X("".concat(e.content||"").concat(n));return A(A({},e),{},{content:r,isProcessing:!t,metadata:A(A({},e.metadata),{},{transcriptionType:"input"})})});else{console.error("[BIDI] appendUserTranscription: ERROR - user message not found!",{expectedId:Ve.current,existingIds:o.map(e=>e.id)});const e="bidi-input-".concat(Date.now());Ve.current=e;const r=pe({id:e,role:"user",content:n,isProcessing:!t,metadata:{source:"bidi",transcriptionType:"input"}});o=[...o,r],console.log("[BIDI] appendUserTranscription: recreated lost user message",{messageId:e})}}else{const r="bidi-input-".concat(Date.now()),a=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(a);const l=pe({id:r,role:"user",content:n,isProcessing:!t,timestamp:s,metadata:{source:"bidi",transcriptionType:"input"}});o.some(e=>e.id===r)?(console.warn("[BIDI] appendUserTranscription: message already exists, updating instead",{messageId:r}),Ve.current=r,o=o.map(e=>e.id===r?A(A({},e),{},{content:"".concat(e.content||"").concat(n),isProcessing:!t}):e)):(o=[...o,l],Ve.current=r)}return o.length<r?(console.error("[BIDI] appendUserTranscription: CRITICAL ERROR - losing messages!",{prevLength:r,resultLength:o.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: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)}})}),e):o}),t&&(Ve.current=null,j(!0))},[]),vt=i(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(j(!1),console.log("[BIDI] appendAssistantContent called",{text:null==e?void 0:e.substring(0,50),finished:t,currentAssistantId:We.current,currentInputId:Ve.current}),!e||"string"==typeof e&&!e.trim())return console.log("[BIDI] appendAssistantContent: skipping empty text"),void(t&&We.current&&(Ne(e=>e.map(e=>e.id!==We.current?e:A(A({},e),{},{isProcessing:!1}))),We.current=null,Xe.current=null));const n="".concat(We.current||"new","-").concat(e.substring(0,100),"-").concat(t);if(Ze.current&&Qe.current===n)return;Ze.current=!0,Qe.current=n;const r=Ve.current;if(Ne(n=>{const o=n.length;let a=[...n];if(console.log("[BIDI] appendAssistantContent: starting update",{prevLength:o,prevMessageIds:n.map(e=>e.id),inputMessageIdToFinalize:r,currentAssistantId:We.current,textLength:e.length}),r){a.some(e=>e.id===r)?a=a.map(e=>e.id===r?A(A({},e),{},{isProcessing:!1}):e):console.warn("[BIDI] appendAssistantContent: input message not found for finalization",{inputMessageId:r,existingIds:a.map(e=>e.id)})}if(We.current){if(a.some(e=>e.id===We.current))a=a.map(n=>{var r;if(n.id!==We.current)return n;const o="".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:o.length,textLength:e.length}),A(A({},n),{},{content:o,isProcessing:!t},Array.isArray(nt.current)&&nt.current.length>0?{sources:nt.current}:{})}),Array.isArray(nt.current)&&nt.current.length>0&&(nt.current=null);else{console.error("[BIDI] appendAssistantContent: ERROR - assistant message not found!",{expectedId:We.current,existingIds:a.map(e=>e.id)});const n="bidi-assistant-".concat(Date.now());We.current=n;const r=pe({id:n,role:"assistant",content:e,isProcessing:!t,metadata:{source:"bidi"}});Array.isArray(nt.current)&&nt.current.length>0&&(r.sources=nt.current,nt.current=null),a=[...a,r],console.log("[BIDI] appendAssistantContent: recreated lost assistant message",{messageId:n})}}else{const n="bidi-assistant-".concat(Date.now()),o=Date.now(),i=r?new Date(o):new Date(o+1e3),s=pe({id:n,role:"assistant",content:e,isProcessing:!t,timestamp:i,metadata:{source:"bidi"}});Array.isArray(nt.current)&&nt.current.length>0&&(s.sources=nt.current,nt.current=null);a.some(e=>e.id===n)?(console.error("[BIDI] appendAssistantContent: ERROR - message ID collision!",{messageId:n,existingIds:a.map(e=>e.id)}),a=a.map(r=>r.id===n?A(A({},r),{},{content:"".concat(r.content||"").concat(e),isProcessing:!t},Array.isArray(nt.current)&&nt.current.length>0?{sources:nt.current}:{}):r),Array.isArray(nt.current)&&nt.current.length>0&&(nt.current=null),We.current=n):(a=[...a,s],We.current=n)}return console.log("[BIDI] appendAssistantContent: atomic state update complete",{prevLength:o,newLength:a.length,finished:t,messageIds:a.map(e=>e.id),messageRoles:a.map(e=>e.role)}),a.length<o?(console.error("[BIDI] appendAssistantContent: CRITICAL ERROR - losing messages!",{prevLength:o,resultLength:a.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: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)}})}),n):a}),r&&(Ve.current=null),t)console.log("[BIDI] appendAssistantContent: finalizing message",{messageId:We.current}),We.current=null,Xe.current=null;else{const e=updateKey;Promise.resolve().then(()=>{Xe.current===e&&(Xe.current=null)})}},[]),wt=i(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 o,a;null!==(o=e.inlineData)&&void 0!==o&&o.data&&null!==(a=e.inlineData.mimeType)&&void 0!==a&&a.startsWith("audio/pcm")&&(console.log("[BIDI] handleContentParts: sending audio data to player"),Ue.current?Ue.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,o=new Uint8Array(r);for(let e=0;e<r;e+=1)o[e]=n.charCodeAt(e);return o.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}),vt(r,t))},[vt]),St=i(()=>{j(!1),console.log("[BIDI] handleTurnComplete called",{currentAssistantId:We.current,currentInputId:Ve.current}),Ne(e=>{const t=e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)&&e.isProcessing?A(A({},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}),We.current=null,Ve.current=null,et.current=!1,nt.current=null},[]),Et=i(()=>{j(!1),Ue.current&&Ue.current.port.postMessage({command:"endOfAudio"}),We.current=null,Ve.current=null,nt.current=null,Ne(e=>e.map(e=>{var t;return"bidi"===(null===(t=e.metadata)||void 0===t?void 0:t.source)?A(A({},e),{},{isProcessing:!1,metadata:A(A({},e.metadata),{},{interrupted:!0})}):e}))},[]),kt=i(()=>{var e,t,n,r,o;Ce(!1),j(!1),Ke.current=!1,Re("idle"),Le(null),Je.current=!1,nt.current=null,Be.current&&Be.current.readyState===WebSocket.OPEN&&Be.current.close(),Be.current=null,null===(e=Ue.current)||void 0===e||e.disconnect(),null===(t=ze.current)||void 0===t||t.close(),Ue.current=null,ze.current=null,null===(n=$e.current)||void 0===n||n.disconnect(),null===(r=Ge.current)||void 0===r||r.close(),$e.current=null,Ge.current=null,G(qe.current),qe.current=null,null===(o=He.current)||void 0===o||o.reset(),He.current=null,Ye.current=!1},[]),xt=i(e=>{var t,n,r,o,a;if(console.log("[BIDI] handleBidiEvent called",{event:e,isVoiceSessionActive:Ke.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=tt.current)||void 0===s||s.call(tt),Me(!0));if("boolean"==typeof i&&i)return kt(),void Ne(e=>{const t=[...e];for(let e=t.length-1;e>=0;e--)if("assistant"===t[e].role){t[e]=A(A({},t[e]),{},{conclusionDetected:!0});break}return t});if(e.interrupted)return console.log("[BIDI] handleBidiEvent: processing interrupted"),void Et();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?(ue(u),yt(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,o,a,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!==(o=e.source_id)&&void 0!==o?o:e.sourceid)&&void 0!==r?r:e.sourceId,source_name:null!==(a=null!==(i=e.source_name)&&void 0!==i?i:e.sourceName)&&void 0!==a?a:"",url:e.url}}).filter(e=>e.source_id||e.url);if(0===e.length)return;Ne(t=>{const n=[...t];let r=!1;for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=A(A({},n[t]),{},{sources:e}),r=!0;break}return r||(nt.current=e),n})}var c,d;if(!Je.current&&(null!==(c=e.outputTranscription)&&void 0!==c&&c.text||null!==(d=e.content)&&void 0!==d&&d.parts))return void(e.turnComplete&&St());if(null!==(o=e.outputTranscription)&&void 0!==o&&o.text&&(et.current=!0,vt(e.outputTranscription.text,Boolean(e.outputTranscription.finished))),null!==(a=e.content)&&void 0!==a&&a.parts){var p;const t=(null===(p=e.content)||void 0===p?void 0:p.finished)||e.finished||!1;wt(e.content.parts,t,et.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}),Ne(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role){n[t]=A(A({},n[t]),{},{prompts:e.prompts});break}return n});try{de(u,e.prompts)}catch(e){}}e.turnComplete?St():e.interrupted||e.inputTranscription||e.outputTranscription||e.content||e.prompts||console.warn("[BIDI] handleBidiEvent: event had no recognized fields",e)},[vt,yt,wt,Et,St,kt]),At=i(e=>{if(!Ke.current)return;const t=He.current;if(t)return void t.process(e);const n=Be.current;n&&n.readyState===WebSocket.OPEN&&n.send(e)},[]),Tt=i(async()=>{if(!Ye.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]}();Ue.current=e,ze.current=t,await t.resume();const n=e=>{const t=Be.current;t&&t.readyState===WebSocket.OPEN&&t.send(e)};He.current=K({sampleRate:16e3},{onSpeechStart:()=>{var e;null===(e=Ue.current)||void 0===e||e.port.postMessage({command:"endOfAudio"});const t=Be.current;t&&t.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"interrupt"}))},onVoiceFrame:n,onSpeechEnd:()=>{const e=Be.current;e&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"audio_end"}))}});const[r,o,a]=await $(At);$e.current=r,Ge.current=o,qe.current=a,await o.resume(),Ye.current=!0}catch(e){throw console.error("Failed to initialize audio pipeline",e),e}},[At]),Ot=i(()=>{if("undefined"!=typeof window&&at&&(!Be.current||Be.current.readyState!==WebSocket.OPEN)){Re("connecting"),Le(null);try{const e=new WebSocket(at);Be.current=e,e.onopen=()=>{Re("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 o=JSON.parse(e.data);console.log("[BIDI] WebSocket message parsed",{hasTurnComplete:!!o.turnComplete,hasInterrupted:!!o.interrupted,hasInputTranscription:!!o.inputTranscription,hasOutputTranscription:!!o.outputTranscription,hasContentParts:!(null===(n=o.content)||void 0===n||!n.parts),payload:o}),xt(o)}catch(t){console.error("[BIDI] Failed to parse WebSocket event",{error:t,data:e.data})}},e.onerror=()=>{Re("error"),Le("Voice session connection error"),j(!1)},e.onclose=()=>{Be.current=null,Re("idle"),j(!1),Ke.current&&setTimeout(()=>{Ot()},5e3)}}catch(e){console.error("Failed to open voice websocket",e),Re("error"),Le(e instanceof Error?e.message:"Unable to start voice session")}}},[xt,at]),Ct=i(async()=>{if(h&&u){Le(null),Re(e=>"connected"===e?e:"connecting"),Ce(!0),Ke.current=!0,Me(!1),Je.current=!1,Ne(e=>{if(e.length>0||_.length>0)return e;if(!t||""===t.trim())return[];return[pe({id:"bidi-welcome-".concat(Date.now()),role:"assistant",content:t,metadata:{source:"bidi"}})]}),Ot();try{await Tt()}catch(e){console.error("Failed to start audio pipeline",e),Le(e instanceof Error?e.message:"Unable to access microphone"),Re("error")}}},[h,u,t,Ot,Tt,_]),It=i(()=>{Oe?kt():"connecting"!==_e&&Ct()},[Oe,Ct,kt,_e]),Nt=i(e=>{const t=e.trim();if(!t)return;Je.current=!0;const n=Be.current;if(!n||n.readyState!==WebSocket.OPEN)return void Le("Voice session is not connected yet");n.send(JSON.stringify({type:"text",text:t})),ue(u),j(!0);const r=pe({id:"bidi-user-".concat(Date.now()),role:"user",content:t,metadata:{source:"bidi"}});Ne(e=>[...e,r]),L("")},[]);a(()=>{Ke.current=Oe},[Oe]),a(()=>()=>{var e,t,n,r;Be.current&&Be.current.readyState===WebSocket.OPEN&&Be.current.close(),null===(e=Ue.current)||void 0===e||e.disconnect(),null===(t=ze.current)||void 0===t||t.close(),null===(n=$e.current)||void 0===n||n.disconnect(),null===(r=Ge.current)||void 0===r||r.close(),G(qe.current),qe.current=null,Ye.current=!1},[]);const _t=i(()=>{(e=>{try{const t=se(e);localStorage.removeItem("".concat(te,"_").concat(e)),null!=t&&t.conversationId&&ae(e,t.conversationId)}catch(e){}})(u),de(u,[]),H(null),W(null),Q(null),Y.current=null,J.current=null,R([]),Ne([]),ae(u,Fe),me(!1),ye(!1),Ee({}),we(null),ke.current=!1,Je.current=!1,st.current=!1,lt.current=!1;const e="widget-session-".concat(Math.random().toString(36).slice(2,9));if(ce(u,e,{settingsSnapshot:JSON.stringify({value:w,unit:null==S?void 0:S.toUpperCase()})}),je(e),t&&""!==t.trim()&&R([A(A({},pe({id:Date.now().toString(),role:"assistant",content:t})),{},{isWelcome:!0})]),y){ge(b).length>0&&me(!0)}},[u,Fe,t,y,b,w,S]),Rt=o(_t);a(()=>{Rt.current=_t},[_t]),a(()=>{ct.current=!1,ut.current={value:null,unit:null}},[u]),a(()=>{if(!u||!w)return;const e=ie(w,S);if(!e)return;const t=ut.current,n=ct.current&&(t.value!==w||t.unit!==S);if(ct.current=!0,ut.current={value:w,unit:S},n)return console.warn("[Session] Inactivity timeout config changed — resetting conversation."),void Rt.current();let r=null;const o=()=>{const t=se(u);if(!t)return;if(!t.firstInteractionAt)return void(r=setTimeout(o,e));const n=new Date(t.lastActivity).getTime(),a=Date.now()-n,i=e-a;if(i<=0)return console.warn("[Session] Inactivity timeout reached! Resetting conversation immediately."),void Rt.current();r=setTimeout(o,i)};return o(),()=>{r&&clearTimeout(r)}},[u,w,S,Fe]);const Pt=n(()=>s,[s]),Lt=n(()=>fe(_,Ie),[Ie,_]);a(()=>{Oe&&console.log("[BIDI] bidiMessages state changed",{count:Ie.length,messages:Ie.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)}})})},[Ie,Oe]);const Dt=i((e,t)=>{R(n=>n.map(n=>"assistant"===n.role&&n.content===e?A(A({},n),{},{feedback:t}):n))},[]);return{conversationId:Fe,isOpen:x,isMinimized:O,isDark:I,messages:Lt,inputValue:P,isLoading:F,isConversationLoading:Ae,widgetRef:B,quickQuestions:Pt,isVoiceSessionActive:Oe,voiceStatus:_e,voiceError:Pe,voiceConclusionForCsat:De,onboardingQuestions:b,onboardingActive:he,onboardingCompleted:be,handleOnboardingFormSubmit:ft,widgetFilter:q,setWidgetFilter:H,addAssistantMessage:dt,setInputValue:L,handleSend:ht,handleQuickQuestion:mt,sendMessage:pt,toggleChat:()=>{T(e=>!e),C(!1)},toggleTheme:()=>{N(e=>!e)},toggleMinimize:()=>{C(e=>!e)},closeChat:()=>{T(!1)},handleDecision:bt,handleVoiceToggle:It,sendBidiTextMessage:Nt,resetConversation:_t,updateMessageFeedback:Dt}},me=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim(),be=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ye=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
  *
@@ -8347,20 +8347,33 @@
8347
8347
  // Handle text_chunk events
8348
8348
  if (parsed.type === 'text_chunk') {
8349
8349
  var _parsed$choices;
8350
+ // ALWAYS create the skeleton on the first text_chunk, even when it
8351
+ // carries no content (a role-only "skeleton" chunk — delta.role
8352
+ // without delta.content — is the backend's "an assistant turn is
8353
+ // starting" signal used by the input/source-clarification short-
8354
+ // circuits in chat_utils.py). Without this, a clarification turn
8355
+ // that emits [text_chunk role-only] -> [complete content+
8356
+ // finalContent] never created the assistant bubble (this branch
8357
+ // skipped on empty content; the COMPLETE branch's updateFinalMessage
8358
+ // requires lastMessage.role === 'assistant' to render — see
8359
+ // updateFinalMessage line ~189) → the follow-up question was
8360
+ // silently dropped, even though the wire carried everything
8361
+ // correctly. Mirrors handleStreamEvent (line ~257) and packages/
8362
+ // frontend ChatService.ts (line ~213) which both create the
8363
+ // skeleton unconditionally on the first text_chunk.
8364
+ if (!hasReceivedFirstChunk.current) {
8365
+ hasReceivedFirstChunk.current = true;
8366
+ setMessages(prev => {
8367
+ const lastMessage = prev[prev.length - 1];
8368
+ if (!lastMessage || lastMessage.role !== 'assistant' || !lastMessage.isProcessing) {
8369
+ const skeletonMessage = createSkeletonMessage();
8370
+ return [...(prev || []), skeletonMessage];
8371
+ }
8372
+ return prev;
8373
+ });
8374
+ }
8350
8375
  const content = ((_parsed$choices = parsed.choices) === null || _parsed$choices === void 0 || (_parsed$choices = _parsed$choices[0]) === null || _parsed$choices === void 0 || (_parsed$choices = _parsed$choices.delta) === null || _parsed$choices === void 0 ? void 0 : _parsed$choices.content) || parsed.content;
8351
8376
  if (content) {
8352
- // Create skeleton on first chunk if not already created
8353
- if (!hasReceivedFirstChunk.current) {
8354
- hasReceivedFirstChunk.current = true;
8355
- setMessages(prev => {
8356
- const lastMessage = prev[prev.length - 1];
8357
- if (!lastMessage || lastMessage.role !== 'assistant' || !lastMessage.isProcessing) {
8358
- const skeletonMessage = createSkeletonMessage();
8359
- return [...(prev || []), skeletonMessage];
8360
- }
8361
- return prev;
8362
- });
8363
- }
8364
8377
  accumulatedText.current += content;
8365
8378
  updateMessage(accumulatedText.current);
8366
8379
  }