ai12z 3.17.2 → 3.17.4

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.
@@ -0,0 +1 @@
1
+ import{E as t,t as i,p as e,H as s,e as o,f as n,h as a,d as r}from"./p-rVmRQ8bG.js";import{a as l,l as h}from"./p-H6rMkkSS.js";import{s as d,p as c}from"./p-BJOnT4k4.js";import{L as u,a as v}from"./p-DC_B95kh.js";import{g as p,d as g,a as m,b as f,c as b,f as y,s as w,H as x,u as S,e as C,h as A,i as E,j as k,k as T}from"./p-djQQf6su.js";import{e as I}from"./p-CNxI_jB-.js";import{i as z,g as N,a as L,p as O,r as D,c as R}from"./p-CC6xbinS.js";import{r as B}from"./p-M51H23z5.js";import{c as M}from"./p-CztWNvRK.js";import{w as _,h as $}from"./p-D338smYm.js";import{D as P}from"./p-CsY3PAR1.js";import{f as j,e as U,s as G,p as H}from"./p-CTvP5Cqt.js";import{d as V,s as F}from"./p-dG64_Rr_.js";import{i as q,s as J,b as Z}from"./p-D1NOmiJo.js";import{b as K}from"./p-DvxYmlU_.js";import{d as Y}from"./p-SoJiujnW.js";import{d as W}from"./p-ClSkLu41.js";import{d as Q}from"./p-DmCL0aBr.js";import{d as X}from"./p-kJpnWRAF.js";import{d as tt}from"./p-BRczakta.js";import{d as it}from"./p-BswGpAXe.js";import{d as et}from"./p-nxQB8VYC.js";import{d as st}from"./p-BZbWeuCl.js";import{d as ot}from"./p-C0ycOUZ8.js";import{d as nt}from"./p-c6Z5KXDQ.js";const at=t.DATA_MODE||"prod";class rt extends Error{constructor(t="Live agent session authentication has expired"){super(t),this.name="LiveAgentAuthExpiredError"}}const lt=new class{constructor(){this.events=new Map}on(t,i){this.events.has(t)||this.events.set(t,new Set),this.events.get(t).add(i)}off(t,i){var e;null===(e=this.events.get(t))||void 0===e||e.delete(i)}emit(t,i){var e;null===(e=this.events.get(t))||void 0===e||e.forEach((t=>t(i)))}},ht=new u("SalesforceLiveAgentProvider",{logLevel:v.Info,remoteLoggingUrl:""});class dt{constructor(){this.configSettings=null,this.sessionContext=null,this.endpointSSE="",this.checkAgentAvailability=async t=>{var i,e,s;this.availabilityAbort=new AbortController;const{signal:o}=this.availabilityAbort,n=Date.now();for(;Date.now()-n<2e4;){if(o.aborted)return!1;const n=await fetch(`${null===(i=this.configSettings)||void 0===i?void 0:i.instanceUrl}/iamessage/api/v2/conversation/${t}/entries`,{method:"GET",signal:o,headers:{"Content-Type":"application/json",Authorization:`Bearer ${null===(e=this.sessionContext)||void 0===e?void 0:e.accessToken}`}});if(!n.ok)return ht.warn(`Agent availability check failed: ${n.status} ${n.statusText}`),lt.emit("AGENT_UNAVAILABLE",{reason:"request_error"}),!1;const a=await n.json();ht.debug("Agent availability check result:",a);const r=null!==(s=null==a?void 0:a.conversationEntries)&&void 0!==s?s:[],l=r.find((t=>"RoutingResult"===t.entryType));if(l){let t=l.entryPayload;if("string"==typeof t)try{t=JSON.parse(t)}catch(t){ht.warn("Failed to parse RoutingResult entryPayload")}const i=null==t?void 0:t.failureReason;return i?(ht.warn("Routing failed with reason:",i),lt.emit("AGENT_UNAVAILABLE",{reason:i}),!1):(ht.debug("Agent routed successfully"),!0)}ht.debug(`No RoutingResult yet (entries: ${r.length}), retrying in 1500ms…`),await new Promise(((t,i)=>{const e=setTimeout(t,1500);o.addEventListener("abort",(()=>{clearTimeout(e),i()}),{once:!0})})).catch((()=>null))}return ht.warn("Timed out waiting for MIAW routing result"),lt.emit("AGENT_UNAVAILABLE",{reason:"timeout"}),!1},this.configSettings=null,this.sessionContext=null,this.endpointSSE=p(at)}async authenticate(){var t,i,e;const s=await fetch(`${null===(t=this.configSettings)||void 0===t?void 0:t.instanceUrl}/iamessage/api/v2/authorization/unauthenticated/access-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({orgId:null===(i=this.configSettings)||void 0===i?void 0:i.orgId,esDeveloperName:null===(e=this.configSettings)||void 0===e?void 0:e.messagingChannelId,capabilitiesVersion:"1",platform:"Web",context:{appName:"DemoMessagingClient",clientVersion:"1.0.0"}})});if(!s.ok)throw new Error(`Failed to authenticate with Salesforce MIAW: [error]: ${s.status} ${s.statusText}`);const o=await s.json();this.sessionContext||(this.sessionContext={}),this.sessionContext.accessToken=o.accessToken,this.sessionContext.sessionId=o.lastEventId}async startSession(){var t,i,e,s,o,n,a,r,l,h,d,c;const u={};if(null===(i=null===(t=this.sessionContext)||void 0===t?void 0:t.extraPrechatFormDetails)||void 0===i?void 0:i.length)for(const t of this.sessionContext.extraPrechatFormDetails)(null==t?void 0:t.label)&&"string"==typeof t.value&&""!==t.value.trim()&&(u[t.label]=t.value);const v=crypto.randomUUID().toLowerCase(),p=await fetch(`${null===(e=this.configSettings)||void 0===e?void 0:e.instanceUrl}/iamessage/api/v2/conversation`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${null===(s=this.sessionContext)||void 0===s?void 0:s.accessToken}`},body:JSON.stringify({conversationId:v,esDeveloperName:null===(o=this.configSettings)||void 0===o?void 0:o.messagingChannelId,routingAttributes:Object.assign({recordId:null===(n=this.sessionContext)||void 0===n?void 0:n.conversationId},u)})});if(!p.ok)throw new Error(`Conversation start failed: ${p.status} ${p.statusText}`);if(p.ok){this.sessionContext.conversationId=v,lt.emit("liveAgentReady",void 0),lt.emit("AGENT_SESSION_INFO",{sessionId:this.sessionContext.accessToken,conversationId:this.sessionContext.conversationId});let t="";if(null===(r=null===(a=this.sessionContext)||void 0===a?void 0:a.extraPrechatFormDetails)||void 0===r?void 0:r.length){const i=this.sessionContext.extraPrechatFormDetails.filter((t=>(null==t?void 0:t.label)&&"string"==typeof t.value&&""!==t.value.trim()&&!1!==t.displayToAgent)).map((t=>`${t.label}: ${t.value}`));i.length>0&&(t+=`Pre-chat details:\n${i.join("\n")}\n\n`)}(null===(l=this.sessionContext)||void 0===l?void 0:l.initialMessages)&&(null===(h=this.sessionContext)||void 0===h?void 0:h.initialMessages.length)>0&&(null===(d=this.sessionContext.initialMessages[0])||void 0===d||d.messages.forEach((i=>{(null==i?void 0:i.text)&&(i.text=i.text.replace(/<\/?p>/g,""),t+=(null==i?void 0:i.isUser)?`User: ${i.text}\n`:`Bot: ${i.text}\n`)}))),t&&this.sendMessage({isNewSession:!0,sessionId:(null===(c=this.sessionContext)||void 0===c?void 0:c.sessionId)||"",message:t}),await this.checkAgentAvailability(this.sessionContext.conversationId||"")?(ht.debug("Agent is available, starting to listen to messages"),this.listenToMessages()):ht.warn("No agent assigned — skipping SSE listener setup")}}async initialize(t){var i,e,s;if(ht.debug("Initializing Salesforce Live Agent Provider"),this.configSettings||(this.configSettings=(null==t?void 0:t.config)||this.configSettings),!(null===(i=this.configSettings)||void 0===i?void 0:i.instanceUrl)||!(null===(e=this.configSettings)||void 0===e?void 0:e.orgId)||!(null===(s=this.configSettings)||void 0===s?void 0:s.messagingChannelId))throw new Error("Missing required configuration settings for Salesforce Live Agent Provider");this.sessionContext||(this.sessionContext={accessToken:"",lastMessageReadTime:0,sessionId:"",initialMessages:(null==t?void 0:t.messageHistory)||[],isActive:!1,conversationId:(null==t?void 0:t.conversationId)||crypto.randomUUID().toLowerCase(),userId:(null==t?void 0:t.userId)||"",extraPrechatFormDetails:(null==t?void 0:t.extraPrechatFormDetails)||[]});try{await this.authenticate(),await this.startSession()}catch(t){throw ht.error("Error initializing Salesforce Live Agent Provider:",t),t}}parseMessageEntries(t){return t.filter((t=>{var i,e,s,o;return"Message"===t.entryType&&(null===(s=null===(e=null===(i=t.entryPayload)||void 0===i?void 0:i.abstractMessage)||void 0===e?void 0:e.staticContent)||void 0===s?void 0:s.text)&&"EndUser"!=(null===(o=t.sender)||void 0===o?void 0:o.role)})).map((t=>({id:t.entryPayload.abstractMessage.id,content:t.entryPayload.abstractMessage.staticContent.text,sender:{role:this.mapSenderRole(t.sender.role),displayName:t.senderDisplayName||"Unknown"},timestamp:t.clientTimestamp})))}handleParticipantChange(t){try{if(ht.debug("Participant change event received:",t.data),!t.data)return;const i=JSON.parse(t.data),e=JSON.parse(i.conversationEntry.entryPayload).entries;let s=[];e.forEach((t=>{var i,e;const o=crypto.randomUUID();"add"===t.operation&&"agent"===t.participant.role.toLowerCase()&&s.push({id:o,isUser:!1,conversationId:o,type:"system",text:`${t.displayName} has joined the chat`,timestamp:new Date,sender:{role:"agent",displayName:null!==(i=null==t?void 0:t.displayName)&&void 0!==i?i:"System"}}),"remove"===t.operation&&"agent"===t.participant.role.toLowerCase()&&s.push({id:o,type:"system",text:`${t.displayName} has left the chat`,conversationId:o,isUser:!1,timestamp:new Date,sender:{role:"agent",displayName:null!==(e=null==t?void 0:t.displayName)&&void 0!==e?e:"System"}})})),(null==s?void 0:s.length)>0&&lt.emit("AGENT_EVENT",s)}catch(t){ht.error("Error handling participant change event:",t)}}mapEntriesToMessages(t){return t.map((t=>({id:t.entryPayload.abstractMessage.id,text:t.entryPayload.abstractMessage.staticContent.text,sender:{role:this.mapSenderRole(t.sender.role),displayName:t.senderDisplayName||"Unknown"},type:"endUser"===t.sender.role?"user":"ai",timestamp:new Date(t.timestamp),isUser:!1,conversationId:t.entryPayload.abstractMessage.id})))}handleParticipantMessage(t){var i,e;try{if(!t.data)return;const s=JSON.parse(t.data);if("EndUser"===(null===(e=null===(i=null==s?void 0:s.conversationEntry)||void 0===i?void 0:i.sender)||void 0===e?void 0:e.role))return void ht.debug("Ignoring message from EndUser role");const o=JSON.parse(s.conversationEntry.entryPayload);s.conversationEntry.entryPayload=o;const n=this.mapEntriesToMessages([s.conversationEntry]);(null==n?void 0:n.length)>0&&lt.emit("AGENT_MESSAGE",n)}catch(t){ht.error("Error handling participant message event:",t)}}mapSenderRole(t){const i=t.toLowerCase();return"chatbot"===i?"agent":"enduser"===i?"endUser":"unknown"}handleSessionStatusChange(t){var i;try{if(!t.data)return;const e=JSON.parse(t.data),s=JSON.parse(e.conversationEntry.entryPayload);ht.debug("Session status changed:",null==s?void 0:s.sessionStatus),"Active"===(null==s?void 0:s.sessionStatus)?lt.emit("AGENT_SESSION_CREATED",!0):"Ended"===(null==s?void 0:s.sessionStatus)&&(lt.emit("CONVERSATION_CLOSED",!0),null===(i=this.eventSource)||void 0===i||i.close())}catch(t){ht.error("Error handling session status change event:",t)}}listenToMessages(){var t,i,e,s;ht.debug("Listening to messages from Salesforce Live Agent"),null===(t=this.eventSource)||void 0===t||t.close();const o=new EventSource(`${this.endpointSSE}/bot/liveagent/sse?token=${null===(i=this.sessionContext)||void 0===i?void 0:i.accessToken}&org_id=${null===(e=this.configSettings)||void 0===e?void 0:e.orgId}&sse_url=${null===(s=this.configSettings)||void 0===s?void 0:s.instanceUrl}`,{withCredentials:!0});if(!o)throw ht.error("Failed to create EventSource"),new Error("Failed to create EventSource");this.eventSource=o,o.onerror=t=>{const i=null==t?void 0:t.data;ht.error("string"==typeof i&&i?`❌ SSE server error frame: ${i}`:"❌ SSE Error: Connection lost or error occurred"),lt.emit("AGENT_ERROR",{reason:"string"==typeof i&&i?i:"transport"}),o.close()},o.onopen=()=>{ht.debug("✅ SSE Connection Established")};const n=t=>{var i,e;try{const s=JSON.parse(t.data);switch(ht.debug("📡 Message Received on entrytype:",null===(i=null==s?void 0:s.conversationEntry)||void 0===i?void 0:i.entryType," --- ",t.data),null===(e=null==s?void 0:s.conversationEntry)||void 0===e?void 0:e.entryType){case"RoutingResult":case"RoutingWorkResult":ht.debug("Conversation Routing Result:",t.data),lt.emit("FINDING_AGENT",t.data);break;case"ParticipantChanged":ht.debug("Conversation ParticipantChanged event received:",null==t?void 0:t.data),this.handleParticipantChange(t);break;case"Message":this.handleParticipantMessage(t);break;case"CloseConversation":lt.emit("CONVERSATION_CLOSED",!0),o.close();break;case"DeliveryAcknowledgement":case"ReadAcknowledgement":ht.debug("Conversation event received:",null==t?void 0:t.data);break;case"TypingStartedIndicator":lt.emit("TYPING_STARTED",!0);break;case"TypingStoppedIndicator":ht.debug("Typing indicator received:",t.data),lt.emit("TYPING_STOPPED",!0);break;case"StreamingToken":ht.debug("Streaming token received",t.data);break;case"ProgressIndicator":ht.debug("Progress indicator received",t.data);break;case"SessionStatusChanged":ht.debug("Session status changed event received",t.data),this.handleSessionStatusChange(t)}}catch(t){return void ht.error("Failed to parse event data:",t)}};Object.values({Message:"CONVERSATION_MESSAGE",RoutingResult:"CONVERSATION_ROUTING_RESULT",RoutingWorkResult:"CONVERSATION_ROUTING_WORK_RESULT",ParticipantChanged:"CONVERSATION_PARTICIPANT_CHANGED",TypingStartedIndicator:"CONVERSATION_TYPING_STARTED_INDICATOR",TypingStoppedIndicator:"CONVERSATION_TYPING_STOPPED_INDICATOR",DeliveryAcknowledgement:"CONVERSATION_DELIVERY_ACKNOWLEDGEMENT",ReadAcknowledgement:"CONVERSATION_READ_ACKNOWLEDGEMENT",CloseConversation:"CONVERSATION_CLOSE_CONVERSATION",StreamingToken:"CONVERSATION_STREAMING_TOKEN",ProgressIndicator:"CONVERSATION_PROGRESS_INDICATOR",SessionStatusChanged:"CONVERSATION_SESSION_STATUS_CHANGED"}).forEach((t=>o.addEventListener(t,n))),o.onmessage=n,o.addEventListener("upstream_error",(t=>{ht.error("❌ Live agent SSE upstream error:",t.data),lt.emit("AGENT_ERROR",{reason:"string"==typeof t.data&&t.data?t.data:"upstream_error"}),o.close()}))}async startChat(t){await this.initialize(t)}async resumeChat(t){var i,e,s;if(!(null==t?void 0:t.sessionId)||!(null==t?void 0:t.conversationId))throw new Error("resumeChat requires sessionId (accessToken) and conversationId");if(this.configSettings=(null==t?void 0:t.config)||this.configSettings,!(null===(i=this.configSettings)||void 0===i?void 0:i.instanceUrl)||!(null===(e=this.configSettings)||void 0===e?void 0:e.orgId)||!(null===(s=this.configSettings)||void 0===s?void 0:s.messagingChannelId))throw new Error("Missing required configuration settings for resuming Salesforce Live Agent session");this.sessionContext={accessToken:t.sessionId,conversationId:t.conversationId,userId:t.userId||"",isActive:!0,lastMessageReadTime:0};const o=new URL(`${this.configSettings.instanceUrl}/iamessage/api/v2/conversation/${this.sessionContext.conversationId}/entries`);o.searchParams.set("limit","1"),o.searchParams.set("direction","FromEnd");const n=await fetch(o.toString(),{method:"GET",headers:{Authorization:`Bearer ${this.sessionContext.accessToken}`}});if(401===n.status||403===n.status)throw new rt;if(!n.ok)throw new Error(`Session probe failed: ${n.status} ${n.statusText}`);lt.emit("liveAgentReady",void 0),this.listenToMessages()}async sendMessage(t){var i,e,s,o;if(!(await fetch(`${null===(i=this.configSettings)||void 0===i?void 0:i.instanceUrl}/iamessage/api/v2/conversation/${null===(e=this.sessionContext)||void 0===e?void 0:e.conversationId}/message`,{method:"POST",headers:{Authorization:`Bearer ${null===(s=this.sessionContext)||void 0===s?void 0:s.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({message:{id:crypto.randomUUID(),messageType:"StaticContentMessage",staticContent:{formatType:"Text",text:null==t?void 0:t.message}},esDeveloperName:null===(o=this.configSettings)||void 0===o?void 0:o.messagingChannelId,isNewMessagingSession:(null==t?void 0:t.isNewSession)||!1,language:""})})).ok)throw new Error("Failed to send message")}async pollMessages(t){return new Promise((async(t,i)=>{this.sessionContext.lastMessageReadTime=0;const e=async()=>{var s,o,n;try{const i=new URL(`${null===(s=this.configSettings)||void 0===s?void 0:s.instanceUrl}/iamessage/api/v2/conversation/${null===(o=this.sessionContext)||void 0===o?void 0:o.conversationId}/entries`);i.searchParams.append("limit","50"),i.searchParams.append("direction","FromEnd"),i.searchParams.append("startTimestamp",`${this.sessionContext.lastMessageReadTime}`);const a=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${null===(n=this.sessionContext)||void 0===n?void 0:n.accessToken}`}}),r=await a.json(),l=this.parseMessageEntries(r.conversationEntries).sort(((t,i)=>t.timestamp-i.timestamp)).map((t=>{var i;return{text:t.content,isUser:!1,id:t.id,timestamp:new Date(t.timestamp),images:[],conversationId:t.id,formModel:"",surveyDomId:"",sender:{role:"endUser"===t.sender.role?"user":"ai",displayName:null===(i=null==t?void 0:t.sender)||void 0===i?void 0:i.displayName}}}));(null==l?void 0:l.length)>0&&(this.sessionContext.lastMessageReadTime=(new Date).getTime(),lt.emit("messageReceived",l)),t(l),setTimeout(e,5e3)}catch(t){ht.error("Error on Polling",t.toString()),i(t)}};await e()}))}async isChatActive(t){return ht.debug("sessionId",t),!!this.sessionContext&&this.sessionContext.isActive}async endChat(t){var i,e,s,o,n,a,r;if(null===(i=this.availabilityAbort)||void 0===i||i.abort(),null===(e=this.eventSource)||void 0===e||e.close(),null===(s=this.sessionContext)||void 0===s?void 0:s.conversationId){const t=await fetch(`${null===(o=this.configSettings)||void 0===o?void 0:o.instanceUrl}/iamessage/api/v2/conversation/${null===(n=this.sessionContext)||void 0===n?void 0:n.conversationId}?esDeveloperName=${null===(a=this.configSettings)||void 0===a?void 0:a.messagingChannelId}`,{method:"DELETE",headers:{Authorization:`Bearer ${null===(r=this.sessionContext)||void 0===r?void 0:r.accessToken}`,"Content-Type":"application/json"}});(null==t?void 0:t.ok)||ht.warn("Failed to end the chat")}}async getTranscript(t){return ht.debug("sessionId",t),this.sessionContext&&this.sessionContext.initialMessages||[]}}class ct{constructor(){}static getProvider(t){if("salesforce"!==(null!=t?t:this.provider))throw new Error("Unsupported Live Agent provider");return this.providerInstance=new dt,this.providerInstance}}ct.provider="salesforce";class ut{constructor(){this.logger=new u("LiveAgentEventHandler",{logLevel:v.Warn}),this.handleAgentMessage=t=>{let i="";if((null==t?void 0:t.length)>0)for(const e of t)i+=(null==e?void 0:e.text)+"\n\n";return i},this.sendMessage=t=>{this.liveAgentProvider?(this.logger.debug("Sending message to Live Agent:",t.message),this.liveAgentProvider.sendMessage(t)):this.logger.warn("Live Agent provider is not initialized. Cannot send message.")},this.disconnectLiveAgent=()=>{this.liveAgentProvider?(this.logger.debug("Disconnecting from Live Agent"),this.liveAgentProvider.endChat("")):this.logger.warn("Live Agent provider is not initialized. Cannot disconnect.")}}addAgentEventMessage(t){const i=document.createElement("div");return t.forEach((t=>{const e=document.createElement("div");e.className="py-2 border-b border-gray-200 text-center";const s=document.createElement("span");s.className="text-[10px] font-medium text-gray-500 tracking-wide",s.textContent=(null==t?void 0:t.text)||"Agent event",e.appendChild(s),i.appendChild(e)})),i}async connectToLiveAgent(t="salesforce",i){try{switch(this.logger.debug("Connected to Live Agent",t," --- ",i),t){case"salesforce":this.logger.debug("Using Salesforce Live Agent Provider"),this.liveAgentProvider=ct.getProvider(t),await this.liveAgentProvider.startChat(i);break;case"custom":this.logger.debug("Using Custom Live Agent Provider");break;case"liveagent":this.logger.debug("Using LiveAgent Live Agent Provider");break;default:throw new Error(`Unsupported Live Agent provider: ${t}`)}}catch(t){throw this.logger.error("Error connecting to Live Agent:",t),t}}async resumeLiveAgentSession(t="salesforce",i){try{if(this.logger.debug("Resuming Live Agent session",t," --- ",i),this.liveAgentProvider=ct.getProvider(t),!this.liveAgentProvider.resumeChat)throw new Error(`Provider '${t}' does not support session resume`);await this.liveAgentProvider.resumeChat(i)}catch(t){throw this.logger.error("Error resuming Live Agent session:",t),t}}}function vt(t){return!!function(t){return"object"==typeof t&&null!==t}(t)&&Array.isArray(t.messages)&&"boolean"==typeof t.isMinimized&&"boolean"==typeof t.isOpened&&"boolean"==typeof t.isExpanded&&"string"==typeof t.conversationId&&"string"==typeof t.projectId&&"boolean"==typeof t.newChat}function pt(t){return"undefined"!=typeof TextEncoder?(new TextEncoder).encode(t).length:t.length}function gt(t,i,e={}){var s,o,n,a;if("undefined"==typeof document)return!1;const r=null!==(s=e.path)&&void 0!==s?s:"/",l=null!==(o=e.sameSite)&&void 0!==o?o:"Lax",h=null!==(n=e.secure)&&void 0!==n?n:"undefined"!=typeof window&&"https:"===window.location.protocol,d=e.domain;let c=`${t}=${encodeURIComponent(i)}`;if(d){if(!/^[a-zA-Z0-9._-]+$/.test(d))return console.warn("AI12Z: Invalid cookie domain characters"),!1;c+=`; Domain=${d}`}c+=`; Path=${r}`,c+=`; SameSite=${l}`,c+="; Max-Age="+24*(null!==(a=e.maxAgeDays)&&void 0!==a?a:7)*60*60,h&&(c+="; Secure");const u=pt(c);return u>4e3?(console.warn(`AI12Z: Cookie value exceeds safe limit (${u} bytes). Cookie not set.`),!1):(document.cookie=c,!0)}function mt(t,i,e={}){var s,o;const n=Object.assign({},i);(null===(s=n.messages)||void 0===s?void 0:s.length)>0&&(n.messages=[]);const a=JSON.stringify(n),r=encodeURIComponent(a),l=null!==(o=e.maxBytes)&&void 0!==o?o:3800;return pt(r)>l?(console.warn(`AI12Z: Cookie '${t}' exceeds size limit and was skipped`),!1):gt(t,a,e)}function ft(t){if(!t)return;if("undefined"==typeof window)return;const i=t.replace(/^\./,""),e=window.location.hostname;if(e===i||e.endsWith("."+i))return t;console.warn("AI12Z: subDomain does not match current host")}const bt=new u("Ai12zBot"),yt=e(class extends s{constructor(i){super(),!1!==i&&this.__registerHost(),this.__attachShadow(),this.messageSent=o(this,"messageSent",7),this.messageReceived=o(this,"messageReceived",7),this.close=o(this,"close",7),this.open=o(this,"open",7),this.minimize=o(this,"minimize",7),this.errored=o(this,"errored",7),this.formSubmitted=o(this,"formSubmitted",7),this.isElementAvailable=o(this,"isElementAvailable",7),this.cdnPath="https://cdn.ai12z.net/assets/bot",this.surveyCDNPath="https://cdn.ai12z.net/pkg/surveyjs",this.styles=["https://cdn.jsdelivr.net/npm/@highlightjs/cdn-assets@11.11.1/styles/default.min.css",`https://cdn.ai12z.net/assets/bot/${t.CDN_PATH}/tailwind.min.css`],this.liveAgentEventHandler=new ut,this.customStyle="",this.customJS="",this.dataOverrideFunction=null,this.ignoreChunks=!1,this.unreadCount=0,this.hasPersistedConversationId=!1,this.liveAgentButtonText="Talk to a Live Agent",this.isLiveAgentEnabled=!1,this.isTypingIndicatorVisible=!1,this.dataKey=t.DATA_KEY||"",this.dataMode=t.DATA_MODE||"prod",this.dataAttributes={},this.excludeTags=[],this.includeTags=[],this.botSettings={},this.canRender=!0,this.voiceType="default",this.voice="en-US",this.showSubmit=!1,this.hideAllButtons=!1,this.showMenu=!1,this.isProse=!0,this.isLiveAgent=!1,this.isConnectingLiveAgent=!1,this.showWelcomeScreen=!0,this.showHistory=!1,this.conversationId="",this.surveyDomId="",this.searchResults={},this.buttons=[],this.currentDomId="",this.messages=[],this.questionCounter=0,this.timestamp="",this.rowCount=1,this.isBot=!1,this.conversationHistory=[],this.query="",this.scriptArray=[],this.imagesBase64List=[],this.focusedIndex=-1,this.isAnimated=!1,this.isMinimized=!1,this.isStreaming=!1,this.showErrorMessage=!1,this.errorMessage="",this.emptyMessageError=!1,this.isOpened=!1,this.isContent=!1,this.isToggled=!1,this.showPrivacy=!1,this.isRendered=!1,this.showShortcutsDialog=!1,this.showLiveAgentEndDialog=!1,this.liveAgentSessionId="",this.liveAgentConversationId="",this.liveAgentProviderName="salesforce",this.liveAgentListenersRegistered=!1,this.shortcuts=P,this.announceMessage="",this.isSending=!1,this.messageRefs=[],this.handlePaste=t=>{var i;t.preventDefault();const e=(null===(i=t.clipboardData)||void 0===i?void 0:i.getData("text"))||"";if(this.inputEl&&e){const t=this.inputEl,i=t.selectionStart,s=t.selectionEnd,o=t.value,n=o.substring(0,i)+e+o.substring(s);t.value=n;const a=i+e.length;t.setSelectionRange(a,a),setTimeout((()=>{this.adjustHeight()}),0)}},this.checkHistory=()=>{const t=localStorage.getItem(`${this.visitorID}`);let i=[];t&&(i=JSON.parse(t),i=i.filter((t=>{var i;return t.projectId===(null===(i=this.botSettings)||void 0===i?void 0:i.pId)}))),this.showHistory=i.length>0&&"v1"===this.botSettings.botVersion},this.initializeScript=t=>z(t,this.mainObject),this.renderSurvey=async t=>{if(this.surveyDomId){await this.assetLoader.loadSurveyDependencies();try{await B({chat:t,surveyDomId:this.surveyDomId,shadowRoot:this.el.shadowRoot,config:{dataKey:this.dataKey,dataMode:this.dataMode,dataAttributes:this.dataAttributes,formSubmitRenderCallback:t=>{this.handleSurveyCompletionRender(t)},onSubmitError:t=>{var i;const e=null===(i=this.el.shadowRoot)||void 0===i?void 0:i.querySelector(`#${this.surveyDomId}`);e?e.innerHTML="Form submission blocked by validation"!==t?"Failed to submit form":"Submission blocked due to suspicious activity.":console.error(`Survey element not found for DOM ID: ${this.surveyDomId}`)}}})}catch(t){console.error("Error rendering survey:",t)}}else console.warn("Survey DOM ID is empty")},this.handleMessage=(t,i)=>{var e;const s=new d.Converter,o=null===(e=this.el.shadowRoot)||void 0===e?void 0:e.querySelector(`#${i}`);if(!o)return void console.error(`Message bubble with ID ${i} not found.`);var n=o.getAttribute("data-bubbleText")||"";o.setAttribute("data-bubbleText",n+=t),o.setAttribute("aria-label",n),o.setAttribute("role","log"),o.setAttribute("aria-live","polite"),o.setAttribute("aria-atomic","false");let a=s.makeHtml(n);o.innerHTML=a},this.updateScreenSize=()=>{window.innerWidth<=767&&(this.isMinimized=!this.isOpened)},this.handleSend=async(t,i={})=>{var e,s,o;const{isHide:n=!1,isLiveChatEnded:a=!1,bypassSendGuard:r=!1}=i;if((this.isSending||this.isStreaming)&&!r)return this.query="",!1;this.isSending=!0;const l="string"==typeof this.query?this.query.trim():"",h="string"==typeof t?t.trim():"",d=(null===(e=this.inputEl)||void 0===e?void 0:e.value.trim())||"",c=l||h||d,u=h||(n?"":c);if(!c&&0===this.imagesBase64List.length)return this.showEmptyMessageValidation(),this.query="",this.isSending=!1,!1;if(!n&&!u&&0===this.imagesBase64List.length)return this.query="",this.isSending=!1,this.showEmptyMessageValidation(),!1;this.emptyMessageError=!1,this.surveyDomId="",this.announce("Message sent successfully"),this.isLiveAgent||(this.questionCounter=this.questionCounter+1,localStorage.setItem("ai12z-bot-data",JSON.stringify({qCounter:this.questionCounter})));const v=u;this.inputEl&&(this.inputEl.value=v),0===this.messages.length&&this.botSettings.autoResetTimer>0&&this.startTimer(),this.showWelcomeScreen&&"v1"===this.botSettings.botVersion&&(this.showWelcomeScreen=!1);try{0!==this.messages.length&&(null===(s=this.socket)||void 0===s?void 0:s.connected)&&this.socket&&this.socket.connected||await this.socketConnection()}catch(t){return console.error("Error in handleSend:",t),this.query="",this.isSending=!1,!1}const p=(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(this.messages=[...this.messages,{text:v,isUser:!0,id:`user-${m()}`,timestamp:p,images:this.imagesBase64List,conversationId:this.conversationId,isLoading:!1,formModel:{},surveyDomId:"",isHide:null!=n&&n},{text:this.botSettings.maxQuestion>0&&this.questionCounter>this.botSettings.maxQuestion&&!this.isLiveAgent&&!a?""!==this.botSettings.msgLimit?this.botSettings.msgLimit:"Sorry, you have reached the maximum number of questions.":"",isUser:!1,id:"",timestamp:"",isLoading:!(this.botSettings.maxQuestion>0&&this.questionCounter>this.botSettings.maxQuestion&&!this.isLiveAgent&&!a),images:[],conversationId:this.conversationId,formModel:{},surveyDomId:""}],2===this.messages.length&&(this.visitorID=f()),this.checkHistory(),setTimeout((()=>{this.scrollToBottom()}),100),this.botSettings.maxQuestion>0&&this.questionCounter>this.botSettings.maxQuestion&&!this.isLiveAgent&&!a)return this.inputEl.value="",this.query="",this.releaseSendLock(),!1;this.currentDomId="",this.isLiveAgent?(this.messages=this.messages.slice(0,-1),this.liveAgentEventHandler.sendMessage({sessionId:"",message:this.inputEl.value}),this.updateBotState(),this.inputEl.value&&(this.inputEl.value=""),this.query="",this.isSending=!1):(this.checkLiveAgentMode(),this.isStreaming=!0,this.ignoreChunks=!1,this.resetStreamEndWatchdog(),this.invokeSocket(c));const g=null===(o=this.el.shadowRoot)||void 0===o?void 0:o.querySelector("#previewContainer");return g&&(g.innerHTML=""),this.imagesBase64List=[],this.rowCount=1,this.showSubmit=!1,!0},this.agentMessageCreated=t=>{var i;const e=this.liveAgentEventHandler.handleAgentMessage(t);if(!e)return;this.announce("New message received from live agent");const s=(new d.Converter).makeHtml(e),o=Array.isArray(t)?t[0]:t,n={id:`chatbot-${m()}`,text:s,isUser:!1,isLoading:!1,timestamp:(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),images:[],conversationId:this.conversationId,formModel:{},surveyDomId:"",thumbsId:`${m()}`,showIcon:!0,hideThumbsUpandDown:!0,insightId:null,sender:null!==(i=null==o?void 0:o.sender)&&void 0!==i?i:{role:"agent",displayName:"Agent"}};this.messages=[...this.messages,n],this.currentDomId="",this.updateBotState(),this.scheduleAutoScroll()},this.addEventMessage=t=>{var i;const e=this.liveAgentEventHandler.addAgentEventMessage([{text:t}]);if(""===this.currentDomId&&this.messages.length>0&&(this.currentDomId=this.messages[this.messages.length-1].id),e&&this.currentDomId){const t=null===(i=this.el.shadowRoot)||void 0===i?void 0:i.querySelector(`#${this.currentDomId}`);if(t)return t.parentNode.appendChild(e),this.currentDomId="",e}return null},this.findingAgent=()=>{this.announce("Finding a live agent for you"),this.isTypingIndicatorVisible=!1,this.removeFindingAgentPlaceholder();const t=this.addEventMessage("Connecting to a live agent...");t&&t.setAttribute("data-finding-agent","true"),this.currentDomId=""},this.handleTypingStarted=t=>{this.isTypingIndicatorVisible=t},this.handleTypingStopped=()=>{this.isTypingIndicatorVisible=!1},this.handleAgentError=t=>{bt.warn("Live Agent error category:",function(t){if(!t)return"unknown";if("transport"===t)return"transport";const i=/\b([1-5]\d{2})\b/.exec(t);return i?`upstream_${i[1][0]}xx`:"upstream_other"}(null==t?void 0:t.reason)),this.addEventMessage("Something went wrong with Live Agent, please try again later"),this.isLiveAgent=!1,this.liveAgentSessionId="",this.liveAgentConversationId="",this.isTypingIndicatorVisible=!1,this.liveAgentEventHandler.disconnectLiveAgent(),this.clearEvents(),this.liveAgentButtonText="Talk to a Live Agent",this.announce("Live agent connection failed")},this.handleAgentConversationEnded=()=>{if(this.isLiveAgent){const t=this.messages[this.messages.length-1];"system"===(null==t?void 0:t.type)&&"string"==typeof(null==t?void 0:t.text)&&t.text.toLowerCase().includes("left")||(this.messages=[...this.messages,{id:`system-${m()}`,text:"The live agent has left the conversation.",type:"system",isUser:!1,isLoading:!1,timestamp:(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),images:[],conversationId:this.conversationId,formModel:{},surveyDomId:"",sender:null}]),this.announce("Live agent chat ended")}this.isLiveAgent=!1,this.liveAgentSessionId="",this.liveAgentConversationId="",this.isTypingIndicatorVisible=!1,this.liveAgentButtonText="Talk to a Live Agent",this.currentDomId="",this.clearEvents(),this.updateBotState(),this.scheduleAutoScroll()},this.agentEventHandler=t=>{if(this.isTypingIndicatorVisible=!1,(null==t?void 0:t.length)>0){const i=t.map((t=>({id:t.id||`system-${m()}`,text:t.text||"",type:"system",isUser:!1,isLoading:!1,timestamp:new Date,images:[],conversationId:this.conversationId,formModel:{},surveyDomId:"",sender:t.sender||null})));this.messages=[...this.messages,...i],this.updateBotState(),this.removeFindingAgentPlaceholder(),this.inputEl&&(this.inputEl.value=""),this.currentDomId="",this.scheduleAutoScroll()}},this.handleAgentSessionCreated=()=>{this.announce("Connected to live agent"),this.isLiveAgent=!0,this.liveAgentButtonText="End Live Agent chat",requestAnimationFrame((()=>{var t;const i=null===(t=this.el.shadowRoot)||void 0===t?void 0:t.querySelector('[data-testid="user-input-textarea"]');i&&(this.inputEl=i)}))},this.handleAgentSessionInfo=t=>{this.liveAgentSessionId=(null==t?void 0:t.sessionId)||"",this.liveAgentConversationId=(null==t?void 0:t.conversationId)||"",this.isLiveAgent=!0,this.updateBotState()},this.handleAgentUnavailable=()=>{this.addEventMessage("Live Agent is currently unavailable. Please try again later."),this.isTypingIndicatorVisible=!1,this.isLiveAgent=!1,this.liveAgentSessionId="",this.liveAgentConversationId="",this.updateBotState(),this.announce("Live agent is currently unavailable"),this.clearEvents()},this.toggleBot=()=>{this.isToggled=!this.isToggled},this.menuClick=t=>{switch(t.type){case"menu":this.toggleBot(t),this.showHistory=!1,this.showWelcomeScreen=!0,this.isStreaming||this.handleSend(t.button.label);break;case"history":this.toggleBot(t),this.showHistory=!0,this.loadConversation();break;case"end":this.syncBodyScrollLock(!1),this.messages=[],this.conversationId="",this.isOpened=!1,this.isMinimized=!this.isExpanded,this.showWelcomeScreen=!0,this.toggleBot(t),this.showHistory=!1,this.close.emit("close");break;case"startover":this.messages=[],this.conversationId="",this.isOpened=!0,this.isMinimized=!1,this.showWelcomeScreen=!0,this.toggleBot(t),this.showHistory=!1,this.updateBotState()}}}get mainObject(){return window.ai12z||(window.ai12z={}),window.ai12z}handleKeyDown(t){var i,e;if(!["Control","Shift","Alt","Meta"].includes(t.key)){if(("?"===t.key||"/"===t.key)&&t.shiftKey&&(t.metaKey||t.ctrlKey)&&!this.isInputFocused())return t.preventDefault(),void(this.showShortcutsDialog=!this.showShortcutsDialog);if(this.showShortcutsDialog&&("Escape"===t.key||("?"===t.key||"/"===t.key)&&t.shiftKey&&(t.metaKey||t.ctrlKey)))return t.preventDefault(),void(this.showShortcutsDialog=!1);if("k"===t.key&&(t.metaKey||t.ctrlKey))return t.preventDefault(),t.stopPropagation(),void this.action("open");if("h"===t.key&&(t.metaKey||t.ctrlKey))return t.preventDefault(),t.stopPropagation(),this.showHistory=!this.showHistory,this.showWelcomeScreen=!1,void this.loadConversation();if("n"===t.key&&(t.metaKey||t.ctrlKey))return t.preventDefault(),t.stopPropagation(),void this.handleNewConversation();"Enter"===t.key&&!t.shiftKey&&this.isOpened&&this.isInputFocused()&&(t.preventDefault(),t.stopPropagation(),(null===(i=this.inputEl)||void 0===i?void 0:i.value.trim().length)>0&&!this.isStreaming?this.handleSend(this.inputEl.value):0===(null===(e=this.inputEl)||void 0===e?void 0:e.value.trim().length)&&0===this.imagesBase64List.length&&(this.emptyMessageError=!0,this.announce("Message cannot be empty. Please enter a message."),this.inputEl&&this.inputEl.focus(),setTimeout((()=>{this.emptyMessageError=!1}),3e3))),"Escape"===t.key&&(this.action("minimize"),this.showPrivacy&&(this.showPrivacy=!1,t.preventDefault()))}}isInputFocused(){var t;const i=(null===(t=this.el.shadowRoot)||void 0===t?void 0:t.activeElement)||document.activeElement;return"TEXTAREA"===(null==i?void 0:i.tagName)||"INPUT"===(null==i?void 0:i.tagName)}handleNewConversation(){this.syncBodyScrollLock(!0),this.messages=[],this.conversationId="",this.showWelcomeScreen=!0,this.showHistory=!1,this.isOpened=!0,this.releaseSendLock(),setTimeout((()=>{var t;null===(t=this.inputEl)||void 0===t||t.focus()}),100)}buttonClickHandler(t){this.showWelcomeScreen=!1,this.query=t.detail.action,this.handleSend(t.detail.label)}sendQueryToBotHandler(t){this.showWelcomeScreen=!1,this.query=t.detail,this.handleSend(t.detail)}deleteChatHistoryHandler(t){var i;const e=this.getConversationHistory().filter((i=>i.conversationId!==t.detail.conversationId));localStorage.setItem(`${this.visitorID}`,JSON.stringify(e)),this.conversationHistory=j(e,null===(i=this.botSettings._id)||void 0===i?void 0:i.$oid,this.botSettings.pId)}chatClickHandler(t){t.detail.length>0&&(this.messages=t.detail,requestAnimationFrame((()=>{this.hydrateMessagesFromState()}))),this.showWelcomeScreen=!1,this.showHistory=!1}openChatHandler(t){}formSubmittedHandler(t){t.stopPropagation(),this.formSubmitted.emit(t.detail.data)}async sendMessage(t,i,e){this.query=t,this.handleSend(null!=i?i:t,e)}async sendQuery(t){console.warn("sendQuery mehtdod is deprecated, use sendMessage instead"),this.handleSend(t)}async sendJSON(t,i){this.query=JSON.stringify(t),this.handleSend(i)}async openBot(t=!1){this.openChat(t)}async action(t,i){var e;"open"===t&&this.openChat(null!==(e=null==i?void 0:i.expanded)&&void 0!==e&&e),"minimize"===t&&this.isOpened&&(this.syncBodyScrollLock(!1),this.minimizeChat()),this.checkHistory(),"close"===t&&(this.syncBodyScrollLock(!1),this.searchResults={},this.surveyDomId="",this.showWelcomeScreen=!0,this.showHistory=this.messages.length>0,this.messages=[],this.conversationId="",this.isOpened=!1,this.close.emit("close"),this.announce("Chat closed"),clearInterval(this.timer))}async setProcessDataOverride(t){this.dataOverrideFunction=t}async configureSettings(t){this.botSettings=Object.assign(Object.assign({},this.botSettings),t)}async componentWillLoad(){this.canRender=await b(this.dataKey,this.dataMode),this.checkCustomSlot(),this.timestamp=y(new Date),this.updateScreenSize(),await this.configBot(),this.botSettings.disableBeacon||q(this.dataKey,this.dataMode),this.visitorID="ai12z-"+localStorage.getItem("ai12z-visitorId"),this.hydrateStateFromStorage(),F("bot",this.dataKey,this.dataMode)}onDataKeyChange(t){F("bot",this.dataKey,this.dataMode)}onDataModeChange(t){F("bot",this.dataKey,this.dataMode)}hydrateStateFromStorage(){var t,i,e;const s=null===(t=this.botSettings)||void 0===t?void 0:t.pId;if(!s)return void console.warn("AI12Z: Cannot hydrate state - projectId not available");const o=N(s,null===(i=this.botSettings._id)||void 0===i?void 0:i.$oid)||function(t,i){const e=function(t){if("undefined"==typeof document)return null;const i=t.replace(/([.*+?^${}()|[\]\\])/g,"\\$1"),e=document.cookie.match(new RegExp(`(?:^|; )${i}=([^;]*)`));return e?decodeURIComponent(e[1]):null}(t);if(!e)return null;try{const s=JSON.parse(e);return i&&!i(s)?(console.warn(`AI12Z: Cookie '${t}' failed validation`),null):s}catch(t){return console.warn("AI12Z: Failed to parse cookie JSON:",t),null}}(L(s,null===(e=this.botSettings._id)||void 0===e?void 0:e.$oid),vt);o&&(this.isOpened=o.isOpened,this.isMinimized=o.isMinimized,this.isOpened&&this.syncBodyScrollLock(!0,!1),this.isExpanded=o.isExpanded,this.conversationId=o.conversationId,this.hasPersistedConversationId=Boolean(o.conversationId),o.newChat||(this.messages=[...o.messages||[]]),o.isLiveAgent&&o.liveAgentSessionId&&o.liveAgentConversationId&&(this.isLiveAgent=o.isLiveAgent||!0,this.liveAgentSessionId=o.liveAgentSessionId,this.liveAgentConversationId=o.liveAgentConversationId,this.liveAgentProviderName=o.liveAgentProviderName||"salesforce",this.liveAgentButtonText="End Live Agent chat",setTimeout((()=>this.recoverLiveAgentSession()),0)),setTimeout((()=>{this.scrollToBottom()}),100))}async recoverLiveAgentSession(){var t,i,e,s,o,n;if(0===Object.keys(null!==(e=null===(i=null===(t=this.botSettings)||void 0===t?void 0:t.liveagent)||void 0===i?void 0:i.providers)&&void 0!==e?e:{}).length||!this.liveAgentSessionId||!this.liveAgentConversationId)return;const a=null!==(n=null===(o=null===(s=this.botSettings)||void 0===s?void 0:s.liveagent)||void 0===o?void 0:o.providers[this.liveAgentProviderName])&&void 0!==n?n:null;if(a)try{this.registerLiveAgentListeners(),await this.liveAgentEventHandler.resumeLiveAgentSession(this.liveAgentProviderName,{sessionId:this.liveAgentSessionId,conversationId:this.liveAgentConversationId,userId:this.visitorID,config:a})}catch(t){t instanceof rt?(this.addEventMessage("Your live agent session has expired. Please reconnect."),this.announce("Live agent session expired")):console.warn("AI12Z: Failed to recover live agent session, ending gracefully:",t),this.isLiveAgent=!1,this.liveAgentSessionId="",this.liveAgentConversationId="",this.liveAgentButtonText="Talk to a Live Agent",this.clearEvents()}}releaseSendLock(){this.clearStreamEndWatchdog(),this.isStreaming=!1,this.isSending=!1}clearStreamEndWatchdog(){this.streamEndWatchdog&&(clearTimeout(this.streamEndWatchdog),this.streamEndWatchdog=void 0)}resetStreamEndWatchdog(){this.clearStreamEndWatchdog(),this.streamEndWatchdog=setTimeout((()=>{this.streamEndWatchdog=void 0,this.isStreaming&&(console.error("Socket response timed out before completion"),this.failTurn("Something went wrong. Please try again."))}),3e4)}componentDidLoad(){var t;w(this.el),"undefined"==typeof window||window.Handlebars||(window.Handlebars=x),n.register("bot",this),window.addEventListener("resize",this.updateScreenSize.bind(this)),document.addEventListener("click",this.handleClickOutside.bind(this));const i=document.createElement("script");i.text='\n var ai12zChat = window["ai12z"] = {}\n ',document.head.appendChild(i),null===(t=this.el.shadowRoot)||void 0===t||t.appendChild(i),this.assetLoader||this.initializeAssetLoader(),this.messages.length>0&&requestAnimationFrame((()=>{this.hydrateMessagesFromState()})),n.setActive("bot")}async hydrateMessagesFromState(){var t,i,e,s;if((null===(t=this.el)||void 0===t?void 0:t.shadowRoot)&&0!==this.messages.length){await new Promise((t=>requestAnimationFrame((()=>t()))));for(const t of this.messages)if(!t.isUser&&t.id){if("template"===t.controlType)this.processTemplateData(t,t.itemComponent);else if("form"===t.controlType){if(!t.surveyDomId)continue;if(this.surveyDomId=t.surveyDomId,!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(t.surveyDomId)){console.warn("Invalid surveyDomId, skipping render");continue}t.text=`<div id=${this.surveyDomId} style="width: 100%;" class="survey-container"></div>`,(await _(`#${t.id}`,this.el)).querySelector(`#${t.surveyDomId}`)||await _(`#${t.surveyDomId}`,this.el),await this.renderSurvey(t.itemComponent)}else if("carousel"===t.controlType&&"carousel"===(null===(i=t.itemComponent)||void 0===i?void 0:i.controlType))this.processChatData(t,t.itemComponent);else if(!t.controlType){t.text=S(t.text,(null===(e=this.botSettings)||void 0===e?void 0:e.linkTarget)||"_blank","ai12z-link",null===(s=this.botSettings)||void 0===s?void 0:s.utm,"answer");const i=C(t.text);t.text=i.body,this.buttons=i.buttons,this.addEventListeners(`#${t.id}`)}"form"!==t.controlType&&this.checkHighlightcode(t.id)}}}disconnectedCallback(){document.removeEventListener("click",this.handleClickOutside.bind(this)),window.removeEventListener("resize",this.updateScreenSize),this.autoScrollTimer&&clearTimeout(this.autoScrollTimer),this.clearStreamEndWatchdog()}handleClickOutside(t){this.showMenu&&this.plusIconRef&&!this.plusIconRef.contains(t.target)&&(this.showMenu=!1)}async initializeAssetLoader(){try{this.assetLoader=M({shadowRoot:this.el.shadowRoot,cdnPath:this.cdnPath,surveyCDNPath:this.surveyCDNPath,customStyles:this.styles}),await this.assetLoader.loadBotAssets()}catch(t){console.error("❌ Failed to initialize asset loader:",t)}}async processDataOverride(t){if(this.dataOverrideFunction&&"function"==typeof this.dataOverrideFunction)try{return await this.dataOverrideFunction(t)}catch(t){throw console.error("Error in custom processDataOverride:",t),t}return t}announce(t){this.announceMessage=t,setTimeout((()=>{this.announceMessage=""}),1e3)}isFirstExchange(){return!this.hasPersistedConversationId}syncBodyScrollLock(t,i=this.isOpened){t&&!i&&K.acquire("ai12z-bot"),!t&&i&&K.release("ai12z-bot")}openChat(t=!1){var i,e;this.syncBodyScrollLock(!0),this.unreadCount=0,n.setActive("bot"),this.isExpanded=t,this.isMinimized=!1,this.isContent=!1,this.isOpened=!0;const s=L(this.botSettings.pId,null===(i=this.botSettings._id)||void 0===i?void 0:i.$oid);if(sessionStorage.getItem(s))this.updateBotState();else{const t={messages:[],isMinimized:this.isMinimized,isOpened:this.isOpened,isExpanded:this.isExpanded,conversationId:this.conversationId,projectId:this.botSettings.pId,configId:null===(e=this.botSettings._id)||void 0===e?void 0:e.$oid,newChat:!0};sessionStorage.setItem(s,JSON.stringify(t)),this.botSettings.cookies&&ft(this.botSettings.subDomain)&&mt(s,t,{domain:this.botSettings.subDomain})}setTimeout((()=>{this.announce("Chat opened")}),600),requestAnimationFrame((()=>{requestAnimationFrame((()=>{this.imageUploaderRef&&this.isElementAvailable.emit(!0)}))})),this.open.emit("open")}minimizeChat(){this.isOpened=!1,this.isContent=!!this.isExpanded,this.isMinimized=!this.isExpanded,this.isAnimated=!1,this.updateScreenSize(),this.announce("Chat minimized"),this.minimize.emit("minimize")}adjustHeight(){this.inputEl&&(this.inputEl.style.height="auto",this.inputEl.style.height=this.inputEl.scrollHeight+"px")}async configBot(){var t,i,e,s,o;const n={apiKey:this.dataKey,configId:this.configId,configType:"bot"};try{const a=await A(n,this.dataMode);if(a){if(this.botSettings=a,(null===(i=null===(t=this.botSettings)||void 0===t?void 0:t.v3)||void 0===i?void 0:i.siteKey)?I(a._id,a.v3.siteKey,"bot",this.dataKey,this.dataMode,(t=>{this.errored.emit(t),this.announce("An error occurred while loading the chat.")})).then((t=>{t&&(this.isRendered=!0)})).catch((t=>{console.error("Recaptcha verification failed:",t),this.isRendered=!1})):this.isRendered=!0,"v2"!==this.botSettings.botVersion||this.botSettings.isExpanded||this.isBot||this.isOpened||(this.isMinimized=!0),this.assetLoader||await this.initializeAssetLoader(),this.assetLoader)try{await this.assetLoader.loadBotTheme(this.botSettings)}catch(t){console.error("Failed to load bot theme:",t)}if(this.botSettings.isExpanded&&!this.isBot?(this.isExpanded=!0,this.isMinimized=!1):this.isOpened||(this.isMinimized=!0),this.botSettings.linkTarget||(this.botSettings.linkTarget="_blank"),this.botSettings.customCSS&&(this.customStyle=this.botSettings.customCSS),this.botSettings.customJS&&(this.customJS=this.botSettings.customJS),"v2"===this.botSettings.botVersion){const t=localStorage.getItem("ai12z-visitorId");this.visitorID="ai12z-"+t}if(this.botSettings.privacyTemplate&&""!==this.botSettings.privacyTemplate&&(this.showPrivacy=!0),this.botSettings.audioType&&(this.voiceType=this.botSettings.audioType,this.voice=this.botSettings.voice),this.botSettings&&!(null===(e=this.botSettings)||void 0===e?void 0:e.cookies)){const t=ft(this.botSettings.subDomain);!function(t,i={}){const{path:e="/",domain:s}=i;"undefined"!=typeof document&&function(t,i="/",e){gt(t,"",{maxAgeDays:0,path:i,domain:e})}(t,e,s)}(L(this.botSettings.pId,null===(o=null===(s=this.botSettings)||void 0===s?void 0:s._id)||void 0===o?void 0:o.$oid),{domain:t})}}}catch(t){console.error("Error loading bot configuration:",t)}}checkCustomSlot(){const t=this.el.children;if(t&&t.length>0)for(var i=0;i<t.length;i++)"bot"!==t[i].tagName.toLowerCase()&&"bot"!==t[i].getAttribute("slot")||(this.isBot=!0,this.isExpanded=!1)}handleSocketResponse(){this.socket.off("response"),this.socket.off("end_response"),this.socket.off("chunk"),this.socket.off("complete"),void 0===this.botSettings.maxQuestion||0===this.botSettings.maxQuestion?(this.botSettings.maxQuestion=0,this.handleBotMessages()):this.questionCounter<=this.botSettings.maxQuestion&&this.handleBotMessages()}hideSpinner(t){return new Promise((i=>{var e;const s=null===(e=this.el.shadowRoot)||void 0===e?void 0:e.querySelector(`#${t.id}`);if(s){const t=s.querySelector("#spinner");t&&(t.style.display="none")}i(!0)}))}async processTemplateData(t,i){await O(t,i,this.el.shadowRoot,(t=>this.hideSpinner(t)),(t=>this.renderTemplateData(t)),(t=>{this.messages=this.messages.map((i=>i.id===t.id?t:i))}),x)}async renderTemplateData(t){await D(t,this.el,this.scriptArray,this.mainObject,this.initializeScript)}async processChatData(t,i){c(t,i,this.el,(t=>this.hideSpinner(t)),(t=>{this.messages=this.messages.map((i=>i.id===t.id?t:i)),this.updateBotState()}),this.customJS,this.customStyle,this.isExpanded)}handleBotMessages(){const t=E(this.dataMode),i="v2"===t?"complete":"end_response";this.socket.on("v2"===t?"chunk":"response",(async i=>{this.resetStreamEndWatchdog();const{id:e,idChanged:s}=U(this.currentDomId,this.messages,"chatbot");this.currentDomId=e,s&&(this.messages=[...this.messages]);const o="v2"===t?i.content:i.data;requestAnimationFrame((()=>{this.ignoreChunks||(this.messages[this.messages.length-1].isLoading=!1,this.handleMessage(o,this.currentDomId))}))})),this.socket.on(i,(async i=>{if(!i)return console.error("Received empty end response payload"),void this.failTurn("Something went wrong. Please try again.");this.clearStreamEndWatchdog();const e="v2"===t?l(i):i;void 0!==e.showInput&&"boolean"==typeof e.showInput&&(this.botSettings.showInput=e.showInput),this.unreadCount++;const{id:s,idChanged:o,orphaned:n}=U(this.currentDomId,this.messages,"chatbot");this.currentDomId=s,o&&(this.messages=[...this.messages]);const a=this.isFirstExchange();e.beaconId&&sessionStorage.setItem("ai12zBeaconId",e.beaconId),a&&!this.botSettings.disableBeacon&&(J(this.dataKey,this.dataMode,e.conversationId,e.beaconId),this.hasPersistedConversationId=!0),n||this.messageReceived.emit({data:e,domId:this.currentDomId}),this.announce(this.isOpened?"New message received":"New message received while chat is minimized"),requestAnimationFrame((async()=>{var t,i,s,o,n,r,l;try{const h={element:this.el,hideSpinner:t=>{this.hideSpinner(t)},updateConversations:(t,i)=>this.updateConversations(t,i),renderSurvey:t=>this.renderSurvey(t),processTemplateData:(t,i)=>this.processTemplateData(t,i),processChatData:(t,i)=>this.processChatData(t,i),checkHighlightcode:t=>this.checkHighlightcode(t),addEventListeners:t=>this.addEventListeners(t),customStyle:this.customStyle,customJS:this.customJS,controlSettings:this.botSettings,utmConfig:null===(t=this.botSettings)||void 0===t?void 0:t.utm,conversationId:this.conversationId};if(await $({data:e,currentDomId:this.currentDomId,inputType:"bot",setMessages:t=>{this.messages=[...this.messages,t],requestAnimationFrame((()=>{setTimeout((()=>{t&&t.id&&this.hideSpinner(t).then((()=>{}))}),0)}))},setSurveyDomId:t=>{this.surveyDomId=t},setButtons:t=>{this.buttons=t},config:h}),e.liveAgent&&!this.isLiveAgent&&!this.isConnectingLiveAgent){this.liveAgentDirective=e.liveAgent,this.isConnectingLiveAgent=!0;try{await this.connectLiveChat()}finally{this.isConnectingLiveAgent=!1}}if(e.liveAgent&&!this.isLiveAgent&&!this.isConnectingLiveAgent){this.isConnectingLiveAgent=!0;try{await this.connectLiveChat()}finally{this.isConnectingLiveAgent=!1}}if(this.conversationId=e.conversationId,G(null===(i=this.botSettings)||void 0===i?void 0:i.pId,this.messages,this.conversationId,null!==(o=null===(s=this.botSettings._id)||void 0===s?void 0:s.$oid)&&void 0!==o?o:"",this.visitorID,"bot",{isMinimized:this.isMinimized,isOpened:this.isOpened,isExpanded:this.isExpanded}),this.visitorID&&a){const t=L(this.botSettings.pId,null===(n=this.botSettings._id)||void 0===n?void 0:n.$oid);sessionStorage.setItem(t,JSON.stringify({isMinimized:this.isMinimized,isOpened:this.isOpened,isExpanded:this.isExpanded,messages:this.messages,conversationId:this.conversationId,configId:null===(r=this.botSettings._id)||void 0===r?void 0:r.$oid,visitorID:this.visitorID,projectId:null===(l=this.botSettings)||void 0===l?void 0:l.pId,date:new Date}))}else this.updateBotState();this.scrollToBottom(),this.releaseSendLock(),this.currentDomId=""}catch(t){console.error("Error handling end_response:",t),this.releaseSendLock()}}))}))}updateConversations(t,i){var e,s,o,n,a,r;const l={id:this.currentDomId,text:t,isUser:!1,isLoading:!1,timestamp:(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),images:[],conversationId:this.conversationId,formModel:null!==(n=null!==(o=null===(s=null===(e=i.controlData)||void 0===e?void 0:e.data)||void 0===s?void 0:s.source)&&void 0!==o?o:i.controlData)&&void 0!==n?n:{},surveyDomId:this.surveyDomId,controlType:i.controlType,thumbsId:`${m()}`,showIcon:!i.controlType&&!this.surveyDomId,hideThumbsUpandDown:!!this.isLiveAgent,insightId:null!==(a=null==i?void 0:i.insightId)&&void 0!==a?a:null,sender:null!==(r=null==i?void 0:i.sender)&&void 0!==r?r:null,itemComponent:i};this.messages=this.messages.map((t=>t.id===this.currentDomId?l:t)),requestAnimationFrame((()=>{this.checkHighlightcode(this.currentDomId),this.currentDomId=""}))}checkHighlightcode(t=""){var i;try{if(!t)return console.warn("highlightcodeId is empty"),void(this.isProse=!0);const e=null===(i=this.el.shadowRoot)||void 0===i?void 0:i.querySelector(`#${t}`);if(!e)return console.warn(`Element with id '${t}' not found in shadowRoot`),void(this.isProse=!0);const s=e.querySelectorAll("pre");s.length>0?(e.classList.remove("prose"),import("./p-BO_7DTeV.js").then((function(t){return t.i})).then((({default:t})=>{t.configure({ignoreUnescapedHTML:!0}),s.forEach((i=>{i.dataset.highlighted?console.warn("Element previously highlighted..."):t.highlightElement(i)}))})).catch((t=>console.error("Failed to load highlight.js:",t)))):"form"!==this.messages[this.messages.length-1].controlType&&e.classList.add("prose")}catch(t){console.error("Error in highlightcode:",t),this.isProse=!0}}async handleSurveyCompletionRender(t){const i=this.messages.findIndex((i=>i.surveyDomId===t.domId));if(-1!==i){this.currentDomId=this.messages[i].id,this.surveyDomId=t.domId,this.updateConversations(t.completedHtml,{});const e=t.jsonData;this.query=e;let s=!1;try{s=await this.handleSend(t.completeText,{isHide:!0,bypassSendGuard:!0})}finally{s||console.error("Failed to send form data in finally block"),this.query===e&&(this.query="")}if(!s)return void console.error("Failed to send form data");this.formSubmitted.emit(t.sender.data),this.scrollToBottom()}else console.warn("Could not find message to update for survey completion")}addEventListeners(t){var i;const e=null===(i=this.el.shadowRoot)||void 0===i?void 0:i.querySelector(t);e&&this.buttons.forEach((t=>{const i=e.querySelector(`#${t.id}`);if(i){const e=i.getAttribute("data-original-click");if(!e)return void console.warn(`originalClickHandler is not defined for button with id: ${t.id}`);const s=e.match(/^([\w.]+)\s*\(([\s\S]*)\)$/);if(s){const e=s[1],o=s[2],n=this,a=e.includes(".")?e.split(".").pop():e,r=n[a];i.addEventListener("click",(()=>{if("function"==typeof n[a])try{switch(a){case"sendQuery":console.warn("sendQuery is deprecated, use sendMessage instead");const i=H(o);if(!i)return;i[0]=t.label,r.apply(n,i);break;case"sendMessage":const e=H(o);if(!e)return;r.apply(n,e);break;case"sendJSON":const s=H(o);if(!s)return;r.apply(n,s);break;default:console.warn(`Unknown function: ${a}`)}}catch(t){console.error(`Error invoking ${e}:`,t)}else console.warn(`Function ${a} not found on this`)}))}}}))}async socketConnection(){const t=E(this.dataMode);let i=p(this.dataMode);this.socket=h(i,{transports:"v2"===t?["websocket","polling"]:["polling"]}),await new Promise(((i,e)=>{let s=!1;const o=setTimeout((()=>{if(!s){s=!0;const t="Unable to connect to server. Please try again later.";console.error("Socket connection timed out"),this.errored.emit({message:t,code:"CONNECTION_TIMEOUT"}),e(new Error(t))}}),3e4);this.socket.on("connect",(()=>{"v2"===t?(this.socket.emit("authenticate",{api_key:this.dataKey}),this.socket.once("authenticated",(()=>{s||(s=!0,clearTimeout(o)),this.handleSocketResponse(),i()})),this.socket.once("error",(t=>{"AUTH_FAILED"!==t.code&&"AUTH_REQUIRED"!==t.code&&"AUTH_ERROR"!==t.code||(s||(s=!0,clearTimeout(o)),this.errored.emit(t),e(new Error(t.message)))}))):(s||(s=!0,clearTimeout(o)),this.handleSocketResponse(),i())}))})).catch((t=>{console.error("Socket connection failed:",t.message),this.messages.length>0&&(this.messages[this.messages.length-1].text=t.message,this.messages[this.messages.length-1].isLoading=!1,this.messages=[...this.messages]),this.isStreaming=!1,this.isSending=!1})),this.socket.on("connect_error",(t=>{this.errored.emit(t),this.announce("Unable to connect to chat server. Please try again."),console.error("Connection error:",t)})),this.socket.on("error",(()=>{this.isStreaming&&this.failTurn("Something went wrong. Please try again.")})),this.socket.on("disconnect",(()=>{this.socket.off("response"),this.socket.off("chunk"),this.isStreaming&&this.failTurn("Connection lost. Please try again.")}))}failTurn(t){this.releaseSendLock();const i=this.messages[this.messages.length-1];i&&!i.isUser&&i.isLoading&&(i.text=t,i.isLoading=!1,this.messages=[...this.messages])}invokeSocket(t){var i;let e,s;if("v2"===E(this.dataMode)){s="query";const o=sessionStorage.getItem("ai12zBeaconId");e=Object.assign({query:t,conversation_id:this.conversationId||"",base64_images:(null===(i=this.imagesBase64List)||void 0===i?void 0:i.length)>0?this.imagesBase64List:void 0,beacon_id:this.botSettings.disableBeacon?"":null!=o?o:""},this.botSettings.disableBeacon||o?{}:{beacon_data:Z()})}else s="evaluate_query",e={apiKey:this.dataKey,query:t,conversationId:this.conversationId,event:"evaluate_query",attributes:this.dataAttributes,excludeTags:this.excludeTags,includeTags:this.includeTags,base64Images:this.imagesBase64List,meta:k()};this.processDataOverride(e).then((t=>{null!=t&&(this.messageSent.emit(JSON.stringify(t)),this.socket.emit(s,t,(t=>{t&&(this.errored.emit(t),this.announce("Unable to send message. Please try again."),this.currentDomId=`chatbot-${m()}`,this.messages[this.messages.length-1].id=this.currentDomId,this.messages[this.messages.length-1].text="Error connecting to server. Please try again later.")})),this.inputEl&&(this.inputEl.value="",this.adjustHeight()),this.query="")})).catch((t=>{console.error("Error in processDataOverride:",t),this.errored.emit(t),this.releaseSendLock(),this.announce("An error occurred while sending your message.")}))}getConversationHistory(){const t=localStorage.getItem(`${this.visitorID}`);return t?JSON.parse(t):[]}loadConversation(){var t;this.showWelcomeScreen=!1;const i=localStorage.getItem(`${this.visitorID}`);i&&(this.conversationHistory=JSON.parse(i),this.conversationHistory=j(this.conversationHistory,null===(t=this.botSettings._id)||void 0===t?void 0:t.$oid,this.botSettings.pId))}startTimer(){this.timer=setInterval((()=>{this.questionCounter=0,localStorage.setItem("ai12z-bot-data",JSON.stringify({qCounter:this.questionCounter}))}),this.botSettings.autoResetTimer)}stopResponse(){this.ignoreChunks=!0,this.isStreaming=!1,this.releaseSendLock(),this.messages[this.messages.length-1].isLoading=!1}showEmptyMessageValidation(){this.emptyMessageError=!0,this.announce("Message cannot be empty. Please enter a message."),this.inputEl&&this.inputEl.focus(),setTimeout((()=>{this.emptyMessageError=!1}),3e3)}scrollToBottom(){var t;const i=null===(t=this.el.shadowRoot)||void 0===t?void 0:t.querySelector(".chat-body");i&&i.scroll({top:i.scrollHeight,behavior:"smooth"}),this.isOpened&&(this.unreadCount=0)}isNearBottom(t=150){var i;const e=null===(i=this.el.shadowRoot)||void 0===i?void 0:i.querySelector(".chat-body");return!e||e.scrollHeight-e.scrollTop-e.clientHeight<=t}scheduleAutoScroll(){this.isNearBottom()&&(this.autoScrollTimer&&clearTimeout(this.autoScrollTimer),this.autoScrollTimer=setTimeout((()=>this.scrollToBottom()),60))}checkLiveAgentBusinessHours(){var t,i,e,s,o,n;const a=null!==(e=null===(i=null===(t=this.botSettings)||void 0===t?void 0:t.liveagent)||void 0===i?void 0:i.businessHours)&&void 0!==e?e:null,r=null!==(n=null===(o=null===(s=this.botSettings)||void 0===s?void 0:s.liveagent)||void 0===o?void 0:o.timezone)&&void 0!==n?n:null;return!a||!r||R(a,r)}checkLiveAgentMode(){var t,i,e,s;const o=(null===(i=null===(t=this.botSettings)||void 0===t?void 0:t.liveagent)||void 0===i?void 0:i.providers)&&Object.keys(null===(s=null===(e=this.botSettings)||void 0===e?void 0:e.liveagent)||void 0===s?void 0:s.providers).length>0;let n=!1;try{n=this.checkLiveAgentBusinessHours()}catch(t){console.error("Error checking live agent business hours:",t)}this.isLiveAgentEnabled=o&&this.messages.length>1&&n}openEndLiveAgentDialog(){this.isToggled=!1,this.showLiveAgentEndDialog=!0}closeEndLiveAgentDialog(){this.showLiveAgentEndDialog=!1}async handleLiveAgentToolbarAction(){this.isLiveAgent?this.openEndLiveAgentDialog():await this.connectLiveChat()}confirmEndLiveAgent(){this.showLiveAgentEndDialog=!1,this.disconnectLiveChat()}disconnectLiveChat(){var t,i,e,s;this.liveAgentEventHandler.disconnectLiveAgent(),this.isLiveAgent=!1,this.liveAgentSessionId="",this.liveAgentConversationId="",this.liveAgentButtonText="Talk to a Live Agent";const o=""!==(null===(t=this.botSettings)||void 0===t?void 0:t.llmMessageOnDisconnect)?null===(i=this.botSettings)||void 0===i?void 0:i.llmMessageOnDisconnect:"The live agent has been disconnected. Please do not initiate the live agent directive again.",n=""!==(null===(e=this.botSettings)||void 0===e?void 0:e.userMessageOnDisconnect)?null===(s=this.botSettings)||void 0===s?void 0:s.userMessageOnDisconnect:"The live agent has ended the conversation.";this.query=o,this.handleSend(n,{isLiveChatEnded:!0,bypassSendGuard:!0}),this.announce("Live agent chat ended"),this.clearEvents()}removeFindingAgentPlaceholder(){var t;const i=null===(t=this.el.shadowRoot)||void 0===t?void 0:t.querySelector('[data-finding-agent="true"]');if(null==i?void 0:i.parentNode){const t=i.parentNode;t.removeChild(i),t.parentNode&&0===t.childElementCount&&t.parentNode.removeChild(t)}}registerLiveAgentListeners(){this.liveAgentListenersRegistered||(this.liveAgentListenersRegistered=!0,lt.on("FINDING_AGENT",this.findingAgent),lt.on("AGENT_EVENT",this.agentEventHandler),lt.on("AGENT_UNAVAILABLE",this.handleAgentUnavailable),lt.on("TYPING_STARTED",this.handleTypingStarted),lt.on("TYPING_STOPPED",this.handleTypingStopped),lt.on("AGENT_MESSAGE",this.agentMessageCreated),lt.on("AGENT_ERROR",this.handleAgentError),lt.on("CONVERSATION_CLOSED",this.handleAgentConversationEnded),lt.on("AGENT_SESSION_INFO",this.handleAgentSessionInfo))}clearEvents(){this.liveAgentListenersRegistered=!1,lt.off("FINDING_AGENT",this.findingAgent),lt.off("AGENT_EVENT",this.agentEventHandler),lt.off("AGENT_UNAVAILABLE",this.handleAgentUnavailable),lt.off("AGENT_MESSAGE",this.agentMessageCreated),lt.off("AGENT_ERROR",this.handleAgentError),lt.off("CONVERSATION_CLOSED",this.handleAgentConversationEnded),lt.off("TYPING_STARTED",this.handleTypingStarted),lt.off("TYPING_STOPPED",this.handleTypingStopped),lt.off("AGENT_SESSION_CREATED",this.handleAgentSessionCreated),lt.off("AGENT_SESSION_INFO",this.handleAgentSessionInfo)}async connectLiveChat(){var t,i,e,s,o,n,a,r,l,h,d,c;this.announce("Connecting to live agent"),this.clearEvents();const u=Object.keys(null!==(e=null===(i=null===(t=this.botSettings)||void 0===t?void 0:t.liveagent)||void 0===i?void 0:i.providers)&&void 0!==e?e:{});if(0===u.length)return console.error("No live agent provider found in bot settings"),void this.announce("Live agent is not configured");u.length>1&&console.warn("Multiple live agent providers found, using the first one");let v=null!==(a=null===(n=null===(o=null===(s=this.botSettings)||void 0===s?void 0:s.liveagent)||void 0===o?void 0:o.providers)||void 0===n?void 0:n[u[0]])&&void 0!==a?a:null;if(!v)return console.error("No live agent settings found for the provider",u[0]),void this.announce("Live agent settings are unavailable");if(v){let t=this.getConversationHistory().filter((t=>{var i;return t.conversationId===this.conversationId&&t.projectId===(null===(i=this.botSettings)||void 0===i?void 0:i.pId)}));const i=Object.entries(this.liveAgentDirective&&"object"==typeof this.liveAgentDirective?this.liveAgentDirective:{}).map((([t,i])=>({label:t.charAt(0).toUpperCase()+t.slice(1),value:i,displayToAgent:!0})));let e;this.isTypingIndicatorVisible=!0,v={config:v,userId:this.visitorID,conversationId:this.conversationId,messageHistory:t,extraPrechatFormDetails:i},this.liveAgentProviderName=u[0];try{e=this.checkLiveAgentBusinessHours()}catch(t){return console.error("AI12Z: unexpected error evaluating business hours — blocking live agent connection",t),this.announce("Unexpected error evaluating business hours. Live agent connection blocked."),this.addEventMessage("Unexpected error evaluating business hours. Please try again later."),void(this.isTypingIndicatorVisible=!1)}if(!e){const t=null!==(l=null===(r=v.config)||void 0===r?void 0:r.outsideBusinessHoursMessage)&&void 0!==l?l:"Our live agents are currently offline. Please try again during our business hours.";return this.addEventMessage(t),this.announce("Live agents are currently offline"),void(this.isTypingIndicatorVisible=!1)}if("liveagent"===u[0]){if(!this.liveAgentRef)return this.isTypingIndicatorVisible=!1,console.error("LiveAgent reference is not set"),void this.announce("Live agent is currently unavailable");await this.liveAgentRef.startChat(),this.isLiveAgent=!0,this.liveAgentButtonText="End Live Agent chat",this.announce("Connected to live agent")}else{const t=Number(null===(h=null==v?void 0:v.config)||void 0===h?void 0:h.maxWaitTime),i=1e3*(Number.isFinite(t)&&t>=5?t:300);this.registerLiveAgentListeners();try{await this.liveAgentEventHandler.connectToLiveAgent(u[0],v)}catch(t){return console.error("Live agent connection error:",t),this.isTypingIndicatorVisible=!1,this.liveAgentSessionId="",this.liveAgentConversationId="",this.updateBotState(),this.addEventMessage("Issue connecting to live agent. Please try again later."),this.announce("Issue connecting to live agent. Please try again later."),this.liveAgentEventHandler.disconnectLiveAgent(),void this.clearEvents()}let e,s=()=>{};try{await new Promise(((t,o)=>{s=()=>{this.handleAgentSessionCreated(),t("SUCCESS")},lt.on("AGENT_SESSION_CREATED",s),e=setTimeout((()=>o(new Error("TIMEOUT"))),i)}))}catch(t){this.liveAgentSessionId="",this.liveAgentConversationId="",this.isLiveAgent=!1,this.isTypingIndicatorVisible=!1;const i=null!==(c=null===(d=v.config)||void 0===d?void 0:d.maxWaitMessage)&&void 0!==c?c:"Sorry, no agents are available at the moment.";this.removeFindingAgentPlaceholder(),this.addEventMessage(i),this.liveAgentEventHandler.disconnectLiveAgent(),this.clearEvents(),this.updateBotState(),this.announce("Agents are not available at this time.")}finally{e&&clearTimeout(e),lt.off("AGENT_SESSION_CREATED",s)}}}}handleMessageKeyNav(t,i){var e,s;if("ArrowDown"===t.key){t.preventDefault();const s=Math.min(this.messages.length-1,i+1);this.focusedIndex=s,null===(e=this.messageRefs[s])||void 0===e||e.focus()}else if("ArrowUp"===t.key){t.preventDefault();const e=Math.max(0,i-1);this.focusedIndex=e,null===(s=this.messageRefs[e])||void 0===s||s.focus()}}async updateBotState(){var t,i,e,s;const o=L(this.botSettings.pId,null===(t=this.botSettings._id)||void 0===t?void 0:t.$oid);let n=await T(o);if(n||(n=N(this.botSettings.pId,null===(i=this.botSettings._id)||void 0===i?void 0:i.$oid)),"string"==typeof n)try{n=JSON.parse(n)}catch(t){console.error("AI12Z: Failed to parse bot state from sessionStorage:",t)}Array.isArray(n)&&(n=n.find((t=>{var i;return t.projectId===(null===(i=this.botSettings)||void 0===i?void 0:i.pId)}))||null);const a={isMinimized:this.isMinimized,isOpened:this.isOpened,isExpanded:this.isExpanded,messages:this.messages,conversationId:this.conversationId,projectId:null===(e=this.botSettings)||void 0===e?void 0:e.pId,configId:null===(s=this.botSettings)||void 0===s?void 0:s._id.$oid,newChat:0===this.messages.length,isLiveAgent:this.isLiveAgent,liveAgentProviderName:this.liveAgentProviderName,liveAgentSessionId:this.liveAgentSessionId,liveAgentConversationId:this.liveAgentConversationId};0===this.messages.length&&(this.conversationId="");try{sessionStorage.setItem(o,JSON.stringify(a)),this.botSettings.cookies&&ft(this.botSettings.subDomain)&&mt(o,function(t,i){var e={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&i.indexOf(s)<0&&(e[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(s=Object.getOwnPropertySymbols(t);o<s.length;o++)i.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(t,s[o])&&(e[s[o]]=t[s[o]])}return e}(a,["liveAgentSessionId","liveAgentConversationId"]),{domain:this.botSettings.subDomain})}catch(t){console.error("AI12Z: Failed to update bot state in sessionStorage:",t)}}skipTo(t){var i;const e=null===(i=this.el.shadowRoot)||void 0===i?void 0:i.querySelector("#"+t);e&&e.focus()}render(){var t,i,e,s,o,n,l,h,d,c,u,v,p,g,m,f,b,y,w,x,S,C;return this.canRender?a("div",{lang:"en"},a("div",{class:"skip-links "+(this.isOpened?"visible":"hidden")},a("a",{class:"skip-link",href:"#main-content",onClick:()=>this.skipTo("main-content")},"Skip to main content"),a("a",{class:"skip-link",href:"#message-input",onClick:()=>{var t;null===(t=this.inputEl)||void 0===t||t.focus()}},"Skip to message input")),"v1"!==this.botSettings.botVersion&&this.isRendered&&a("div",{class:`pt-0 show-grid ${this.isAnimated?"transition ease-out duration-300":""} layout ${this.isOpened?"is-open":""} ${this.isExpanded?"is-expanded":""} search-flex`,style:{gridTemplateColumns:`0fr minmax(${null!==(t=this.botSettings.minWidth)&&void 0!==t?t:"340px"}, ${null!==(i=this.botSettings.maxWidth)&&void 0!==i?i:"375px"}) 0fr`,paddingTop:null!==(s=null===(e=this.botSettings)||void 0===e?void 0:e.paddingTop)&&void 0!==s?s:"96px"}},a("div",{class:"modal-overlay",role:"none","aria-label":"Close Modal",style:{display:this.isExpanded&&this.isOpened?"grid":"none",opacity:this.isExpanded&&this.isOpened?"1":"0",pointerEvents:this.isExpanded&&this.isOpened?"all":"none"}}),a("div",{class:"modal","data-testid":"modal","aria-hidden":"false",role:"dialog","aria-modal":"true",tabindex:"-1",style:{display:this.isOpened?"grid":"none",opacity:this.isOpened?"1":"0",transform:this.isOpened?"none":"translateY(100%)"}},a("header",{role:"banner"},a("div",{class:"flex bg-white overflow-hidden border-b border-gray-90 border-solid md:pl-3 pl-4 justify-end md:rounded-t-xl items-center toolbar"},a("div",{class:"flex gap-1 toolbar-overflow-actions"},this.isLiveAgentEnabled&&(null===(l=null===(n=null===(o=this.botSettings)||void 0===o?void 0:o.liveagent)||void 0===n?void 0:n.providers)||void 0===l?void 0:l.liveagent)&&a("live-agent-chat",{config:null===(c=null===(d=null===(h=this.botSettings)||void 0===h?void 0:h.liveagent)||void 0===d?void 0:d.providers)||void 0===c?void 0:c.liveagent,ref:t=>this.liveAgentRef=t}),!this.showHistory&&a("button",{class:"rounded-full flex items-center justify-center disabled:cursor-not-allowed bg-transparent hover:bg-blue-95 disabled:bg-transparent disabled:hover:bg-transparent h-6 w-6 bot-btn-primary",tabindex:"0","aria-label":"options menu","aria-haspopup":"menu","aria-expanded":this.isToggled?"true":"false","aria-controls":"dropdown-menu",onClick:t=>{t.preventDefault(),t.stopPropagation(),this.toggleBot(t)}},a("i",{class:"block wes-icon--loading text-body2 modal-toolbar-icon ",title:"Options Menu"},a("svg",{viewBox:"0 0 24 24",id:"align-left-2","data-name":"Flat Line",xmlns:"http://www.w3.org/2000/svg",class:"icon flat-line",fill:"currentColor","aria-hidden":"true"},a("g",{id:"SVGRepo_bgCarrier","stroke-width":"0"}),a("g",{id:"SVGRepo_tracerCarrier","stroke-linecap":"round","stroke-linejoin":"round"}),a("g",{id:"SVGRepo_iconCarrier"},a("path",{id:"primary",d:"M3,12H17M3,6H21M3,18H13",style:{fill:"none",stroke:"currentColor"}}))))),this.showHistory&&a("button",{class:"w-6 h-6 back-btn bot-btn-primary",tabindex:"0","aria-label":"Back",onClick:t=>{t.preventDefault(),t.stopPropagation(),this.showHistory=!1,this.showWelcomeScreen=!0,this.isOpened=!0,this.isMinimized=!1,this.isAnimated=!0}},a("i",{title:"Back"},a("svg",{viewBox:"0 0 200 200","data-name":"Layer 1",id:"Layer_1",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20","aria-hidden":"true"},a("g",{id:"SVGRepo_bgCarrier","stroke-width":"0"}),a("g",{id:"SVGRepo_tracerCarrier","stroke-linecap":"round","stroke-linejoin":"round"}),a("g",{id:"SVGRepo_iconCarrier"},a("title",null),a("path",{d:"M160,89.75H56l53-53a9.67,9.67,0,0,0,0-14,9.67,9.67,0,0,0-14,0l-56,56a30.18,30.18,0,0,0-8.5,18.5c0,1-.5,1.5-.5,2.5a6.34,6.34,0,0,0,.5,3,31.47,31.47,0,0,0,8.5,18.5l56,56a9.9,9.9,0,0,0,14-14l-52.5-53.5H160a10,10,0,0,0,0-20Z"}))))),a("hamburger-menu",{isToggled:this.isToggled,botSettings:this.botSettings,messages:this.messages,liveAgentButtonText:this.liveAgentButtonText,isLiveAgentEnabled:this.isLiveAgentEnabled,onHamburgerMenuClick:t=>{this.menuClick(t.detail)},onHandleByLiveAgent:()=>{this.handleLiveAgentToolbarAction()},onToggledChange:t=>{this.isToggled=t.detail}})),(null===(u=this.botSettings)||void 0===u?void 0:u.botLogo)&&a("img",{src:null===(v=this.botSettings)||void 0===v?void 0:v.botLogo,class:"w-8 h-8 rounded-lg",alt:"Bot Logo"}),a("h2",{class:"flex-1 pl-2 heading text-body1"},null===(p=this.botSettings)||void 0===p?void 0:p.botName),a("div",{class:"buttons flex gap-2 p-[10px]"},this.isLiveAgent&&a("button",{"aria-label":"End Live Agent",title:"End Live Agent",onClick:()=>this.openEndLiveAgentDialog()},a("svg",{xmlns:"http://www.w3.org/2000/svg",height:"24px",viewBox:"0 -960 960 960",width:"24px",fill:"#151313"},a("path",{d:"m136-304-92-90q-12-12-12-28t12-28q88-95 203-142.5T480-640q118 0 232.5 47.5T916-450q12 12 12 28t-12 28l-92 90q-11 11-25.5 12t-26.5-8l-116-88q-8-6-12-14t-4-18v-114q-38-12-78-19t-82-7q-42 0-82 7t-78 19v114q0 10-4 18t-12 14l-116 88q-12 9-26.5 8T136-304Zm104-198q-29 15-56 34.5T128-424l40 40 72-56v-62Zm480 2v60l72 56 40-38q-29-26-56-45t-56-33Zm-480-2Zm480 2Z"}))),this.messages.length>0&&a("button",{class:"rounded-full flex items-center justify-center disabled:cursor-not-allowed bg-transparent hover:bg-blue-95 disabled:bg-transparent disabled:hover:bg-transparent h-6 w-6 bot-btn-primary",tabindex:"0",onClick:t=>{t.preventDefault(),this.messages=[],this.isOpened=!0,this.isMinimized=!1,this.showWelcomeScreen=!0,this.showHistory=!1,this.updateBotState(),this.checkLiveAgentMode()},"aria-label":"Start New Conversation",title:"Start New Conversation"},a("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",width:"20",height:"20",class:"modal-toolbar-icon","aria-hidden":"true"},a("circle",{cx:"4",cy:"4",r:"1.5"}),a("circle",{cx:"10",cy:"4",r:"1.5"}),a("circle",{cx:"16",cy:"4",r:"1.5"}),a("circle",{cx:"4",cy:"10",r:"1.5"}),a("circle",{cx:"10",cy:"10",r:"1.5"}),a("circle",{cx:"16",cy:"10",r:"1.5"}),a("circle",{cx:"4",cy:"16",r:"1.5"}),a("circle",{cx:"10",cy:"16",r:"1.5"}),a("circle",{cx:"16",cy:"16",r:"1.5"}))),a("button",{class:"rounded-full flex items-center justify-center disabled:cursor-not-allowed bg-transparent hover:bg-blue-95 disabled:bg-transparent disabled:hover:bg-transparent h-6 w-6 bot-btn-primary",tabindex:"0",onClick:t=>{t.preventDefault(),this.showShortcutsDialog=!0},"aria-label":"Keyboard Shortcuts",title:"Keyboard Shortcuts (Press ? for help)"},a("i",{class:"wes-block wes-icon--loading wes-text-body2 modal-toolbar-icon",title:"Keyboard Shortcuts"},a("svg",{viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true"},a("path",{d:"M3 5C3 3.89543 3.89543 3 5 3H19C20.1046 3 21 3.89543 21 5V14C21 15.1046 20.1046 16 19 16H13L9 21V16H5C3.89543 16 3 15.1046 3 14V5Z",stroke:"currentColor","stroke-width":"2"}),a("circle",{cx:"12",cy:"10",r:"1",fill:"currentColor"}),a("path",{d:"M9 10C9 8.34315 10.3431 7 12 7",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"})))),a("button",{class:"rounded-full flex items-center justify-center disabled:cursor-not-allowed bg-transparent hover:bg-blue-95 disabled:bg-transparent disabled:hover:bg-transparent h-6 w-6 hidden md:flex bot-btn-primary",tabindex:"0",onClick:()=>{this.isExpanded=!this.isExpanded,this.isAnimated=!0,this.updateBotState()},"aria-label":"Collapse Bot to Side Panel","aria-expanded":this.isExpanded?"true":"false","aria-controls":"settings-panel"},a("i",{class:"wes-block wes-icon--loading wes-text-body2 modal-toolbar-icon",title:"Collapse Bot to Side Panel"},this.isExpanded&&a("svg",{viewBox:"0 0 32 32",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor","aria-hidden":"true"},a("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M18.215 14.7076H27.692C28.3074 14.7076 28.492 14.0307 27.9997 13.5383L24.9843 10.4614L30.5228 4.86149C30.8305 4.5538 30.8305 3.99995 30.5228 3.69226L28.2459 1.41536C27.9382 1.16921 27.4459 1.16921 27.0767 1.4769L21.5381 7.01532L18.3997 3.99995C17.9073 3.50765 17.2304 3.69226 17.2304 4.30764V13.7845C17.2304 14.2153 17.7843 14.7076 18.215 14.7076ZM13.7847 17.2308H4.30766C3.69227 17.2308 3.50765 17.9077 3.99996 18.4L7.01537 21.4769L1.47686 27.0769C1.16917 27.3846 1.16917 27.9384 1.47686 28.2461L3.75381 30.523C4.0615 30.8307 4.55381 30.8307 4.92305 30.523L10.5231 24.923L13.6616 27.9384C14.0924 28.4923 14.7693 28.3076 14.7693 27.6923V18.2769C14.7693 17.8462 14.2154 17.2308 13.7847 17.2308Z"})),!this.isExpanded&&a("svg",{viewBox:"0 0 32 32",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor","aria-hidden":"true"},a("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M30.0308 1.23071H20.4923C19.8769 1.23071 19.6923 1.78455 20.1846 2.27686L23.2 5.29222L17.6615 10.8306C17.3538 11.1383 17.3538 11.6306 17.6615 11.9999L19.9384 14.2768C20.2461 14.5845 20.7384 14.5845 21.1077 14.2768L26.7077 8.67681L29.7231 11.6922C30.2154 12.1845 30.7692 11.9999 30.7692 11.3845V1.90763C30.7692 1.5384 30.4 1.23071 30.0308 1.23071ZM2.15379 30.7692H11.6307C12.2461 30.7692 12.4307 30.0923 11.9384 29.6L8.92303 26.5231L14.4615 20.9231C14.7692 20.6154 14.7692 20.0616 14.4615 19.7539L12.1846 17.477C11.8769 17.1693 11.3846 17.1693 11.0153 17.477L5.47687 23.0154L2.39995 20C1.8461 19.5077 1.23071 19.6923 1.23071 20.3077V29.7846C1.23071 30.2153 1.72302 30.7692 2.15379 30.7692Z"})))),a("button",{class:"rounded-full flex items-center justify-center disabled:cursor-not-allowed bg-transparent hover:bg-blue-95 disabled:bg-transparent disabled:hover:bg-transparent h-6 w-6 bot-btn-primary","data-testid":"modal-minimize",tabindex:"0","aria-label":"Minimize",onClick:()=>{this.syncBodyScrollLock(!1),this.isOpened=!1,this.isContent=!(!this.isExpanded||!this.botSettings.isExpanded),this.isMinimized=!this.isExpanded||!this.botSettings.isExpanded,this.isAnimated=!1,this.updateScreenSize(),this.updateBotState(),this.announce("Chat minimized"),this.minimize.emit("minimize")}},a("i",{class:"block wes-icon--loading text-body2 modal-toolbar-icon",title:"Minimize Bot"},a("svg",{viewBox:"0 0 26 26",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor","aria-hidden":"true"},a("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M25 24.25C25 24.65 24.65 25 24.25 25H1.75C1.35 25 1 24.65 1 24.25V22.75C1 22.35 1.35 22 1.75 22H24.25C24.65 22 25 22.35 25 22.75V24.25Z"}))))))),a("div",{class:"flex-1 flex flex-col main",role:"main","aria-labelledby":"chat-main-heading",id:"main-content",tabindex:"-1"},a("h1",{id:"chat-main-heading",class:"sr-only"},"Chat"),a("div",{class:"h-full flex flex-col chat-body"},a("div",{class:"px-5 flex-[1_1_0] min-h-[calc(100%-1px)] flex flex-col gap-y-3 @md:px-3 messages-container",role:"region","aria-labelledby":"messages-region-heading"},a("h2",{id:"messages-region-heading",class:"sr-only"},"Messages"),this.showWelcomeScreen&&a("div",{class:"@md:px-6 pb-3 @md:pb-7 @md:pt-8 pt-5 text-display5",innerHTML:null===(m=null===(g=this.botSettings)||void 0===g?void 0:g.welcome)||void 0===m?void 0:m.message}),this.messages.length>0&&!this.showHistory&&this.messages.map(((t,i)=>{var e,s,o,n;return"system"===t.type?a("div",{class:"flex justify-center pb-3 message-item",role:"listitem",tabindex:-1,ref:t=>this.messageRefs[i]=t,"aria-label":t.text},a("span",{class:"text-[10px] font-medium text-gray-500 tracking-wide border-b border-gray-200 py-1 px-3 text-center"},t.text)):a("div",{class:`flex pb-3 gap-x-2 @md:gap-x-3 \n ${t.isUser?"self-end":""}\n ${t.isUser?"justify-end":""} end-user-message message-item`,style:{opacity:"1",transform:"none"},role:"listitem",tabindex:i===this.focusedIndex?0:-1,onKeyDown:t=>this.handleMessageKeyNav(t,i),ref:t=>this.messageRefs[i]=t,"aria-label":"Message from "+(t.isUser?"User":"Bot")},t.isUser&&!t.isHide&&a("div",{class:"flex flex-col items-end"},a("div",{"data-testid":"message",class:"break-words @md:text-body2 box-border @md:pr-4 flex-1 rounded-lg py-2 px-4 user-msg text-body3",innerHTML:t.text,id:t.id,"aria-live":"polite","aria-atomic":"false","aria-label":t.text,role:"log"},null===(e=null==t?void 0:t.images)||void 0===e?void 0:e.map((t=>a("img",{src:t,class:"thumbnail",alt:"thumbnail images"})))),a("div",{class:"text-gray-30 pt-2 text-right text-body4"},"Sent ",t.timestamp)),!t.isUser&&a("div",{class:"avatar-column"},a("chat-avatar",{id:`la${t.id}`,senderType:(null==t?void 0:t.sender)?"agent":"bot",avatarUrl:null===(s=this.botSettings)||void 0===s?void 0:s.botAvatar})),!t.isUser&&a("div",{class:"flex flex-col",style:{width:"100%"}},a("div",{"data-testid":"message",class:{prose:"form"!==t.controlType,"transition-all":!0,"duration-300":!0,"opacity-100":this.isProse,"opacity-90":!this.isProse,"max-w-full break-words @md:text-body2 box-border @md:pr-4 flex-1 rounded-lg text-gray-30 pr-2 text-body3":!0},innerHTML:t.text,id:t.id},t.isLoading&&a("div",{class:"w-full rounded-md",id:"spinner"},a("div",{class:"flex animate-pulse space-x-4"},a("div",{class:"flex-1 space-y-3 py-1"},a("div",{class:"h-4 rounded bg-gray-200"}),a("div",{class:"space-y-3"},a("div",{class:"grid grid-cols-3 gap-4"},a("div",{class:"col-span-2 h-4 rounded bg-gray-200"}),a("div",{class:"col-span-1 h-4 rounded bg-gray-200"})),a("div",{class:"h-4 rounded bg-gray-200"})))))),""!==t.text&&t.showIcon&&(null===(o=this.botSettings.showMessageIcons)||void 0===o||o)&&a("interaction-buttons",{message:t,chatArray:this.messages,currentIndex:i,dataKey:this.dataKey,dataMode:this.dataMode,voice:this.voice,voiceType:this.voiceType,source:"bot",conversationId:this.conversationId,projectId:(null===(n=this.botSettings)||void 0===n?void 0:n.pId)||""}),a("div",{class:"text-gray-30 pt-2 text-body4"},this.botSettings.botName," • ",t.timestamp)))})),this.showHistory&&a("chatbot-history",{chatList:this.conversationHistory,botName:null===(f=this.botSettings)||void 0===f?void 0:f.botName,styles:this.customStyle,scripts:this.customJS}),a("div",{class:"h-px pt-2px",style:{overflowAnchor:"auto"}})),a("div",{role:"status","aria-live":"polite","aria-atomic":"true",class:"sr-only"},this.announceMessage)))),!1!==(null===(b=this.botSettings)||void 0===b?void 0:b.showInput)&&a("form",{"data-testid":"user-input",class:`relative pointer-events-auto ${this.isOpened?"p-2.5":""} searchform user-input`,"aria-label":"Message Area","aria-hidden":"false",style:{opacity:this.isMinimized?"0":"1",transform:"translateX(0)",pointerEvents:this.isMinimized?"none":"auto"}},!this.isOpened&&a("div",{class:`absolute right-4 md:right-0 border-2 border-white border-solid rounded-full ${this.isContent?"":"top-0"} minimize-input`},a("button",{class:"rounded-full flex items-center justify-center disabled:cursor-not-allowed bg-gray-500 bg-opacity-60 hover:bg-opacity-80 h-5 w-5 bot-btn-primary","aria-label":"Minimized to fab Bot",tabindex:"0",onClick:t=>{t.preventDefault();const i=!this.isMinimized,e=!i;this.syncBodyScrollLock(e),this.isMinimized=i,this.isOpened=e,this.updateBotState()}},a("i",{class:"block ai-minimize-icon ai-text-caption",title:"Minimize Bot"},a("svg",{xmlns:"http://www.w3.org/2000/svg",height:"52",width:"52",viewBox:"0 0 520 520",fill:"#fff","aria-hidden":"true"},a("path",{d:"M500 275c0 8-7 15-15 15H35c-8 0-15-7-15-15v-30c0-8 7-15 15-15h450c8 0 15 7 15 15z"}))))),a("fieldset",{class:"flex flex-col @md:mx-0 @md:rounded-t-xl transition-colors "+(this.isMinimized&&!this.isExpanded?"":"p-4 user-input-fieldset")},!this.isExpanded&&this.isOpened&&0===this.messages.length&&a("privacy-modal",{show:this.showPrivacy,message:this.botSettings.privacyTemplate}),a("div",{class:"flex-1 align-bottom"},a("div",{"aria-hidden":this.isTypingIndicatorVisible?"false":"true",class:"flex items-center justify-center w-full "+(this.isTypingIndicatorVisible?"h-12 opacity-100":"h-0 opacity-0 pointer-events-none")},a("typing-indicator",null)),a("div",{class:"grow-wrap show-grid after:whitespace-pre-wrap after:invisible relative","data-replicated-value":"","aria-disabled":"false"},this.botSettings.imageUpload&&a("div",{"aria-disabled":"true",class:`absolute flex items-center left-0 bottom-0 h-full pl-4 pr-2 ${this.hideAllButtons?"hidden":""} agent-input-icon`},a("button",{class:"plus-icon bot-plus-icon bot-btn-primary",tabindex:"0","aria-label":"Add Image",onClick:t=>{t.stopPropagation(),t.preventDefault(),this.showMenu=!this.showMenu}},a("i",{class:"plus-icon bot-plus-icon wes-block wes-text-body1",title:"Add Image"},a("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",width:"20",height:"20","aria-hidden":"true"},a("path",{d:"M10.75 4.75a.75.75 0 0 0-1.5 0v4.5h-4.5a.75.75 0 0 0 0 1.5h4.5v4.5a.75.75 0 0 0 1.5 0v-4.5h4.5a.75.75 0 0 0 0-1.5h-4.5v-4.5Z"})))),a("div",{class:"absolute bottom-6 left-0 w-44 bg-white rounded-lg shadow-lg transition-all duration-300 ease-in-out z-10\n "+(this.showMenu?"opacity-100 scale-100 pointer-events-auto":"opacity-0 scale-90 pointer-events-none")},a("ul",{class:"space-y-2",ref:t=>this.plusIconRef=t},a("li",{class:"px-4 py-2 hover:bg-gray-100 cursor-pointer flex",onClick:()=>{this.showMenu=!1}},a("image-uploader",{maxImages:10,images:this.imagesBase64List,targetElement:this.inputEl,onImagesChange:t=>{this.errorMessage="",this.showErrorMessage=!1,this.imagesBase64List=[...t.detail]},onImageUploadError:t=>{this.errorMessage=t.detail,this.showErrorMessage=!0,this.announce(t.detail||"Image upload failed")},ref:t=>this.imageUploaderRef=t}))))),a("div",{class:"textarea"},this.imagesBase64List.length>0&&a("div",{class:"flex flex-wrap gap-2 mx-1 mt-2.5 mb-1"},this.imagesBase64List.map(((t,i)=>a("div",{class:"image-Container sc-ai12z-input-form",key:i},a("img",{src:t,style:{width:"70px",height:"50px",borderRadius:"12px"},alt:"uploaded image"}),a("span",{class:"delete-image sc-ai12z-input-form cursor-pointer ml-1",onClick:()=>{this.imagesBase64List=this.imagesBase64List.filter(((t,e)=>e!==i)),this.imageUploaderRef&&"function"==typeof this.imageUploaderRef.removeImageAtIndex&&this.imageUploaderRef.removeImageAtIndex(i),this.imagesBase64List=[...this.imagesBase64List]}},"×"))))),a("textarea",{id:"message-input","aria-invalid":this.emptyMessageError,"aria-describedby":[this.emptyMessageError?"empty-message-error":"","message-hint",0===this.messages.length?"input-enter-tip":""].filter(Boolean).join(" "),"aria-placeholder":this.isLiveAgent?"Type a message to the agent...":""!==(null===(y=this.botSettings)||void 0===y?void 0:y.botPlaceholderText)?null===(w=this.botSettings)||void 0===w?void 0:w.botPlaceholderText:"Ask me anything","aria-label":"Type your message here",class:"resize-none overflow-hidden text-ellipsis focus:outline-none w-full custom-input "+(this.hideAllButtons?"hidden":""),"data-testid":"user-input-textarea",rows:this.rowCount,name:"userMessage",placeholder:this.isLiveAgent?"Type a message to the agent...":""!==(null===(x=this.botSettings)||void 0===x?void 0:x.botPlaceholderText)?null===(S=this.botSettings)||void 0===S?void 0:S.botPlaceholderText:"Ask me anything",ref:t=>this.inputEl=t,onKeyUp:()=>{this.adjustHeight()},onKeyDown:t=>{this.handleKeyDown(t),"Enter"!==t.key||t.shiftKey||(this.syncBodyScrollLock(!0),this.isOpened=!0)},onPaste:t=>{this.handlePaste(t)}}),a("span",{id:"message-hint",class:"sr-only"},"Press Enter to send, Shift+Enter for new line")),this.botSettings.enableMic&&a("div",{class:"absolute bottom-0 "+(this.hideAllButtons?"w-full":"right-8")},a("audio-recorder",{"component-type":"bot",onStartRecord:()=>{this.hideAllButtons=!0},onStopRecord:()=>{this.hideAllButtons=!1},onSendTranscript:t=>{setTimeout((()=>{this.inputEl&&(this.inputEl.value=t.detail,this.adjustHeight(),this.showSubmit=!0)}),1e3)},style:{width:this.hideAllButtons?"100%":"10%"}})),a("div",{class:"absolute right-0 bottom-0 "+(this.hideAllButtons?"hidden":"")},!this.isStreaming&&a("button",{class:"text-white transition rounded-full p-1.5 self-center btn-bg-color bot-btn-primary","aria-label":"Send Message",tabindex:"0",id:"message-submit",onClick:t=>{var i,e;if(t.preventDefault(),""===(null===(i=this.inputEl)||void 0===i?void 0:i.value.trim())&&this.imagesBase64List&&0===this.imagesBase64List.length)return this.emptyMessageError=!0,this.announce("Message cannot be empty. Please enter a message."),this.inputEl&&this.inputEl.focus(),void setTimeout((()=>{this.emptyMessageError=!1}),3e3);this.syncBodyScrollLock(!0),this.isOpened=!0,this.handleSend(null===(e=this.inputEl)||void 0===e?void 0:e.value)}},a("i",{class:"block ai-icon text-body1",title:"Send Message"},a("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",fill:"currentColor",class:"size-6","aria-hidden":"true"},a("path",{"fill-rule":"evenodd",d:"M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z","clip-rule":"evenodd"})))),this.isStreaming&&a("button",{class:"text-white transition rounded-full p-1.5 self-center btn-bg-color bot-btn-primary","aria-label":"Stop Streaming",tabindex:"0",id:"message-submit",onClick:t=>{t.preventDefault(),this.syncBodyScrollLock(!0),this.isOpened=!0,this.stopResponse()}},a("i",{class:"block text-body1",title:"Stop Streaming"},a("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",class:"size-6","aria-hidden":"true"},a("path",{d:"M4.5 5.75C4.5 5.05964 5.05964 4.5 5.75 4.5H14.25C14.9404 4.5 15.5 5.05964 15.5 5.75V14.25C15.5 14.9404 14.9404 15.5 14.25 15.5H5.75C5.05964 15.5 4.5 14.9404 4.5 14.25V5.75Z"})))))),this.isExpanded&&!this.isOpened&&a("privacy-modal",{show:this.showPrivacy,message:this.botSettings.privacyTemplate}),0===this.messages.length&&a("div",{id:"input-enter-tip",role:"tooltip",class:"enter-tip"},"Tip: Press Enter to send, Shift+Enter for new line"),this.emptyMessageError&&a("div",{class:"error-message-container"},a("span",{id:"empty-message-error",class:"error-msg",role:"alert"},"Message cannot be empty. Please enter a message to send.")),this.showErrorMessage&&a("p",{class:"error-msg",innerHTML:this.errorMessage}),this.botSettings.buttons&&this.botSettings.buttons.length>0&&!this.isOpened&&a("div",{class:"bot-buttons-container flex flex-wrap gap-2 mt-2.5 mb-1"},this.botSettings.buttons.map(((t,i)=>a("button",{key:i,class:"px-4 py-2 ai12z-btn",onClick:i=>{i.preventDefault(),this.syncBodyScrollLock(!0),this.isOpened=!0,this.isContent=!1,this.handleSend(t.label)}},t.label))))))),a("div",{class:"pointer-events-auto fixed right-7 whitespace-nowrap transition-transform duration-300 ease-in-out fab",style:{opacity:this.isMinimized?"1":"0",transform:this.isMinimized?"translateX(0)":"translateX(-100%)",pointerEvents:this.isMinimized?"auto":"none",transformOrigin:"50% 50% 0px"},onClick:()=>{this.openChat()}},this.isBot&&a("slot",{name:"bot"}),!this.isBot&&a("button",{class:"rounded-full flex cursor-pointer items-center pr-[14px] md:gap-x-3 focus:outline focus:outline-2 focus:outline-offset-2 focus:outline-blue-focused bot-btn-primary",tabindex:"0","aria-label":"open Bot"},a("div",{class:"w-10 h-10 flex items-center justify-center bg-white rounded-full border relative"},this.botSettings.botLaunchIcon&&a("img",{src:this.botSettings.botLaunchIcon,alt:"bot icon",class:"w-8 h-8 rounded-lg"}),!this.botSettings.botLaunchIcon&&a("svg",{viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",stroke:"#2095ae","aria-hidden":"true"},a("g",{"stroke-width":"0"}),a("g",{"stroke-linecap":"round","stroke-linejoin":"round"}),a("g",null," ",a("path",{d:"M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z",stroke:"#2095ae","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})," "))),a("span",{class:"bot-name"}," ",null===(C=this.botSettings)||void 0===C?void 0:C.botName," ")))),a("keyboard-shortcuts-dialog",{show:this.showShortcutsDialog,shortcuts:this.shortcuts,onCloseDialog:()=>{this.showShortcutsDialog=!1}}),a("delete-confirmation-modal",{show:this.showLiveAgentEndDialog,dialogTitle:"End live agent chat?",message:"You are about to end the current live agent conversation. You can continue chatting with the bot after ending it.",confirmButtonText:"End",onConfirmDelete:()=>{this.confirmEndLiveAgent()},onCancelDelete:()=>{this.closeEndLiveAgentDialog()}})):a(r,null,a("span",{style:{display:"none"}},"Failed to load ai12z bot control due to insufficient fund"))}get el(){return this}static get watchers(){return{dataKey:[{onDataKeyChange:0}],dataMode:[{onDataModeChange:0}]}}static get style(){return':host{font-family:var(--ai12zBot-v2-font-family) !important;font-size:var(--ai12zBot-v2-font-size) !important;color:var(--ai12zBot-v2-font-color, black);text-align:var(--ai12zBot-v2-text-align, left)}.chat-body{height:100%;overflow-y:auto;display:flex;flex-direction:column;gap:10px;overflow-x:hidden}.chat-body::-webkit-scrollbar{width:5px;height:5px;}.chat-body::-webkit-scrollbar-thumb{background-color:#888;border-radius:10px;}.message{padding:10px;border-radius:15px;font-size:14px;line-height:1.4;word-wrap:break-word}span.prose{font-size:14px;}.image-Container{position:relative;display:inline-block;margin-right:10px}.delete-image{opacity:3;position:absolute;right:3px;top:0;cursor:pointer;line-height:10px}.ai12zBtn{background-color:var(--ai12zBot-v2-button-background) !important;color:var(--ai12zBot-v2-button-font-color);padding:5px 10px;border:none;border-radius:5px;cursor:pointer;text-decoration:none;margin:5px}.ai12z-btn{background-color:var(--ai12zBot-v2-button-background) !important;color:var(--ai12zBot-v2-button-font-color);padding:5px 10px;border:none;border-radius:5px;cursor:pointer;text-decoration:none;margin:5px}.custom-privacy{color:var(--ai12z-bot-privacy-color);padding-bottom:10px;padding-left:5px;margin-top:auto;}@media (max-width: 768px){.hide-chatbot{display:none !important}}:host{--wes-c-icon-color:#fff;--fab-bottom:26px;--xsf-ai12z-zindex-isexpanded-10:20020;--ai-toolbar-icon-color:#2095ae;--xsf-ai12z-zindex-0:19979;--xsf-ai12z-zindex-10:19989;--xsf-ai12z-fab-bottom:26px}.modal-overlay{position:absolute;height:100%;width:100%;z-index:var(--xsf-ai12z-zindex-0);background-color:#2e2e2e99}.layout{pointer-events:none;position:fixed;inset:0;height:100dvh;width:99dvw;justify-content:flex-end;grid-template-rows:auto 1fr auto;grid-template-areas:"left toolbar right" "left main right" "left footer right";padding-top:96px;transition-property:grid-template-columns, padding-top;z-index:19979}.layout.is-open .modal{pointer-events:auto}.layout.is-expanded ai12z-bot{pointer-events:auto}.layout.is-open.is-expanded .modal{border-top-left-radius:12px;border-top-right-radius:12px;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);z-index:var(--xsf-ai12z-zindex-isexpanded-10)}.layout.is-open .user-input-fieldset{background-image:none;padding:0px;background:none}.layout.is-expanded .user-input-fieldset{border-top-left-radius:12px;border-top-right-radius:12px}.layout.is-open .grow-wrap>.textarea,.layout.is-open .grow-wrap>button,.layout.is-open .grow-wrap:after{border-color:var(--ai12zBot-v2-searchbar-open-border-color);}.layout.is-expanded .grow-wrap:after{display:none}.layout.is-open.is-expanded .user-input{z-index:var(--xsf-ai12z-zindex-isexpanded-10)}.layout.is-open .user-input{z-index:var(--xsf-ai12z-zindex-10)}.text-body2{font-size:16px;line-height:1.5;letter-spacing:-0.12px;font-weight:400}.modal-toolbar-icon{color:var(--ai12zBot-v2-toolbar-icon-color, inherit);width:16px;height:16px}.search-flex{flex:1 1 0%}.show-grid{display:grid}.hide-title{padding:0px;opacity:0;height:0px}.user-msg{background-color:var(--ai12zBot-v2-user-bubble-background);color:var(--ai12zBot-v2-user-bubble-font-color)}.text-body4{font-size:var(--ai12zBot-v2-timestamp-font-size);line-height:1.5;letter-spacing:0.03px;font-weight:400;color:var(--ai12zBot-v2-timestamp-font-color)}.isContent{background:var(--ai12zBot-v2-content-background);padding:10px}.default-botAvatar{color:var(--ai12zBot-v2-default-avatar-color)}.searchform{opacity:1;transform:none}.user-input{margin-left:auto;margin-right:auto;width:100%;max-width:840px;min-width:340px;grid-area:footer}.main{margin-left:auto;margin-right:auto;width:100%;max-width:840px;min-width:340px;margin-top:7px}.heading{color:var(--ai12zBot-v2-title-color)}.dropdown-item-button{display:flex;width:100%;cursor:pointer;align-items:center;-moz-column-gap:8px;column-gap:8px;border-radius:4px;--tw-border-opacity:1;--tw-bg-opacity:1;background-color:var(--ai12zBot-v2-dropdown-bgcolor);padding:8px 24px;font-weight:500;--tw-text-opacity:1;color:var(--ai12zBot-v2-dropdown-font-color);transition-property:color, background-color, border-color, text-decoration-color, fill, stroke;transition-timing-function:cubic-bezier(0.4, 0, 0.2, 1);transition-duration:75ms}.helptext{padding:0px;opacity:0;height:0px}.minimize-input{transform:translateY(calc(-100% - 4px))}.ai-text-caption{font-size:12px;line-height:1.5;letter-spacing:0.2px;font-weight:400}.fab>button{background:var(--ai12zBot-v2-fab-button-background);}.user-input-fieldset{background:var(--ai12zBot-v2-searchbar-background)}.return-text-color{color:rgb(255, 255, 255)}.ai-minimize-icon svg{fill:currentColor;height:1em;width:1em}.hide-form{opacity:0;transform:none}.show-form{opacity:1;transform:none}.ai-minimize-icon{color:var(--wes-c-icon-color, inherit)}.fab{bottom:var(--fab-bottom, 30px)}.text-body1{font-size:var(--ai12zBot-v2-title-font-size);line-height:1.5;letter-spacing:-0.12px;font-weight:400}#message-submit{margin-right:6px;margin-bottom:7px;background-color:var(--ai12zBot-v2-searchbar-submit-bgcolor)}.ai-icon{color:var(--ai12zBot-v2-searchbar-submit-color);font-size:24px;width:24px;height:24px}.bot-plus-icon{color:var(--ai12zBot-v2-searchbar-plus-icon-color);font-size:24px;width:24px;height:24px}.grow-wrap>.textarea,.grow-wrap:after{min-height:48px;align-content:center;border-radius:24px;border-width:1px;border-style:solid;border:1px solid var(--ai12zBot-v2-searchbar-border-color);--tw-bg-opacity:1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1));padding:8px 48px;text-indent:2px;font-size:16px;line-height:1.5;letter-spacing:-0.12px;font-weight:400;--tw-text-opacity:1;color:rgb(46 46 46 / var(--tw-text-opacity, 1));--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);--tw-ring-inset:inset;--tw-ring-offset-width:0px;transition-property:all;transition-timing-function:cubic-bezier(0.4, 0, 0.2, 1);transition-duration:0.15s}.grow-wrap>.textarea,.grow-wrap:after{grid-area:1 / 1 / 2 / 2}.modal{position:relative;grid-column:span 1 / span 1;grid-column-start:2;grid-row:span 3 / span 3;grid-row-start:1;display:grid;border-top-left-radius:0;border-top-right-radius:0;background-position:center;box-shadow:0 16px 32px -4px #18181829, 0 12px 24px -4px #18181814;background-image:var(--ai12zBot-v2-modal-backgroundImage);background-repeat:no-repeat;background-size:100vw 100vh;grid-template-columns:subgrid;grid-template-rows:subgrid;z-index:var(--xsf-ai12z-zindex-10);transition:0.3sease-out;transition-property:grid-template-columns}.dropdown-menu{pointer-events:none;opacity:0;z-index:10;background-color:var(--ai12zBot-v2-dropdown-bgcolor);transform:translateY(-10px);transition:opacity 0.3s ease, transform 0.3s ease}.dropdown-menu.show{pointer-events:auto;opacity:1;pointer-events:auto;transform:translateY(0);background-color:var(--ai12zBot-v2-dropdown-bgcolor)}.copy-btn{color:var(--ai12zBot-v2-copy-btn-color)}.thumbs-up{fill:var(--ai12zBot-v2-feedback-selected);width:24px}.thumbs-down{fill:var( --ai12zBot-v2-feedback-selected);width:24px}.chat-thumbs-up{color:var(--ai12zBot-v2-feedback-color)}.thumbs-container{justify-content:flex-start;align-items:center}.back-btn svg{fill:var(--ai12zBot-v2-back-button-color)}.dropdown-item{background-color:var(--ai12zBot-v2-dropdown-bgcolor)}button:focus-visible{outline:2px solid var(--ai12zBot-v2-focus-visible-color, #0A2A43);outline-offset:2px}button.bot-btn-primary:focus-visible{outline:2px solid var(--ai12zBot-v2-focus-visible-color-primary, var(--ai12zBot-v2-focus-visible-color, #0A2A43));outline-offset:2px}button.bot-btn-secondary:focus-visible{outline:2px solid var(--ai12zBot-v2-focus-visible-color-secondary, var(--ai12zBot-v2-focus-visible-color, #0A2A43))}.bot-name{color:var(--ai12zBot-v2-fab-name-color, var(--ai12zBot-v2-bot-name-color));font-weight:var(--ai12zBot-v2-fab-font-weight, var(--ai12zBot-v2-bot-name-font-weight))}.ai12z-link{color:var(--ai12zBot-v2-link-color);text-decoration:underline}.ai12z-link:hover{color:var(--ai12zBot-v2-link-hover-color);text-decoration:underline}.toolbar{height:52px;border:#fff;grid-area:toolbar}.skip-link{position:absolute;left:-999px;top:auto;width:1px;height:1px;overflow:hidden}.skip-link:focus{left:10px;top:10px;width:auto;height:auto;z-index:1000}.enter-tip{font-size:12px;color:#666;margin-left:10px}.skip-links.hidden{position:absolute;left:-9999px;}.skip-links.visible{left:auto;position:static;}.error-message-container{margin-top:4px}.error-msg{color:#dc2626;font-size:12px;display:block;animation:slideIn 0.2s ease-out}.ai12z-form-honeypot{position:absolute;left:-10000px;top:auto;width:1px;height:1px;overflow:hidden}@keyframes slideIn{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}@media (min-width: 1024px){.modal{background-size:80vw 100vh}}@media (min-width: 1024px){.layout.is-expanded{grid-template-columns:1fr minmax(340px, 80dvw) 1fr !important}}@media (min-width: 768px){.layout.is-expanded{-moz-column-gap:48px;column-gap:48px}}@media (max-width: 767px){.layout.is-open{padding-top:0px !important;grid-template-columns:0fr minmax(340px, 1fr) 0fr !important}}@media (max-width: 767px){.fab{right:30px;bottom:var(--xsf-ai12z-fab-bottom, 26px)}}'}},[257,"ai12z-bot",{dataKey:[513,"data-key"],dataMode:[513,"data-mode"],configId:[513,"config-id"],dataAttributes:[520,"data-attributes"],excludeTags:[16],includeTags:[16],liveAgentButtonText:[32],isLiveAgentEnabled:[32],isTypingIndicatorVisible:[32],botSettings:[32],canRender:[32],voiceType:[32],voice:[32],showSubmit:[32],hideAllButtons:[32],showMenu:[32],isProse:[32],isLiveAgent:[32],isConnectingLiveAgent:[32],showWelcomeScreen:[32],showHistory:[32],conversationId:[32],surveyDomId:[32],searchResults:[32],buttons:[32],currentDomId:[32],messages:[32],questionCounter:[32],visitorID:[32],timestamp:[32],rowCount:[32],isBot:[32],conversationHistory:[32],query:[32],scriptArray:[32],imagesBase64List:[32],focusedIndex:[32],isAnimated:[32],isMinimized:[32],isStreaming:[32],showErrorMessage:[32],errorMessage:[32],emptyMessageError:[32],isOpened:[32],isContent:[32],isExpanded:[32],isToggled:[32],showPrivacy:[32],isRendered:[32],showShortcutsDialog:[32],showLiveAgentEndDialog:[32],liveAgentSessionId:[32],liveAgentConversationId:[32],liveAgentProviderName:[32],liveAgentListenersRegistered:[32],shortcuts:[32],announceMessage:[32],liveAgentDirective:[32],isSending:[32],sendMessage:[64],sendQuery:[64],sendJSON:[64],openBot:[64],action:[64],setProcessDataOverride:[64],configureSettings:[64]},[[0,"keydown","handleKeyDown"],[0,"buttonClick","buttonClickHandler"],[0,"sendQueryToBot","sendQueryToBotHandler"],[0,"deleteChatHistory","deleteChatHistoryHandler"],[0,"chatClick","chatClickHandler"],[0,"openChat","openChatHandler"],[0,"formComplete","formSubmittedHandler"]],{dataKey:[{onDataKeyChange:0}],dataMode:[{onDataModeChange:0}]}]);function wt(){"undefined"!=typeof customElements&&["ai12z-bot","audio-recorder","chat-avatar","chatbot-history","delete-confirmation-modal","hamburger-menu","image-uploader","interaction-buttons","item-list","keyboard-shortcuts-dialog","live-agent-chat","privacy-modal","typing-indicator"].forEach((t=>{switch(t){case"ai12z-bot":customElements.get(i(t))||customElements.define(i(t),yt);break;case"audio-recorder":customElements.get(i(t))||V();break;case"chat-avatar":customElements.get(i(t))||Y();break;case"chatbot-history":customElements.get(i(t))||W();break;case"delete-confirmation-modal":customElements.get(i(t))||Q();break;case"hamburger-menu":customElements.get(i(t))||X();break;case"image-uploader":customElements.get(i(t))||tt();break;case"interaction-buttons":customElements.get(i(t))||it();break;case"item-list":customElements.get(i(t))||g();break;case"keyboard-shortcuts-dialog":customElements.get(i(t))||et();break;case"live-agent-chat":customElements.get(i(t))||st();break;case"privacy-modal":customElements.get(i(t))||ot();break;case"typing-indicator":customElements.get(i(t))||nt()}}))}wt();export{yt as A,wt as d}
@@ -1065,6 +1065,7 @@ var __rest = (undefined && undefined.__rest) || function (s, e) {
1065
1065
  return t;
1066
1066
  };
1067
1067
  const logger = new Logger("Ai12zBot");
1068
+ const STREAM_END_TIMEOUT_MS = 30000;
1068
1069
  const Ai12zBot = class {
1069
1070
  constructor(hostRef) {
1070
1071
  registerInstance(this, hostRef);
@@ -1146,6 +1147,7 @@ const Ai12zBot = class {
1146
1147
  this.liveAgentListenersRegistered = false;
1147
1148
  this.shortcuts = DEFAULT_SHORTCUTS;
1148
1149
  this.announceMessage = ""; // For accessibility announcements
1150
+ this.isSending = false;
1149
1151
  this.messageRefs = [];
1150
1152
  // Replace your existing handlePaste method with this enhanced version
1151
1153
  this.handlePaste = (event) => {
@@ -1258,12 +1260,30 @@ const Ai12zBot = class {
1258
1260
  }
1259
1261
  };
1260
1262
  this.handleSend = async (eleValue, options = {}) => {
1261
- var _a, _b;
1262
- const { isHide = false, isLiveChatEnded = false } = options;
1263
- const resolvedQuery = (typeof this.query === "string" && this.query.trim()) || eleValue.trim() || ((_a = this.inputEl) === null || _a === void 0 ? void 0 : _a.value.trim()) || "";
1263
+ var _a, _b, _c;
1264
+ const { isHide = false, isLiveChatEnded = false, bypassSendGuard = false } = options;
1265
+ // Acquire the lock before any await.
1266
+ if ((this.isSending || this.isStreaming) && !bypassSendGuard) {
1267
+ this.query = "";
1268
+ return false;
1269
+ }
1270
+ this.isSending = true;
1271
+ const queryText = typeof this.query === "string" ? this.query.trim() : "";
1272
+ const displayText = typeof eleValue === "string" ? eleValue.trim() : "";
1273
+ const inputText = ((_a = this.inputEl) === null || _a === void 0 ? void 0 : _a.value.trim()) || "";
1274
+ const resolvedQuery = queryText || displayText || inputText;
1275
+ const resolvedDisplayText = displayText || (!isHide ? resolvedQuery : "");
1264
1276
  if (!resolvedQuery && this.imagesBase64List.length === 0) {
1265
1277
  this.showEmptyMessageValidation();
1266
- return;
1278
+ this.query = "";
1279
+ this.isSending = false;
1280
+ return false;
1281
+ }
1282
+ if (!isHide && !resolvedDisplayText && this.imagesBase64List.length === 0) {
1283
+ this.query = "";
1284
+ this.isSending = false;
1285
+ this.showEmptyMessageValidation();
1286
+ return false;
1267
1287
  }
1268
1288
  this.emptyMessageError = false;
1269
1289
  this.surveyDomId = "";
@@ -1272,7 +1292,7 @@ const Ai12zBot = class {
1272
1292
  this.questionCounter = this.questionCounter + 1;
1273
1293
  localStorage.setItem(`ai12z-bot-data`, JSON.stringify({ qCounter: this.questionCounter }));
1274
1294
  }
1275
- const inputValue = eleValue;
1295
+ const inputValue = resolvedDisplayText;
1276
1296
  if (this.inputEl) {
1277
1297
  this.inputEl.value = inputValue;
1278
1298
  }
@@ -1282,11 +1302,19 @@ const Ai12zBot = class {
1282
1302
  if (this.showWelcomeScreen && this.botSettings.botVersion === "v1") {
1283
1303
  this.showWelcomeScreen = false;
1284
1304
  }
1285
- if (this.messages.length === 0) {
1286
- await this.socketConnection();
1305
+ try {
1306
+ if (this.messages.length === 0 || !((_b = this.socket) === null || _b === void 0 ? void 0 : _b.connected)) {
1307
+ await this.socketConnection();
1308
+ }
1309
+ else if (!this.socket || !this.socket.connected) {
1310
+ await this.socketConnection();
1311
+ }
1287
1312
  }
1288
- else if (!this.socket || !this.socket.connected) {
1289
- await this.socketConnection();
1313
+ catch (error) {
1314
+ console.error("Error in handleSend:", error);
1315
+ this.query = "";
1316
+ this.isSending = false;
1317
+ return false;
1290
1318
  }
1291
1319
  // if (inputValue.trim()) {
1292
1320
  const now = new Date();
@@ -1333,6 +1361,9 @@ const Ai12zBot = class {
1333
1361
  if (this.botSettings.maxQuestion > 0 && this.questionCounter > this.botSettings.maxQuestion && !this.isLiveAgent && !isLiveChatEnded) {
1334
1362
  // console.log("Max question limit reached")
1335
1363
  this.inputEl.value = "";
1364
+ this.query = "";
1365
+ this.releaseSendLock();
1366
+ return false;
1336
1367
  }
1337
1368
  else {
1338
1369
  this.currentDomId = "";
@@ -1344,16 +1375,18 @@ const Ai12zBot = class {
1344
1375
  this.inputEl.value = "";
1345
1376
  }
1346
1377
  this.query = "";
1378
+ this.isSending = false;
1347
1379
  }
1348
1380
  else {
1349
1381
  this.checkLiveAgentMode();
1350
1382
  this.isStreaming = true;
1351
1383
  this.ignoreChunks = false;
1352
- this.invokeSocket();
1384
+ this.resetStreamEndWatchdog();
1385
+ this.invokeSocket(resolvedQuery);
1353
1386
  }
1354
1387
  }
1355
1388
  // this.invokeSocket()
1356
- const parent = (_b = this.el.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector("#previewContainer");
1389
+ const parent = (_c = this.el.shadowRoot) === null || _c === void 0 ? void 0 : _c.querySelector("#previewContainer");
1357
1390
  if (parent) {
1358
1391
  parent.innerHTML = "";
1359
1392
  }
@@ -1361,6 +1394,7 @@ const Ai12zBot = class {
1361
1394
  this.rowCount = 1;
1362
1395
  this.showSubmit = false;
1363
1396
  // }
1397
+ return true;
1364
1398
  };
1365
1399
  this.agentMessageCreated = (message) => {
1366
1400
  var _a;
@@ -1705,6 +1739,7 @@ const Ai12zBot = class {
1705
1739
  this.showWelcomeScreen = true;
1706
1740
  this.showHistory = false;
1707
1741
  this.isOpened = true;
1742
+ this.releaseSendLock();
1708
1743
  // Focus input if available
1709
1744
  setTimeout(() => {
1710
1745
  var _a;
@@ -1752,9 +1787,6 @@ const Ai12zBot = class {
1752
1787
  }
1753
1788
  async sendMessage(message, displayText, options) {
1754
1789
  this.query = message;
1755
- // if (!this.isChatOpen) {
1756
- // this.isChatOpen = true
1757
- // }
1758
1790
  this.handleSend(displayText !== null && displayText !== void 0 ? displayText : message, options);
1759
1791
  }
1760
1792
  async sendQuery(query) {
@@ -1763,9 +1795,6 @@ const Ai12zBot = class {
1763
1795
  }
1764
1796
  async sendJSON(jsonData, displayText) {
1765
1797
  this.query = JSON.stringify(jsonData);
1766
- // if (!this.isChatOpen) {
1767
- // this.isChatOpen = true
1768
- // }
1769
1798
  this.handleSend(displayText);
1770
1799
  }
1771
1800
  async openBot(expanded = false) {
@@ -1895,6 +1924,28 @@ const Ai12zBot = class {
1895
1924
  this.clearEvents();
1896
1925
  }
1897
1926
  }
1927
+ releaseSendLock() {
1928
+ this.clearStreamEndWatchdog();
1929
+ this.isStreaming = false;
1930
+ this.isSending = false;
1931
+ }
1932
+ clearStreamEndWatchdog() {
1933
+ if (this.streamEndWatchdog) {
1934
+ clearTimeout(this.streamEndWatchdog);
1935
+ this.streamEndWatchdog = undefined;
1936
+ }
1937
+ }
1938
+ resetStreamEndWatchdog() {
1939
+ this.clearStreamEndWatchdog();
1940
+ this.streamEndWatchdog = setTimeout(() => {
1941
+ this.streamEndWatchdog = undefined;
1942
+ if (!this.isStreaming) {
1943
+ return;
1944
+ }
1945
+ console.error("Socket response timed out before completion");
1946
+ this.failTurn("Something went wrong. Please try again.");
1947
+ }, STREAM_END_TIMEOUT_MS);
1948
+ }
1898
1949
  componentDidLoad() {
1899
1950
  var _a;
1900
1951
  setBotElement(this.el); // register globally
@@ -1976,6 +2027,7 @@ const Ai12zBot = class {
1976
2027
  // fire scrollToBottom() against a torn-down component.
1977
2028
  if (this.autoScrollTimer)
1978
2029
  clearTimeout(this.autoScrollTimer);
2030
+ this.clearStreamEndWatchdog();
1979
2031
  }
1980
2032
  handleClickOutside(event) {
1981
2033
  // Check if the clicked target is outside the menu
@@ -2247,6 +2299,7 @@ const Ai12zBot = class {
2247
2299
  const responseEvent = protocol === "v2" ? "chunk" : "response";
2248
2300
  const endEvent = protocol === "v2" ? "complete" : "end_response";
2249
2301
  this.socket.on(responseEvent, async (event) => {
2302
+ this.resetStreamEndWatchdog();
2250
2303
  const { id, idChanged } = ensureMessageId(this.currentDomId, this.messages, "chatbot");
2251
2304
  this.currentDomId = id;
2252
2305
  if (idChanged)
@@ -2261,6 +2314,12 @@ const Ai12zBot = class {
2261
2314
  });
2262
2315
  });
2263
2316
  this.socket.on(endEvent, async (rawData) => {
2317
+ if (!rawData) {
2318
+ console.error("Received empty end response payload");
2319
+ this.failTurn("Something went wrong. Please try again.");
2320
+ return;
2321
+ }
2322
+ this.clearStreamEndWatchdog();
2264
2323
  // For v2, adapt the response format to match legacy expectations
2265
2324
  const data = protocol === "v2" ? adaptCompleteToLegacy(rawData) : rawData;
2266
2325
  if (data.showInput !== undefined && typeof data.showInput === "boolean") {
@@ -2375,12 +2434,12 @@ const Ai12zBot = class {
2375
2434
  this.updateBotState();
2376
2435
  }
2377
2436
  this.scrollToBottom();
2378
- this.isStreaming = false;
2437
+ this.releaseSendLock();
2379
2438
  this.currentDomId = "";
2380
2439
  }
2381
2440
  catch (error) {
2382
2441
  console.error("Error handling end_response:", error);
2383
- this.isStreaming = false;
2442
+ this.releaseSendLock();
2384
2443
  }
2385
2444
  });
2386
2445
  });
@@ -2462,7 +2521,7 @@ const Ai12zBot = class {
2462
2521
  }
2463
2522
  }
2464
2523
  // ✅ Handle the survey completion rendering
2465
- handleSurveyCompletionRender(processedResults) {
2524
+ async handleSurveyCompletionRender(processedResults) {
2466
2525
  // console.log("Survey completed with results:", processedResults)
2467
2526
  // Find and update the message
2468
2527
  const idx = this.messages.findIndex(item => item.surveyDomId === processedResults.domId);
@@ -2471,8 +2530,26 @@ const Ai12zBot = class {
2471
2530
  this.surveyDomId = processedResults.domId;
2472
2531
  // Update conversations with completed HTML
2473
2532
  this.updateConversations(processedResults.completedHtml, {});
2533
+ // Use the JSON payload as the query and the completion text as display text.
2534
+ const surveyQuery = processedResults.jsonData;
2535
+ this.query = surveyQuery;
2536
+ let sent = false;
2474
2537
  // Send the JSON data message
2475
- this.sendMessage(processedResults.jsonData, processedResults.completeText, { isHide: true });
2538
+ try {
2539
+ sent = await this.handleSend(processedResults.completeText, { isHide: true, bypassSendGuard: true });
2540
+ }
2541
+ finally {
2542
+ if (!sent) {
2543
+ console.error("Failed to send form data in finally block");
2544
+ }
2545
+ if (this.query === surveyQuery) {
2546
+ this.query = "";
2547
+ }
2548
+ }
2549
+ if (!sent) {
2550
+ console.error("Failed to send form data");
2551
+ return;
2552
+ }
2476
2553
  this.formSubmitted.emit(processedResults.sender.data);
2477
2554
  // Scroll to bottom
2478
2555
  this.scrollToBottom();
@@ -2608,20 +2685,37 @@ const Ai12zBot = class {
2608
2685
  this.messages = [...this.messages];
2609
2686
  }
2610
2687
  this.isStreaming = false;
2688
+ this.isSending = false;
2611
2689
  });
2612
2690
  this.socket.on("connect_error", error => {
2613
2691
  this.errored.emit(error);
2614
2692
  this.announce("Unable to connect to chat server. Please try again.");
2615
2693
  console.error("Connection error:", error);
2616
2694
  });
2695
+ this.socket.on("error", () => {
2696
+ if (this.isStreaming)
2697
+ this.failTurn("Something went wrong. Please try again.");
2698
+ });
2617
2699
  this.socket.on("disconnect", () => {
2618
2700
  // console.log("Disconnected from Socket.IO server")
2619
2701
  this.socket.off("response");
2620
2702
  this.socket.off("chunk");
2621
2703
  // Handle disconnection if needed
2704
+ if (this.isStreaming)
2705
+ this.failTurn("Connection lost. Please try again.");
2622
2706
  });
2623
2707
  }
2624
- invokeSocket() {
2708
+ failTurn(message) {
2709
+ // Release the lock so another message can be sent.
2710
+ this.releaseSendLock();
2711
+ const last = this.messages[this.messages.length - 1];
2712
+ if (last && !last.isUser && last.isLoading) {
2713
+ last.text = message;
2714
+ last.isLoading = false;
2715
+ this.messages = [...this.messages];
2716
+ }
2717
+ }
2718
+ invokeSocket(query) {
2625
2719
  var _a;
2626
2720
  const protocol = getBackendProtocol(this.dataMode);
2627
2721
  let data;
@@ -2629,13 +2723,13 @@ const Ai12zBot = class {
2629
2723
  if (protocol === "v2") {
2630
2724
  eventName = "query";
2631
2725
  const beaconId = sessionStorage.getItem("ai12zBeaconId");
2632
- data = Object.assign({ query: this.query !== "" ? this.query : this.inputEl.value, conversation_id: this.conversationId || "", base64_images: ((_a = this.imagesBase64List) === null || _a === void 0 ? void 0 : _a.length) > 0 ? this.imagesBase64List : undefined, beacon_id: this.botSettings.disableBeacon ? "" : beaconId !== null && beaconId !== void 0 ? beaconId : "" }, (this.botSettings.disableBeacon || beaconId ? {} : { beacon_data: buildBeacon() }));
2726
+ data = Object.assign({ query, conversation_id: this.conversationId || "", base64_images: ((_a = this.imagesBase64List) === null || _a === void 0 ? void 0 : _a.length) > 0 ? this.imagesBase64List : undefined, beacon_id: this.botSettings.disableBeacon ? "" : beaconId !== null && beaconId !== void 0 ? beaconId : "" }, (this.botSettings.disableBeacon || beaconId ? {} : { beacon_data: buildBeacon() }));
2633
2727
  }
2634
2728
  else {
2635
2729
  eventName = "evaluate_query";
2636
2730
  data = {
2637
2731
  apiKey: this.dataKey,
2638
- query: this.query !== "" ? this.query : this.inputEl.value,
2732
+ query,
2639
2733
  conversationId: this.conversationId,
2640
2734
  event: "evaluate_query",
2641
2735
  attributes: this.dataAttributes,
@@ -2672,6 +2766,7 @@ const Ai12zBot = class {
2672
2766
  .catch(error => {
2673
2767
  console.error("Error in processDataOverride:", error);
2674
2768
  this.errored.emit(error);
2769
+ this.releaseSendLock();
2675
2770
  this.announce("An error occurred while sending your message.");
2676
2771
  });
2677
2772
  }
@@ -2704,6 +2799,7 @@ const Ai12zBot = class {
2704
2799
  stopResponse() {
2705
2800
  this.ignoreChunks = true; // drop future chunks
2706
2801
  this.isStreaming = false;
2802
+ this.releaseSendLock();
2707
2803
  this.messages[this.messages.length - 1].isLoading = false;
2708
2804
  // this.socket.off('response');
2709
2805
  }
@@ -2805,9 +2901,12 @@ const Ai12zBot = class {
2805
2901
  this.liveAgentSessionId = "";
2806
2902
  this.liveAgentConversationId = "";
2807
2903
  this.liveAgentButtonText = "Talk to a Live Agent";
2808
- this.sendMessage(((_a = this.botSettings) === null || _a === void 0 ? void 0 : _a.llmMessageOnDisconnect) !== ""
2904
+ const llmMessage = ((_a = this.botSettings) === null || _a === void 0 ? void 0 : _a.llmMessageOnDisconnect) !== ""
2809
2905
  ? (_b = this.botSettings) === null || _b === void 0 ? void 0 : _b.llmMessageOnDisconnect
2810
- : "The live agent has been disconnected. Please do not initiate the live agent directive again.", ((_c = this.botSettings) === null || _c === void 0 ? void 0 : _c.userMessageOnDisconnect) !== "" ? (_d = this.botSettings) === null || _d === void 0 ? void 0 : _d.userMessageOnDisconnect : "The live agent has ended the conversation.", { isLiveChatEnded: true });
2906
+ : "The live agent has been disconnected. Please do not initiate the live agent directive again.";
2907
+ const displayText = ((_c = this.botSettings) === null || _c === void 0 ? void 0 : _c.userMessageOnDisconnect) !== "" ? (_d = this.botSettings) === null || _d === void 0 ? void 0 : _d.userMessageOnDisconnect : "The live agent has ended the conversation.";
2908
+ this.query = llmMessage;
2909
+ void this.handleSend(displayText, { isLiveChatEnded: true, bypassSendGuard: true });
2811
2910
  this.announce("Live agent chat ended");
2812
2911
  this.clearEvents();
2813
2912
  }