1(function(){"use strict";var e=[`fonts.googleapis.com`,`fonts.adobe.com`,`use.typekit.net`,`fonts.bunny.net`,`fast.fonts.net`,`cloud.typography.com`,`api.fontshare.com`,`font`,`typography`],t=class{static widgetID;static userID;static widgetData;static appContainer;static frameContainer;static triggerContainer;static chatwayLauncherIcon;static chatwayCloseIcon;static iconToggler;static agents=null;static included=null;static previewText=null;static status=`online`;static unReadCount=0;static pageTitle=``;static fallbackAvatar=`https://prod-chaty-uploads.s3.us-west-2.amazonaws.com/npgRZqDneIU48ejuo2VR9TK13Lu40mnVdoOGA59Jj3P5VgT140758.svg`;static agentMessage=null;static hasAlreadyLoaded=!1;static token=``;static isChatInitialized=``;static visibilityHourTimezone=``;static visibilityHours=[];static isWidgetVisible=!1;static widgetTriggers={is_trigger_enabled:!1,has_display_after_time:!1,display_after_time:0,has_display_page_scroll:!1,display_page_scroll:0,widget_id:``};static pageRules;static isHideChatwayIcon=!1;static previewTextBubbleDelay=0;static chatContactId=``;static shopifyCustomerId=``;static isVerifiedVisitor=!1;static widgets=[];static browserData={ip:``,loc:``};static aiAssistant=null;static isWidgetReady=!1;static pendingMessages=[]},n=(e,t,n)=>{let r=new Date;r.setTime(r.getTime()+n*24*60*60*1e3);let i=`expires=`+r.toUTCString();document.cookie=e+`=`+t+`;`+i+`;path=/;SameSite=None;Secure`},r=e=>{let t=e+`=`,n=document.cookie.split(`;`);for(let e=0;e<n.length;e++){let r=n[e];for(;r.charAt(0)==` `;)r=r.substring(1);if(r.indexOf(t)==0)return r.substring(t.length,r.length)}return``},i=e=>{document.cookie=e+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;SameSite=None;Secure`,document.cookie=e+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;domain=.chatway.app;Secure;SameSite=None`},a=(e,t)=>{try{localStorage.setItem(e,t)}catch(t){console.error(`Error setting localStorage for key:`,e,t)}},o=e=>{try{return localStorage.getItem(e)||``}catch(t){return console.error(`Error getting localStorage for key:`,e,t),``}},s=e=>{try{localStorage.removeItem(e)}catch(t){console.error(`Error removing localStorage for key:`,e,t)}},c=e=>{let t=o(e),n=r(e);return t?(n&&i(e),t):n?(a(e,n),i(e),n):``},l=()=>window.matchMedia(`(max-width: 600px)`).matches,u=()=>t.widgetData?.open_in_fullscreen_mobile??!0,d=(e,t)=>{let n=document.querySelector(`#${e}`);if(n){let e=n.src;return new URL(e).searchParams.get(t)||null}else return f(`chatway.app`,t)},f=(e,t)=>{let n=document.getElementsByTagName(`script`);for(let r=0;r<n.length;r++){let i=n[r].src;if(i&&i.includes(e))return new URL(i).searchParams.get(t)||null}return null},p=(e,t,n)=>{let r,i,a,o=!1;if(e){let s=e.split(/\s+/);for(a=0;a<s.length;a+=1)if(r=RegExp(`\\b${s[a]}\\b`,`g`),i=RegExp(` *${s[a]}\\b`,`g`),t===`remove`)n.className=n.className.replace(i,``);else if(t===`toggle`)n.className=n.className.match(r)?n.className.replace(i,``):`${n.className} ${s[a]}`;else if(t===`has`&&n.className.match(r)){o=!0;break}}return o},m=(e,t)=>{t&&(e.className+=` ${t}`)},h=(e,t)=>{p(t,`remove`,e)},g=e=>document.querySelector(e),ee=e=>document.querySelectorAll(e),te=()=>{let e=document.createElement(`link`);e.rel=`stylesheet`,e.href=`https://cdn.chatway.app/sdk.css`,e.id=`chatway-widget-css`,document.head.appendChild(e)},_=(e,t)=>
1{switch(e){case`s`:return 44;case`m`:return 60;case`l`:return 70;case`xl`:return 84;case`xxl`:return 94;case`custom`:return t?Number(t):60;default:return 60}},v=e=>[{color:`#0446DE`,hex:`#0446DE`},{color:`linear-gradient(100.96deg, #43cea2 0%, #185a9d 100%), #414141`,hex:`#185A9D`},{color:`#282D3E`,hex:`#282D3E`},{color:`linear-gradient(101.04deg, #56CCF2 0.59%, #2F80ED 100%), #7E8E9C`,hex:`#2F80ED`},{color:`linear-gradient(101.04deg, #00317A 0.59%, #001F4F 100%)`,hex:`#001F4F`},{color:`linear-gradient(100.96deg, #5E3D86 0%, #2F164D 100%), #537EE1`,hex:`#2F164D`},{color:`linear-gradient(180deg, #F69D01 0%, #F65901 100%)`,hex:`#F65901`},{color:`linear-gradient(100.96deg, #6A3093 0%, #A044FF 100%), #3B9488`,hex:`#A044FF`},{color:`linear-gradient(100.96deg, #E96443 0%, #904E95 100%), #5BB055`,hex:`#904E95`}].find(t=>t.color.includes(e))?.hex||e,ne=(e=100)=>new Promise(t=>setTimeout(t,e)),re=()=>{let e=document.activeElement;e&&e.blur()},ie=()=>{if(sessionStorage.getItem(`_bdyF`)!==null)return;let e=document.querySelector(`body`),t=window.getComputedStyle(e),n=window.scrollY;sessionStorage.setItem(`_bdyF`,t.getPropertyValue(`overflow`)),sessionStorage.setItem(`_scrollY`,n.toString()),document.body.style.position=`fixed`,document.body.style.top=`-${n}px`,document.body.style.width=`100%`,document.body.style.overflow=`hidden`},y=()=>
1{if(sessionStorage.getItem(`_bdyF`)===null)return;let e=sessionStorage.getItem(`_bdyF`)||`auto`,t=sessionStorage.getItem(`_scrollY`);document.body.style.position=``,document.body.style.top=``,document.body.style.width=``,document.body.style.overflow=e,t&&window.scrollTo(0,parseInt(t)),sessionStorage.removeItem(`_bdyF`),sessionStorage.removeItem(`_scrollY`)},ae=e=>{let t=window.location.search;return new URLSearchParams(t).get(e)},oe=e=>e.trim().split(` 2`).reduce(function(e,t){return t=t.split(`=`),e[t[0]]=t[1],e},{}),b=()=>window.Shopify?`shopify`:window.wpChatwaySettings?`wordpress`:document.querySelector(`meta[name='generator']`)?.getAttribute(`content`)?.toLowerCase().includes(`wix`)?`wix`:ue()?`duda`:``,x=()=>b()===`shopify`,S=()=>window.location.origin,C=e=>e?e.replace(/^(https?:\/\/)?(www\.)?/,``).replace(/:\d+$/,``).replace(/\/$/,``):``,w=e=>!e||e===`/`?`/`:e.replace(/^\/|\/$/g,``),T=()=>{let e=t.widgetData;return!e.is_separate_device_preference&&e.device_appearance===`both`?`desktop`:l()?`mobile`:`desktop`},se=()=>window.Shopify&&window.Shopify?.theme?.schema_name?le(window.Shopify.theme.schema_name):``,ce=()=>window.wpChatwaySettings?.themeName?le(window.wpChatwaySettings.themeName):``,le=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/(^-|-$)/g,``);function ue(){let e=window.dmAPI||window.DM||window.duda,t=Array.from(document.scripts).some(e=>/duda|dmcdn|dudamobile/i.test(e.src)),n=document.querySelector(`meta[name="generator"][content*="Duda"]`),r=document.querySelector(`[data-dm-page-id], .dmRespRow`);return!!(e||t||n||r)}var E=function(e){return e.widgetToggle=`widget.toggle`,e.widgetLoaded=`widget.loaded`,e.widgetMetaData=`widget.metadata`,e.agentStatusChange=`agent.status.change`,e.unreadMessage=`messages.unread`,e.locationChange=`location.change`,e.agentMessaged=`agent.messages.received`,e.visitorConversationStarted=`visitor.conversation.started`,e.loadImage=`load.image`,e.loadYoutube=`load.youtube`,e.removeYoutube=`remove.youtube`,e.newVisitorNotification=`new.visitor.notification`,e.removeImage=`remove.image`,e.nextImage=`next.image`,e.prevImage=`prev.image`,e.profileData=`profile.data`,e.chatHistory=`chat.history`,e.focusEvent=`focus.event`,e.widgetReload=`widget.reload`,e.widgetDestroy=`widget.destroy`,e.customData=`custom.data`,e.removeToken=`remove.token`,e.chatContactLoaded=`chat.contact.loaded`,e.customerDataLoaded=`customer.data.loaded`,e.setVisitorEmail=`set.visitor.email`,e.setChatwaySettings=`set.chatway.settings`,e.openContactChannel=`open.contact.channel`,e.copyToClipboard=`copy.to.clipboard`,e.widgetDisable=`widget.disable`,e.aiAssistantLoaded=`ai.assistant.loaded`,e.pageVisitAutomationTrigger=`page.visit.trigger`,e.liveChatWidgetIsOpenedAutomationTrigger=`live.chat.widget.is.opened.trigger`,e.hasConversation=`conversation.exist`,e.showQuickReplies=`show.quick.replies`,e.hideQuickReplies=`hide.quick.replies`,e.quickReplyPositionUpdate=`quick.reply.position.update`,e.themeUpdate=`theme.update`,e.previewClosed=`preview.closed`,e.showPreviewText=`show.preview.text`,e.hidePreviewText=`hide.preview.text`,e.showUnreadMessage=`show.unread.message`,e.widgetExpand=`widget.expand`,e.showFAQ=`show.faq`,e.humanActivityDetected=`human.activity.detected`,e.setVisitorDetails=`set.visitor.details`,e.sendMessage=`send.message`,e}({}),D=class{constructor(){}getSessionToken(){return c(`ch_cw_token_${t.widgetID}`)||t.token||``}setSessionToken(e){a(`ch_cw_token_${t.widgetID}`,e)}getChatInitStatus(){return c(`ch_cw_status_${t.widgetID}`)||t.isChatInitialized||`false`}setChatInitStatus(e){a(`ch_cw_status_${t.widgetID}`,e)}setWidgetStatus(e){let t=this.getUserConfig();t.widgetStatus=e?`open`:`close`,this.setUserConfig(t)}setTextBubbleStatus(e){let t=this.getUserConfig();t.hasOpenedTextBubble=e,this.setUserConfig(t)}setShowAttentionEffect(e){n(`ch_cw_shw_atn_efct_${t.widgetID}`,e?`true`:`false`,1)}getShowAttentionEffect(){return r(`ch_cw_shw_atn_efct_${t.widgetID}`)!==`false`}getUserConfig(){return JSON.parse(sessionStorage.getItem(`ch_session_info_${t.widgetID}`)||`{}`)}setUserConfig(e){sessionStorage.setItem(`ch_session_info_${t.widgetID}`,JSON.stringify(e))}deleteUserConfig(){let e=t.widgetID;sessionStorage.removeItem(`ch_session_info_${e}`),sessionStorage.removeItem(`ch_cw_status_${e}`),sessionStorage.removeItem(`ch_cw_token_${e}`),sessionStorage.removeItem(`ch_cw_quick_reply_${e}`),s(`ch_cw_status_${e}`),s(`ch_cw_token_${e}`),i(`ch_cw_status_${e}`),i(`ch_cw_token_${e}`)}getVisitorDetails(){try{let e=sessionStorage.getItem(`ch_visitor_details_${t.widgetID}`);return e?JSON.parse(e):null}catch{return null}}setVisitorDetails(e){sessionStorage.setItem(`ch_visitor_details_${t.widgetID}`,JSON.stringify(e))}removeVisitorDetails(){sessionStorage.removeItem(`ch_visitor_details_${t.widgetID}`)}
2setBubbleExpiration(){let e={data:`false`,expireTime:Date.now()+3600*1e3};localStorage.setItem(`showTextBubble`,JSON.stringify(e))}get wasWidgetOpen(){return this.getUserConfig().widgetStatus===`open`}get hasShownTextBubble(){return!!this.getUserConfig().hasOpenedTextBubble}get showTextBubble(){let e=localStorage.getItem(`showTextBubble`);if(e){let t=JSON.parse(e);return t.expireTime<=Date.now()?(localStorage.removeItem(`showTextBubble`),null):t.data?t.data:`true`}return null}},O=class{widgetData;iframeLoadHandler;constructor(){this.widgetData=t.widgetData}getCalculatedWidgetHeight(e){let t=window.innerHeight-e-104;return Math.min(Math.max(400,t),704)}async makeAppContainer(){let e=document.getElementsByTagName(`body`)[0];if(e||=(await new Promise(e=>setTimeout(e,1e3)),document.body),!e)return;let t=document.createElement(`div`);t.classList.add(`chatway--container`),t.classList.add(`disable--widget`);let n=document.createElement(`div`);n.classList.add(`chatway--frame-container`),n.classList.add(`chatway--chat--widget--container`),u()||n.classList.add(`chatway--no-mobile-fullscreen`);let r=document.createElement(`div`);r.classList.add(`chatway--trigger-container`);let i=se();i&&(n.classList.add(`shopify-theme`,`theme-${i}`),r.classList.add(`shopify-theme`,`theme-${i}`));let a=ce();if(a&&(n.classList.add(`wordpress-theme`,`theme-${a}`),r.classList.add(`wordpress-theme`,`theme-${a}`)),t.appendChild(n),t.appendChild(r),this.widgetData.position==`left`&&t.classList.add(`widget--left`),this.widgetData.position==`custom`){this.widgetData.custom_position_side==`left`&&t.classList.add(`widget--left`);let e=this.getCalculatedWidgetHeight(this.widgetData.bottom_spacing),n=document.createElement(`style`);n.innerHTML=`@media screen and (min-width: 601px) { .custom-position-widget-height .chatway--frame-container{ height: min(`+e+`px,100% - 104px); }}`,document.head.appendChild(n),t.classList.add(`custom-position-widget-height`)}return e.appendChild(t),t}makeTriggerContainer(){let e=g(`.chatway--trigger-container`),t=document.createElement(`div`);t.id=`chatway_widget_trigger`,t.classList.add(`chatway--trigger-icon-container`);let n=_(this.widgetData.widget_size,this.widgetData.custom_widget_size);return t.style.width=`${n}px`,t.style.height=`${n}px`,this.setPosition(e),e.appendChild(t),t}makeFrameContainer(){let e=t.widgetID,n=`https://widget.chatway.app/?userId=${t.userID}&widgetId=${e}&bg-color=${this.widgetData.widget_color}`;if(g(`.chatway--widget-frame`))return null;let r=g(`.chatway--frame-container`),i=document.createElement(`iframe`);i.classList.add(`chatway--widget-frame`);let a=this.widgetData.device_preferences?.[T()];if(a?.is_preview_text_enabled&&this.widgetData.default_state!==`opened`){let e=a.is_enabled_reply_textbox||a.show_quick_responses&&a.quick_responses?.length>0;(e||t.previewText)&&r.classList.replace(`chatway--chat--widget--container`,e?`chatway--quick--reply--container`:`chatway--preview--only--container`)}return i.src=n,i.id=`chatway_widget_app`,i.title=`Live chat widget`,this.iframeLoadHandler=()=>{i.focus()},this.setPosition(r),r.appendChild(i),r}setPosition(e){let t=_(this.widgetData.widget_size,this.widgetData.custom_widget_size),n=this.widgetData.bottom_spacing;if(e.classList.contains(`chatway--frame-container`))if(this.widgetData.position==`custom`){n=t+10+Number(this.widgetData.bottom_spacing);let e=this.getCalculatedWidgetHeight(n),r=n+e;if(r>window.innerHeight){let e=r-window.innerHeight+10;n-=e}}else n=t+10+20;if(e.classList.contains(`chatway--trigger-container`))if(this.widgetData.position==`custom`){n=Number(this.widgetData.bottom_spacing);let e=this.getCalculatedWidgetHeight(n),r=n+e;if(r>window.innerHeight){let e=r-window.innerHeight;n=n-e-t-20}}else n=20;let r=window.innerWidth;if(this.widgetData.position==`custom`){e.style.left=`unset`,e.style.right=`unset`;let t=this.widgetData.side_spacing;if(r>=480){let e=r-420;t>e&&(t=e)}else{let e=r-70;t>e&&(t=e)}t<0&&(t=0),this.widgetData.custom_position_side==`left`?e.style.left=`${t}px`:e.style.right=`${t}px`}e.classList.contains(`chatway--frame-container`)&&r<=600&&(e.style.left=`unset`,e.style.right=`unset`),e.style.bottom=`${n}px`}destroyAppContainer(){let e=g(`.chatway--container`),t=document.getElementById(`chatway_widget_app`);t&&this.iframeLoadHandler&&(t.removeEventListener(`load`,this.iframeLoadHandler),this.iframeLoadHandler=void 0),e?.remove()}get isWidgetVisible(){return t.appContainer?.classList.contains(`widget--open`)}focusIframe(){let e=document.getElementById(`chatway_widget_app`);e&&(e.contentDocument||e.contentWindow?e.focus():e.addEventListener(`load`,()=>{e.focus()},{once:!0}))}},k=class e{static isPreviewShown=!1;getPreviewData(){let e=t.widgetData,n=T(),r=e.device_preferences[n];return{agents:t.agents||[],previewText:t.previewText,status:t.status,widgetData:{avatar_border_color:e.avatar_border_color,header_text_color:e.header_text_color,chat_font_type:e.chat_font_type,is_preview_text_enabled:e.is_preview_text_enabled,widget_color:e.widget_color},preferences:{position:r?.position,custom_position_side:r?.custom_position_side,side_spacing:r?.side_spacing,bottom_spacing:r?.bottom_spacing,hide_automated_message_when_all_agent_offline:r?.hide_automated_message_when_all_agent_offline,show_quick_responses:r?.show_quick_responses,quick_responses:r?.quick_responses||[],is_enabled_reply_textbox:r?.is_enabled_reply_textbox,is_preview_text_enabled:r?.is_preview_text_enabled,preview_text_bubble_delay:r?.preview_text_bubble_delay},hasQuickReplies:this.hasQuickReplies()}}hasQuickReplies(){let e=t.widgetData,n=T(),r=e.device_preferences[n];return!!(r?.show_quick_responses&&r.quick_responses?.length>0||r?.is_enabled_reply_textbox)}showPreviewInIframe(){if(new O().isWidgetVisible||new D().showTextBubble===`fal
2se`)return;let n=t.widgetData,r=T(),i=n.device_preferences[r];if(!this.shouldShowPreviewText(i))return;let a=this.getPreviewData(),o=new Z;this.showIframeContainer(),o.dispatchEvent(E.showPreviewText,JSON.stringify(a)),e.isPreviewShown=!0}showUnreadMessageInIframe(){t.agentMessage&&(new O().isWidgetVisible||(this.showIframeContainer(),e.isPreviewShown=!0))}showIframeContainer(){let e=g(`.chatway--frame-container`),n=t.appContainer;if(!e||!n)return;e.classList.remove(`chatway--chat--widget--container`),e.classList.remove(`chatway--preview--only--container`),e.classList.remove(`chatway--quick--reply--container`);let r=t.widgetData.position===`custom`,i=_(t.widgetData.widget_size,t.widgetData.custom_widget_size),a;if(r){let e=Number(t.widgetData.bottom_spacing)||0;a=i+10+e}else a=i+10+20;this.hasQuickReplies()?(n.style.setProperty(`--quick-reply-bottom`,`${a}px`),e.classList.add(`chatway--quick--reply--container`)):(n.style.setProperty(`--preview-only-bottom`,`${a}px`),e.classList.add(`chatway--preview--only--container`))}hideIframeContainer(){let e=g(`.chatway--frame-container`),n=t.appContainer;!e||!n||(e.classList.remove(`chatway--preview--only--container`),e.classList.remove(`chatway--quick--reply--container`),e.classList.add(`chatway--chat--widget--container`),h(n,`preview--open`),h(n,`quick--reply--open`))}hidePreview(){this.hideIframeContainer(),e.isPreviewShown=!1}get isPreviewVisible(){return e.isPreviewShown}shouldShowPreviewText(e){let n=!!(t.aiAssistant?.active||t.agents?.length||!e?.hide_automated_message_when_all_agent_offline||t.status===`online`),r=!!(t.widgetData.is_preview_text_enabled&&t.previewText);return n&&r}},de=class{removePendingStatus(){let e=g(`#chatway_widget_trigger`);e&&e.classList.add(`has-unread-message`);let t=ee(`.Chatway-channel-link, .csaas-widget-trigger.has-chatway-channel`);t&&t.forEach(e=>{e.classList.add(`has-unread-message`)})}updatePendingStatus(){let e=g(`#chatway_widget_trigger`);if(!e)return;let n=t.pageTitle,r=t.unReadCount,i=t.isWidgetVisible;!i||r==0?(document.title=n,e.classList.remove(`has-unread-message`)):(document.title=`(${r}) ${n}`,e.classList.add(`has-unread-message`)),e.setAttribute(`data-unread-message`,String(r));let a=ee(`.Chatway-channel-link, .csaas-widget-trigger.has-chatway-channel`);a&&a.forEach(e=>{!i||r==0?(document.title=n,e.classList.remove(`has-unread-message`)):(document.title=`(${r}) ${n}`,e.classList.add(`has-unread-message`)),e.setAttribute(`data-unread-message`,String(r))})}},A=class extends Event{constructor(e={}){super(`urlchangeevent`,{cancelable:!0,...e}),this.newURL=e.newURL,this.oldURL=e.oldURL,this.action=e.action}get[Symbol.toStringTag](){return`UrlChangeEvent`}},fe=window.history.pushState.bind(window.history);window.history.pushState=function(e,t,n){let r=new URL(n||``,window.location.href);window.dispatchEvent(new A({newURL:r,oldURL:j,action:`pushState`}))&&(fe({_index:M+1,...e},t,n),P())};var pe=window.history.replaceState.bind(window.history);window.history.replaceState=function(e,t,n){let r=new URL(n||``,window.location.href);window.dispatchEvent(new A({newURL:r,oldURL:j,action:`replaceState`}))&&(pe({_index:M,...e},t,n),P())};var j,M;function N(){let e=window.history.state;(!e||typeof e._index!=`number`)&&pe({_index:window.history.length,...e},null,null)}function P(){j=new URL(window.location.href),M=window.history.state._index}N(),P(),window.addEventListener(`popstate`,function(e){N();let t=window.history.state._index,n=new URL(window.location);if(t===M){e.stopImmediatePropagation();return}if(!window.dispatchEvent(new A({oldURL:j,newURL:n,action:`popstate`}))){e.stopImmediatePropagation(),window.history.go(M-t);return}P()}),window.addEventListener(`beforeunload`,function(e){if(!window.dispatchEvent(new A({oldURL:j,newURL:null,action:`beforeunload`})))return e.preventDefault(),e.returnValue=`o/`,`o/`});var F=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" focusable="false" role="presentation" tabindex="-1"> 3 <path d="M12 4L4 12" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 4 <path d="M4 4L12 12" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> 5</svg>`;function I(e){return new DOMParser().parseFromString(e,`image/svg+xml`).documentElement}var L=class e{static currentInstance=null;src=``;list=null;index=0;constructor(e){this.src=e}static fromList(t,n=0){let r=Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim().length>0):[];if(r.length===0){let t=new e(``);return t.list=[],t.index=0,t}let i=Math.min(Math.max(n,0),r.length-1),a=new e(r[i]);return a.list=r,a.index=i,a}
5openImageViewer(){if(!this.src)return;let t=this.makeViewerContainer();document.body.appendChild(t),this.animateContainer(),e.currentInstance=this,this.addKeyboardListeners()}closeImageViewer(){g(`.chatway--image-viewer-container`)?.remove(),this.removeKeyboardListeners(),e.currentInstance=null}handleKeyDown=e=>{e.key===`Escape`?this.closeImageViewer():e.key===`ArrowLeft`?this.prevImage():e.key===`ArrowRight`&&this.nextImage()};addKeyboardListeners(){document.addEventListener(`keydown`,this.handleKeyDown)}removeKeyboardListeners(){document.removeEventListener(`keydown`,this.handleKeyDown)}makeViewerContainer(){let e=document.createElement(`div`),t=document.createElement(`div`);t.classList.add(`chatway--image--container`);let n=this.makeImage();n.addEventListener(`load`,()=>{e.classList.add(`chatway--image--loaded`)});let r=this.makeCloseButton(),i=this.list&&this.list.length>1?this.makeThumbStrip():null,a=this.list&&this.list.length>1?this.makePrevButton():null,o=this.list&&this.list.length>1?this.makeNextButton():null;return t.appendChild(n),t.appendChild(r),a&&t.appendChild(a),o&&t.appendChild(o),i&&t.appendChild(i),e.classList.add(`chatway--image-viewer-container`),e.appendChild(t),e.addEventListener(`click`,t=>{t.target===e&&this.closeImageViewer()}),e}makeImage(){let e=new Image;return e.src=this.src,e.classList.add(`chatway--image-viewer-image`),e}makeThumbStrip(){let e=document.createElement(`div`);return e.classList.add(`chatway--image-thumbs`),this.list?.forEach((t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.classList.add(`chatway--image-thumb`),n===this.index&&r.classList.add(`active`);let i=new Image;i.src=t,i.alt=`Image ${n+1}`,r.appendChild(i),r.addEventListener(`click`,()=>this.setIndex(n)),e.appendChild(r)}),e}setIndex(e){if(!this.list||e<0||e>=this.list.length)return;let t=this.list[e];if(!t)throw Error(`Invalid image source at index ${e}`);this.index=e,this.src=t;let n=g(`.chatway--image-viewer-image`);n&&(n.src=this.src),document.querySelectorAll(`.chatway--image-thumb`).forEach((t,n)=>t.classList.toggle(`active`,n===e)),this.updateArrowButtons()}nextImage(){!this.list||this.index>=this.list.length-1||this.setIndex(this.index+1)}prevImage(){!this.list||this.index<=0||this.setIndex(this.index-1)}updateArrowButtons(){let e=g(`.chatway--image-prev-btn`),t=g(`.chatway--image-next-btn`);e&&(e.style.display=this.list&&this.index>0?`flex`:`none`),t&&(t.style.display=this.list&&this.index<this.list.length-1?`flex`:`none`)}convertStringToElement(e){return new DOMParser().parseFromString(e,`image/svg+xml`).documentElement}makeCloseButton(){let e=document.createElement(`a`);return e.href=`#`,e.classList.add(`dismiss--button`),e.setAttribute(`aria-label`,`Close`),e.appendChild(I(F)),e.addEventListener(`click`,e=>{e.preventDefault(),this.closeImageViewer()}),e}makePrevButton(){let e=document.createElement(`button`);return e.type=`button`,e.classList.add(`chatway--image-nav-btn`,`chatway--image-prev-btn`),e.style.display=this.index>0?`flex`:`none`,e.setAttribute(`aria-label`,`Previous image`),e.appendChild(this.convertStringToElement(`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> 6 <path d="M15 18L9 12L15 6" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> 7 </svg>`)),e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.prevImage()}),e}makeNextButton(){let e=document.createElement(`button`);return e.type=`button`,e.classList.add(`chatway--image-nav-btn`,`chatway--image-next-btn`),e.style.display=this.list&&this.index<this.list.length-1?`flex`:`none`,e.setAttribute(`aria-label`,`Next image`),e.appendChild(this.convertStringToElement(`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> 8 <path d="M9 18L15 12L9 6" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> 9 </svg>`)),e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.nextImage()}),e}animateContainer(){setTimeout(()=>{g(`.chatway--image-viewer-container`)?.classList.add(`enter-active`)},150)}},R=class e{static currentInstance=null;videoId;constructor(e){this.videoId=e}open(){e.currentInstance?.close();let t=this.makeContainer();document.body.appendChild(t),this.animateContainer(),e.currentInstance=this,document.addEventListener(`ke
9ydown`,this.handleKeyDown),t.focus()}close(){g(`.chatway--youtube-viewer-container`)?.remove(),document.removeEventListener(`keydown`,this.handleKeyDown),e.currentInstance=null}handleKeyDown=e=>{e.key===`Escape`&&this.close()};makeContainer(){let e=document.createElement(`div`);e.classList.add(`chatway--youtube-viewer-container`),e.setAttribute(`tabindex`,`-1`);let t=document.createElement(`div`);t.classList.add(`chatway--youtube-viewer-inner`);let n=this.makeCloseButton(),r=this.makePlayerWrapper();return t.appendChild(r),e.appendChild(n),e.appendChild(t),e.addEventListener(`click`,t=>{t.target===e&&this.close()}),e}getSafeEmbedUrl(){return/^[a-zA-Z0-9_-]{11}$/.test(this.videoId)?`https://www.youtube.com/embed/${this.videoId}?autoplay=1`:`about:blank`}makePlayerWrapper(){let e=document.createElement(`div`);e.classList.add(`chatway--youtube-viewer-player`);let t=document.createElement(`iframe`);return t.src=this.getSafeEmbedUrl(),t.setAttribute(`allow`,`autoplay; encrypted-media; fullscreen`),t.setAttribute(`allowfullscreen`,``),t.setAttribute(`frameborder`,`0`),t.setAttribute(`title`,`YouTube video player`),t.classList.add(`chatway--youtube-viewer-iframe`),e.appendChild(t),e}makeCloseButton(){let e=document.createElement(`button`);return e.type=`button`,e.classList.add(`chatway--youtube-viewer-close`),e.setAttribute(`aria-label`,`Close video`),e.appendChild(I(F)),e.addEventListener(`click`,()=>this.close()),e}animateContainer(){setTimeout(()=>{g(`.chatway--youtube-viewer-container`)?.classList.add(`enter-active`)},50)}},me;(function(e){e.fatal=`fatal`,e.error=`error`,e.warning=`warning`,e.log=`log`,e.info=`info`,e.debug=`debug`,e.critical=`critical`})(me||={});var he=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ge=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js))(?::(\d+))?(?::(\d+))?\s*$/i,_e=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ve=`X-Sentry-Auth`,ye=/^(?:(\w+):)\/\/(?:([\w-]+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/;function be(e){if(!e.stack)return null;let t=[],n=e.stack.split(` 10`),r,i;for(let a=0;a<n.length;++a){if(r=he.exec(n[a]))i={filename:r[2]&&r[2].indexOf(`address at `)===0?r[2].substr(11):r[2],function:r[1]||`?`,lineno:r[3]?+r[3]:null,colno:r[4]?+r[4]:null};else if(r=_e.exec(n[a]))i={filename:r[2],function:r[1]||`?`,lineno:+r[3],colno:r[4]?+r[4]:null};else if(r=ge.exec(n[a]))a===0&&!r[5]&&e.columnNumber!==void 0&&(t[0].column=e.columnNumber+1),i={filename:r[3],function:r[1]||`?`,lineno:r[4]?+r[4]:null,colno:r[5]?+r[5]:null};else continue;!i.function&&i.lineno&&(i.function=`?`),t.push(i)}return t.length?{value:z(e),type:e.name,stacktrace:{frames:t.reverse()}}:null}function z(e){return(e&&e.message||`No error message`).split(` 11`).filter(e=>!!e)[0]}function xe(e){try{let t=be(e);if(t)return t}catch{}return{value:z(e),type:e&&e.name,stacktrace:{frames:[]}}}function Se(){return`xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var Ce=class{constructor(e){if(e&&e.dsn){let t=ye.exec(e.dsn),n=t?t.slice(1):[],r=n[5].split(`/`),i=r.slice(0,-1).join(`/`);this.apiUrl=n[0]+`://`+n[3]+(n[4]?`:`+n[4]:``)+(i?`/`+i:``)+`/api/`+r.pop()+`/store/`,this.authHeader=`Sentry sentry_version=7,sentry_key=`+n[1]+(n[2]?`,sentry_secret=`+n[2]:``)}this.environment=e&&e.environment}prepare(e){return{...this.getRequestBlank(),exception:{values:[xe(e)]}}}report(e){this.send(this.prepare(e))}send(e){!this.apiUrl||!e||this.createRequest(e)}createRequest(e){let t=new XMLHttpRequest;t.open(`POST`,this.apiUrl,!0),t.setRequestHeader(`Content-type`,`application/json`),t.setRequestHeader(ve,this.authHeader||``),t.send(JSON.stringify(e))}getRequestBlank(){return{platform:`javascript`,event_id:Se(),sdk:{name:`micro-sentry.javascript.core`,version:`0.0.0`},timestamp:Date.now()/1e3,environment:this.environment}}};function B(e,t){return Object.prototype.toString.call(t)===`[object RegExp]`?t.test(e):typeof t==`string`?e.indexOf(t)!==-1:!1}function we(){return window}
11var Te=class e extends Ce{constructor(e,t=we()){super(e),this.options=e,this.window=t,this.destroyed=!1,this._state={};let{plugins:n=[],beforeSend:r=e=>e,beforeBreadcrumb:i=e=>e,blacklistUrls:a=[],ignoreErrors:o=[],release:s=void 0}=this.options||{};this.plugins=n.map(e=>new e(this)),this.beforeSend=r,this.beforeBreadcrumb=i,this.blacklistUrls=a,this.ignoreErrors=o,this.release=s}get state(){return this._state}clearState(){this._state={}}setTags(e){return this.setKeyState(`tags`,{...e}),this}setTag(e,t){return this.extendState({tags:{[e]:t}}),this}setExtra(e,t){return this.extendState({extra:{[e]:t}}),this}setExtras(e){return this.setKeyState(`extra`,{...e}),this}setUser(e){return this.setKeyState(`user`,{...e}),this}clone(){let t=new e({...this.options,plugins:[]});return t.extendState(this.state),t}withScope(e){let t=this.clone();e(t),t.destroy(),this.setBreadcrumbs(void 0)}addBreadcrumb(e){this.extendState({breadcrumbs:[{timestamp:Date.now()/1e3,...this.beforeBreadcrumb(e)}]})}setBreadcrumbs(e){this.setKeyState(`breadcrumbs`,e)}captureMessage(e,t){this.send({...this.getRequestBlank(),message:e,level:t})}destroy(){this.destroyed=!0,this.plugins.forEach(e=>{e.destroy&&e.destroy()})}isIgnoredError(e){return this.ignoreErrors.length?this.getPossibleEventMessages(e).some(e=>this.ignoreErrors.some(t=>B(e,t))):!1}getRequestBlank(){return{request:{url:this.window.location.toString(),headers:{"User-Agent":this.window.navigator.userAgent}},...super.getRequestBlank(),sdk:{name:`micro-sentry.javascript.browser`,version:`0.0.0`},...this.state}}send(e){this.destroyed||this.isDeniedUrl(e)||this.isIgnoredError(e)||(super.send(this.beforeSend({release:this.release,...e})),this.setBreadcrumbs(void 0))}getPossibleEventMessages(e){if(e.message)return[e.message];if(e.exception)try{let{type:t=``,value:n=``}=e.exception.values&&e.exception.values[0]||{};return[`${n}`,`${t}: ${n}`]}catch{return[]}return[]}isDeniedUrl(e){if(!this.blacklistUrls.length)return!1;let t=this.getEventFilterUrl(e);
11return t?this.blacklistUrls.some(e=>B(t,e)):!1}getEventFilterUrl(e){try{if(e.exception){let t=e.exception.values&&e.exception.values[0].stacktrace&&e.exception.values[0].stacktrace.frames;return t&&t[t.length-1].filename||null}return null}catch{return null}}extendState(e){this._state=Object.keys(e).reduce((t,n)=>{let r=this._state[n],i=Array.isArray(r)?r:null,a=e[n],o=Array.isArray(a)?a:null;return{...t,[n]:i||o?[...i||[],...o||[]]:{...typeof r==`string`?{}:r,...typeof a==`string`?{}:a}}},this._state)}setKeyState(e,t){this._state[e]=t}},V=class{init(){new Te({dsn:``,ignoreErrors:[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`Property description must be an object.`,`No error message`,`App container not found`,`JSON.parse: unexpected`,`Unexpected token`,`The string did not match the expected pattern.`]})}logError(e){}},H=()=>{let e=`https://prod-api.chatway.app/api/widget/`,t={headers:{"Content-Type":`application/json`,Accept:`application/json`}};function n(n,r){return fetch(e+n,{...t,...r,method:`get`})}function r(n,r,i){return fetch(e+n,{...t,...i,body:JSON.stringify(r),method:`post`})}function i(n,r,i){return fetch(e+n,{...t,...i,body:JSON.stringify(r),method:`put`})}function a(n,r,i){return fetch(e+n,{...t,...i,body:JSON.stringify(r),method:`PATCH`})}function o(n,r,i){return fetch(e+n,{...t,...i,body:JSON.stringify(r),method:`DELETE`})}return{post:r,get:n,put:i,patch:a,delete:o}},U=class{addCustomData({token:e,name:t,value:n}){return H().post(`chat-contacts/custom-fields`,{name:t,value:n},{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,Accept:`application/json`}})}deleteCustomData({token:e,name:t}){return H().delete(`chat-contacts/custom-fields`,{name:t},{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,Accept:`application/json`}})}updateEmailName({token:e,name:t,value:n}){return H().patch(`chat-contacts/profile`,{[t]:n},{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,Accept:`application/json`}})}deleteEmailName({token:e,name:t}){return H().patch(`chat-contacts/profile`,{remove:t},{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,Accept:`application/json`}})}addTag({token:e,tags:t}){return H().post(`chat-contacts/tags`,{tags:t},{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,Accept:`application/json`}})}deleteTag({token:e,tags:t}){return H().delete(`chat-contacts/tags`,{tags:t},{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,Accept:`application/json`}})}assignShopifyCustomer(e){return fetch(`${e.marketplace_origin}/apps/chatway-app-proxy/chat-contacts/${e.chat_contact_id}/assign-customer-id`,{method:`GET`,headers:{"Content-Type":`application/json`,"X-Requested-With":`XMLHttpRequest`}})}getShopifyCustomerData(e){return fetch(`${e.marketplace_origin}/apps/chatway-app-proxy/logged-in-customer-id`,{method:`GET`,headers:{"Content-Type":`application/json`,"X-Requested-With":`XMLHttpRequest`}})}saveShopifyCartData({token:e,chat_contact_id:t,cart_data:n}){return fetch(`https://prod-api.chatway.app/api/pixel/chat-contacts/${t}/cart-info`,{method:`POST`,body:JSON.stringify({cart_data:n}),headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,Accept:`application/json`}})}sendVisitorData(e){return H().post(`../notification/notify-new-visitor-on-website`,e,{headers:{"Content-Type":`application/json`,Accept:`application/json`}})}},W=class{async updateChatwayCustomData(e,t){try{if(!e||!t)return;let n=new D().getSessionToken();if(!n)return new Z().dispatchEvent(E.customData,JSON.stringify({name:e,value:t,method:`updateChatwayCustomData`}));let r=new U;if(e.toLowerCase()===`email`||e.toLowerCase()===`name`||e.toLowerCase()===`phone`){let{data:i}=await(await r.updateEmailName({token:n,name:e,value:t})).json(),a;return a={email:i.attributes.email,phone:i.attributes.phone},e===`name`&&(a={...a,name:i.attributes.name}),new Z().actionDispatcher(E.profileData,a),{message:`Success`}}return(await r.addCustomData({token:n,name:e,value:t})).json()}catch(e){new V().logError(e)}}getContactId(){return t.chatContactId}getContactToken(){return new D().getSessionToken()}async removeChatwayCustomData(e){try{if(!e)return;let t=new D().getSessionToken();if(!t)return new Z().dispatchEvent(E.customData,JSON.stringify({name:e,method:`removeChatwayCustomData`}));let n=new U;if(e.toLowerCase()===`email`||e.toLowerCase()===`name`||e.toLowerCase()===`phone`){let{data:r}=await(await n.deleteEmailName({token:t,name:e})).json(),i;return i={email:r.attributes.email,phone:r.attributes.phone},e===`name`&&(i={...i,name:`remove`}),new Z().actionDispatcher(E.profileData,i),r}return(await n.deleteCustomData({token:t,name:e})).json()}catch(e){new V().logError(e)}}hideChatwayIcon(){t.isHideChatwayIcon=!0;let e=document.getElementsByClassName(`chatway--trigger-icon-container`)[0];if(!e)return;e.classList&&e.classList.add(`hide--chatway`);let n=g(`.chatway--container`);n&&(t.agentMessage?n.classList.remove(`hide--widget`):n.classList.add(`hide--widget`))}showChatwayIcon(){let e=new Z;if(!(e.checkForPageRules(`show`)&&e.checkForPageRules(`hide`)))return;t.isHideChatwayIcon=!1;let n=document.getElementsByClassName(`chatway--trigger-icon-container`)[0];if(!n)return;n.classList&&n.classList.remove(`hide--chatway`);let r=g(`.chatway--container`);r&&r.classList.remove(`hide--widget`)}openChatwayWidget(){let e=document.querySelector(`.chatway--container`);if(!e)return;let n=e.classList.contains(`widget--open`),r=e.classList.contains(`disable--widget`),i=e.classList.contains(`hide--widget`),a=r||i;if(e.classList.remove(`disable--widget`),e.classList.remove(`hide--widget`),t.isHideChatwayIcon||document.querySelector(`.chatway--trigger-icon-container`)?.classList.remove(`hide--chatway`),n&&a){e.classList.remove(`widget--open`),e.offsetHeight,requestAnimationFrame(()=>{e.classList.add(`widget--open`)});return}n||(a?(e.offsetHeight,requestAnimationFrame(()=>{new Z().openWidget()})):new Z().openWidget())}closeChatwayWidget(){new Z().closeWidget()}isChatwayWidgetOpen(){let e=document.querySelector(`.chatway--container`);return e?e.classList.contains(`widget--open`):!1}isChatwayLoaded(){return t.hasAlreadyLoaded}async addChatwayTags(e){try{if(!e)return;let t=new D().getSessionToken();if(!t)return new Z().dispatchEvent(E.customData,JSON.stringify({tag:e,method:`addChatwayTags`}));let n=new U,r=Array.isArray(e)?e.map(e=>({name:e})):[{name:e}];return(await n.addTag({token:t,tags:r})).json()}catch(e){new V().logError(e)}}async removeChatwayTags(e){try{if(!e)return;let t=new D().getSessionToken();if(!t)return new Z().dispatchEvent(E.customData,JSON.stringify({tag:e,method:`removeChatwayTags`}));let n=new U,r=Array.isArray(e)?e.map(e=>({name:e})):[{name:e}];return(await n.deleteTag({token:t,tags:r})).json()}catch(e){new V().logError(e)}}setChatwaySettings(e){if(window.chatwaySettings=e,!e?.visitor)return;let{data:t,hmac:n}=e.visitor;!t?.id&&!t?.email||!n||new Z().dispatchEvent(E.setChatwaySettings,JSON.stringify(e))}openFaqChatwayWidget(){this.openChatwayWidget(),new Z().dispatchEvent(E.showFAQ)}sendMessage(e){if(!(!e||typeof e!=`string`||e.trim().length===0)){if(!t.isWidgetReady){t.pendingMessages.length>=5&&t.pendingMessages.shift(),t.pendingMessages.push(e);return}this.openChatwayWidget(),new Z().dispatchSendMessage(e)}}},G=new class{async assignCustomer(){if(!S()||!t.chatContactId)return;let e={chat_contact_id:t.chatContactId,marketplace_origin:S()};try{let t=await new U().assignShopifyCustomer(e);if(t&&t.status===200){let e=await t.json();new Z().dispatchEvent(E.setVisitorEmail,JSON.stringify(e))}}catch(e){console.log(e)}}isShopifyCartURL(e){if(typeof e!=`string`)return!1;let t=[`/cart/add`,`/cart/change`,`/cart/clear`,`/cart/add.js`,`/cart/change.js`,`/cart/clear.js`];try{let n=e.split(`/`).pop();return t.includes(`/cart/${n}`)}catch{return!1}}watchCartChange(){if(!window.fetch||typeof window.fetch!=`function`)return;let e=window.fetch,t=this;window.fetch=function(){let n=e.apply(this,arguments);return t.isShopifyCartURL(arguments[0])&&n.then(e=>{e.clone().json().then(e=>t.saveCartData(e))}),n}}async getCartData(){if(window?.Shopify?.routes?.root)try{return await(await fetch(window.location.origin+window.Shopify.routes.root+`cart.js`)).json()}catch(e){console.log(e)}}async saveCartData(e){let n=new D().getSessionToken(),r=e?.token?e:await this.getCartData();if(!n||!t.chatContactId||!r)return;let i={token:n,cart_data:r,chat_contact_id:t.chatContactId};try{await new U().saveShopifyCartData(i)}catch(e){console.error(e)}}async getCustomerData(){if(!S())return;let e={marketplace_origin:S()},n={};try{let r=await new U().getShopifyCustomerData(e);r&&r.status===200&&(n=await r.json(),n?.contact_id&&(t.chatContactId=n.contact_id),t.shopifyCustomerId=n?.logged_in_customer_id)}catch(e){console.log(e)}new Z().dispatchEvent(E.customerDataLoaded,JSON.stringify(n))}},K=[`mousemove`,`mousedown`,`keydown`,`scroll`,`touchstart`,`touchmove`],q={passive:!0,capture:!1},J=!1,Y=()=>
11{K.forEach(e=>window.removeEventListener(e,Y,!1)),J=!0},X=null;typeof window<`u`&&K.forEach(e=>window.addEventListener(e,Y,q));function Ee(e){let t=e.trim();if(!t)return null;try{return new URL(t.includes(`://`)?t:`https://${t}`).hostname.toLowerCase().replace(/^www\./,``)}catch{return null}}var Z=class{origin=`https://widget.chatway.app/`;actionType=`CHATWAY`;appContainer;chatwayLauncherIcon;chatwayCloseIcon;frameContainer;bodyContainer;triggerContainer;iconToggler;widgetStatus=!0;originalViewport=null;currentEvaluationUrl=null;boundMessageCallback;boundUrlChangeCallback;boundIconToggleHandler;constructor(){this.appContainer=t.appContainer,this.bodyContainer=document.getElementsByTagName(`body`)[0]?document.getElementsByTagName(`body`)[0]:null,this.frameContainer=t.frameContainer,this.triggerContainer=t.triggerContainer,this.iconToggler=t.iconToggler,this.chatwayLauncherIcon=t.chatwayLauncherIcon,this.chatwayCloseIcon=t.chatwayCloseIcon,this.boundMessageCallback=this.messageCallback.bind(this),this.boundUrlChangeCallback=this.urlChangeCallback.bind(this),this.boundIconToggleHandler=()=>{this.actionDispatcher(E.widgetToggle)}}setupEvents(){window.addEventListener(`message`,this.boundMessageCallback,!1),window.addEventListener(`urlchangeevent`,this.boundUrlChangeCallback,!1),!J&&!X&&K.forEach(e=>window.addEventListener(e,Y,q))}setupHumanActivityDetection(){K.forEach(e=>window.removeEventListener(e,Y,!1)),X&&=(K.forEach(e=>window.removeEventListener(e,X,!1)),null);let e=()=>{K.forEach(t=>window.removeEventListener(t,e,!1)),X=null,J=!0,this.dispatchEvent(E.humanActivityDetected)};X=e,K.forEach(t=>window.addEventListener(t,e,q))}cleanupEvents(){this.iconToggler?.removeEventListener(`click`,this.boundIconToggleHandler),window.removeEventListener(`message`,this.boundMessageCallback,!1),window.removeEventListener(`urlchangeevent`,this.boundUrlChangeCallback,!1),K.forEach(e=>window.removeEventListener(e,Y,!1)),X&&=(K.forEach(e=>window.removeEventListener(e,X,!1)),null)}async actionDispatcher(e,n=null){switch(e){case E.widgetToggle:this.toggleWidget();break;case E.widgetDestroy:new $().destroyApp();break;case E.widgetReload:new D().deleteUserConfig(),new $().destroyApp(),t.isChatInitialized=`false`,t.token=``,await ne(300),new $().initialize();break;case E.agentStatusChange:let e=t.previewTextBubbleDelay*1e3;setTimeout(()=>{this.toggleTextBubble({agentDetails:n,isNewMessage:!1,isStatusChange:!0})},e);break;case E.unreadMessage:this.handleUnread(n);break;case E.agentMessaged:this.handleIncomingMessage(n);break;case E.visitorConversationStarted:this.setVisitorID(n);break;case E.loadImage:this.loadImage(n);break;case E.loadYoutube:this.loadYoutube(n);break;case E.removeYoutube:this.removeYoutube();break;case E.newVisitorNotification:this.sendNewVisitorNotification(n);break;case E.removeImage:this.removeImage();break;case E.nextImage:this.nextImage();break;case E.prevImage:this.prevImage();break;case E.widgetDisable:this.toggleWidgetStatus(n);break;case E.widgetLoaded:t.isWidgetReady=!0,this.flushPendingMessages(),this.sendTheme(),await this.updateSessionKeys(),this.sendChatHistoryData(),this.sendWidgetData(),this.runConfigChecks(),this.emitIconState(),x()&&!new D().getSessionToken()&&G.getCustomerData(),this.triggerPageVisitedAutomation(),this.triggerQuickReplyVisibility(),this.checkPageRules(),J?this.dispatchEvent(E.humanActivityDetected):this.setupHumanActivityDetection();break;case E.profileData:this.setProfileData(n);break;case E.focusEvent:this.handleFocusEvent();break;case E.customData:this.saveCustomData(n);break;case E.removeToken:new D().deleteUserConfig();break;case E.chatContactLoaded:this.setContactData(n),this.syncWordPressData(),x()&&(G.saveCartData(),G.watchCartChange(),t.isVerifiedVisitor||await G.assignCustomer(),G.getCustomerData());break;case E.openContactChannel:this.openContactChannel(n);break;case E.copyToClipboard:this.copyToClipboard(n);break;case E.aiAssistantLoaded:this.setAIAssistant(n);break;case E.hasConversation:case E.hideQuickReplies:this.hideQuickReply();break;case E.quickReplyPositionUpdate:let r=g(`.chatway--quick--reply--container`)||g(`.chatway--preview--only--container`);if(r){let e=JSON.parse(n),i=t.appContainer;document.documentElement.style.setProperty(`--quick-reply-height`,e.height+`px`),document.documentElement.style.setProperty(`--quick-reply-width`,e.width+`px`),document.documentElement.style.setProperty(`--quick-reply-right`,e.right),document.documentElement.style.setProperty(`--quick-reply-left`,e.left),r.classList.contains(`chatway--quick--reply--container`)?(m(i,`quick--reply--open`),h(i,`preview--open`)):(m(i,`preview--open`),h(i,`quick--reply--open`))}break;case E.previewClosed:this.hidePreview(),this.hideQuickReply(),new D().setBubbleE
11xpiration();break;case E.hidePreviewText:this.hidePreview();break;case E.widgetExpand:this.handleWidgetExpand(n);break;case E.setVisitorDetails:new D().setVisitorDetails(JSON.parse(n));break;default:break}}setAIAssistant(e){if(e)try{t.aiAssistant=JSON.parse(e)}catch(e){console.error(`Failed to parse AI assistant data:`,e)}}saveCustomData(e){if(!new D().getSessionToken()||!e)return;let t=JSON.parse(e);switch(t.method){case`updateChatwayCustomData`:new W().updateChatwayCustomData(t.name,t.value);break;case`removeChatwayCustomData`:new W().removeChatwayCustomData(t.name);break;case`addChatwayTags`:new W().addChatwayTags(t.tag);break;case`removeChatwayTags`:new W().removeChatwayTags(t.tag);break;default:break}}addIconEvent(){this.iconToggler?.addEventListener(`click`,this.boundIconToggleHandler)}messageCallback(e){e.data.type&&e.data.type==this.actionType&&this.actionDispatcher(e.data.action,e.data.meta)}urlChangeCallback(e){try{let t=e.oldURL?.pathname||``,n=e.newURL?.pathname||``;if(e.action==`popstate`&&l()){let r=new O().isWidgetVisible;if(t===n&&!r||!r)return;if(t===n&&r){this.closeWidget();return}e.preventDefault(),this.closeWidget(),window.history?.pushState(null,``,window.location.href)}if(e.action==`pushState`&&e.oldURL.href!=e.newURL.href){let t=E.locationChange,n={origin:e.newURL.origin,path:e.newURL.pathname+e.newURL.search};this.dispatchEvent(t,JSON.stringify(n))}if(t!==n){try{this.currentEvaluationUrl=e.newURL?.href?new URL(e.newURL.href):null}catch{this.currentEvaluationUrl=null}this.triggerPageVisitedAutomation(e.newURL?.href),this.checkPageRules(),this.currentEvaluationUrl=null}}catch(e){new V().logError(e)}}toggleWidget(){new O().isWidgetVisible?this.closeWidget():this.openWidget()}closeWidget(){if(new O().isWidgetVisible){h(this.triggerContainer,`hide--chatway-trigger-on-open`),this.restoreViewport(),h(this.appContainer,`widget--open`),h(this.bodyContainer,`chatway-is-open`),this.emitIconState(),new D().setWidgetStatus(!1),y();let e={data:`false`,expireTime:Date.now()+3600*1e3};localStorage.setItem(`showTextBubble`,JSON.stringify(e)),window.removeEventListener(`popstate`,this.boundUrlChangeCallback,!1),this.dispatchWidgetStateEvent(!1)}}findAttentionEffectClass(e){let t=e?.className.match(/\S*effect\S*/);return t?t[0]:``}openWidget(){sessionStorage.getItem(`ch_quick_reply_open_${t.widgetID}`)===`true`&&this.hideQuickReply();let e=new k;e.isPreviewVisible&&e.hidePreview(),l()&&u()&&this.setupViewport();let n=new O().isWidgetVisible,r=document.getElementsByClassName(`chatway-launcher`)?document.getElementsByClassName(`chatway-launcher`)[0]:null;if(r&&this.findAttentionEffectClass(r)&&(r.classList&&r.classList.remove(this.findAttentionEffectClass(r)),new D().setShowAttentionEffect(!1)),window.history?.pushState({page:`widget`},``,window.location.href),window.addEventListener(`popstate`,this.boundUrlChangeCallback,!1),!n){let e=g(`.chatway--frame-container`);if(e.classList.remove(`chatway--preview--only--container`),e.classList.remove(`chatway--quick--reply--container`),e.classList.add(`chatway--chat--widget--container`),l()){let t=u();e.classList.toggle(`chatway--no-mobile-fullscreen`,!t),this.dispatchEvent(E.widgetExpand,JSON.stringify({isExpanded:t}))}h(this.appContainer,`preview--open`),h(this.appContainer,`quick--reply--open`),m(this.appContainer,`widget--open`),m(this.bodyContainer,`chatway-is-open`),re(),window.innerWidth<=601&&u()&&ie(),this.emitIconState(),new D().setWidgetStatus(!0),new D().setBubbleExpiration(),new O().focusIframe(),l()&&m(this.triggerContainer,`hide--chatway-trigger-on-open`),this.dispatchWidgetStateEvent(!0)}this.triggerLiveChatWidgetIsOpenedAutomation()}emitIconState(){if(this.appContainer){let e=E.widgetToggle,t=new O().isWidgetVisible,n={isOpen:!1};t&&(n.isOpen=!0),this.dispatchEvent(e,JSON.stringify(n))}}syncWordPressData(){window?.syncChatwayData&&window.syncChatwayData()}sendChatHistoryData(){let e=ae(`res_chtwy_cht`);if(e){let t=E.chatHistory,n={res_chtwy_cht:e};this.dispatchEvent(t,JSON.stringify(n))}}flushPendingMessages(){if(!t.pendingMessages.length)return;let e=t.pendingMessages.splice(0);
11new W().openChatwayWidget(),e.forEach(e=>this.dispatchSendMessage(e))}dispatchSendMessage(e){this.dispatchEvent(E.sendMessage,JSON.stringify({message:e}))}sendWidgetData(){let e=t.widgetData,n=new D,r={"bg-color":e.widget_color,"icon-color":v(e.widget_color),isMobileDevice:l(),userId:t.userID,widgetId:t.widgetID,origin:location.origin,hostSiteName:location.hostname,marketplace:b(),path:location.pathname+location.search,agents:this.getIncludedDataByWidget(),previewText:t.previewText,token:n.getSessionToken(),isChatInitialized:n.getChatInitStatus(),chatwaySettings:window.chatwaySettings,visitorStatus:this.checkForVisitorStatus(),wpUserInfo:window?.wpChatwaySettings,visitorDetails:n.getVisitorDetails(),...e,hostFontLinks:e.is_load_fonts_from_google===!1?this.getHostFontLinks():[]};this.dispatchEvent(E.widgetLoaded,JSON.stringify(r))}getHostFontLinks(){let t=new Set,n=Array.from(document.querySelectorAll(`head link[rel="stylesheet"]`));for(let r of n)try{let n=new URL(r.href);e.some(e=>n.hostname.includes(e))&&t.add(n.href)}catch{}return Array.from(t)}checkForVisitorStatus(){let e=o(`ch_visitor_id_${t.userID}`);return e?JSON.parse(e)?.expireTime>Date.now()?!1:(s(`ch_visitor_id_${t.userID}`),!0):!0}getIncludedDataByWidget(){return!t.included||!t.widgetID?t.agents||[]:t.included.filter(e=>e.type==`agents`||e.attributes.widget_id===t.widgetID).concat(t.agents||[])}runConfigChecks(){let e=new D().wasWidgetOpen;if(l()){if(t.widgetData.default_state===`opened`){e&&this.checkForPageRules(`show`)&&this.checkForPageRules(`hide`)&&this.toggleWidget();return}this.closeWidget();return}e&&this.checkForPageRules(`show`)&&this.checkForPageRules(`hide`)&&this.toggleWidget()}dispatchEvent(e,t=`{}`){try{let n=g(`#chatway_widget_app`),r={type:`CHATWAY`,action:e,meta:t};if(!n||n.contentWindow===null)return;n.contentWindow?.postMessage(r,`*`)}catch(e){new V().logError(e)}}toggleTextBubble(e){let n=new D,r=JSON.parse(e.agentDetails);t.agents=r,!(!t.widgetData.is_preview_text_enabled||n.showTextBubble===`false`&&!e.isNewMessage||t.isHideChatwayIcon&&e.isStatusChange)&&(t.status=r?.some(e=>e.attributes.online_status.toLowerCase()===`online`)?`online`:`offline`,new k().showPreviewInIframe(),n.setTextBubbleStatus(!0))}handleUnread(e){let n=JSON.parse(e);t.unReadCount=parseInt(n.count),new de().updatePendingStatus()}handleIncomingMessage(e){t.agentMessage=JSON.parse(e);let n=JSON.stringify(t.agents),r=t.widgetID;JSON.parse(sessionStorage.getItem(`ch_session_info_${r}`)||`{}`)?.widgetStatus!==`open`&&this.toggleTextBubble({agentDetails:n,isNewMessage:!0,isStatusChange:!1}),this.checkForPageRules(`show`)&&this.checkForPageRules(`hide`)&&(new k().showUnreadMessageInIframe(),this.toggleWidgetVisibility(!0))}ensurePreviewVisible(){if(new D().showTextBubble===`false`)return;t.isHideChatwayIcon&&this.toggleWidgetVisibility(!0);let e=g(`.chatway--preview-container`);e?.classList.contains(`hide--chatway`)&&e.classList.remove(`hide--chatway`)}setVisitorID(e){let n=JSON.parse(e),r=new D;t.token=n.token,t.isChatInitialized=n.isChatInitialized,r.setSessionToken(n.token),r.setChatInitStatus(n.isChatInitialized),this.addConversationStartedEvent(n.isChatInitialized),window?.syncChatwayData&&window.syncChatwayData()}addConversationStartedEvent(e){typeof window.$chatwayConversationStarted==`function`&&window.$chatwayConversationStarted({isChatInitialized:e})}setContactData(e){if(!e)return;let n=JSON.parse(e);t.chatContactId=n.contactId,t.isVerifiedVisitor=n.isVerified}setProfileData(e){let t=E.profileData;this.dispatchEvent(t,JSON.stringify(e))}async updateSessionKeys(){return new Promise((e,n)=>{try{let n=t.userID,a=new D,o=`ch_cw_token_${n}`,s=sessionStorage.getItem(o);s&&!a.getSessionToken()&&a.setSessionToken(s),sessionStorage.removeItem(o);let c=`ch_cw_status_${n}`,l=sessionStorage.getItem(c);l&&!a.getChatInitStatus()&&a.setChatInitStatus(l),sessionStorage.removeItem(c),r(`ch_cw_shw_atn_efct_${n}`)&&(a.setShowAttentionEffect(!0),i(`ch_cw_shw_atn_efct_${n}`)),sessionStorage.getItem(`ch_session_info_${n}`)&&(a.setUserConfig(JSON.parse(sessionStorage.getItem(`ch_session_info_${n}`)||`{}`)),sessionStorage.removeItem(`ch_session_info_${n}`)),e(`Tokens updated`)}catch{n(`Couldn't update tokens`)}})}handleFocusEvent(){this.closeWidget()}loadImage(e){try{let t=JSON.parse(e);if(t&&Array.isArray(t.list)){L.fromList(t.list,Number(t.index)||0).openImageViewer();return}new L(t.src).openImageViewer()}catch(e){new V().logError(e)}}async sendNewVisitorNotification(e){if(this.checkForVisitorStatus()&&e?.visitor_unique_id){let n={data:e.visitor_unique_id,expireTime:
11Date.now()+3600*1e3};a(`ch_visitor_id_${t.userID}`,JSON.stringify(n)),await new U().sendVisitorData(e)}}removeImage(){new L(``).closeImageViewer()}loadYoutube(e){try{let t=JSON.parse(e);if(!t?.videoId)return;new R(t.videoId).open()}catch(e){new V().logError(e)}}removeYoutube(){R.currentInstance?.close()}nextImage(){let e=L.currentInstance;e&&e.nextImage()}prevImage(){let e=L.currentInstance;e&&e.prevImage()}toggleWidgetStatus(e){this.widgetStatus=e;let t=g(`.chatway--container`);t&&(e?t.classList.remove(`disable--widget`):t.classList.add(`disable--widget`))}checkPageRules(){let e=t.pageRules;if(!e?.is_enable||!e?.rules||!e.rules.length){this.toggleWidgetVisibility(!0),this.applyDefaultWidgetState();return}let n=this.checkForPageRules(`show`),r=this.checkForPageRules(`hide`),i=n&&r;i?this.applyDefaultWidgetState():(t.agentMessage=null,new k().hidePreview()),this.toggleWidgetVisibility(i)}checkForPageRules(e){if(!t.pageRules)return!0;let n=this.currentEvaluationUrl||window.location,r=w(n.pathname+n.search+n.hash),i=C(n.host),a=e===`show`,o=!a,s=!1;for(let c of t.pageRules.rules){let t=C(c.domain),l=w(c.page),u=i===t,d=c.visibility==e,f=c.condition===`any-page`||c.condition===`contains`&&r.includes(l)||c.condition===`equals`&&r===l||c.condition===`start-with`&&r.startsWith(l)||c.condition===`end-with`&&r.endsWith(l)||c.condition===`homepage`&&n.pathname===`/`;u&&d&&(s=!0,f&&(o=a))}return s?o:!0}applyDefaultWidgetState(){let e=t.appContainer;if(e&&t.widgetData.default_state==`opened`&&!localStorage.getItem(`showTextBubble`)){e.classList.add(`widget--open`);let t=document.getElementsByTagName(`body`)[0];if(!t)return;if(t.classList.add(`chatway-is-open`),l()){let e=u();this.dispatchEvent(E.widgetExpand,JSON.stringify({isExpanded:e}))}}}toggleWidgetVisibility(e){let n=g(`.chatway--container`),r=g(`body`);if(!n||!r)return;let i=!!t.agentMessage,a=n.classList.contains(`widget--open`);if(t.isHideChatwayIcon){i||a?(n.classList.remove(`hide--widget`),r.classList.add(`chatway--active`)):(n.classList.add(`hide--widget`),r.classList.remove(`chatway--active`));return}e&&this.widgetStatus?(n.classList.remove(`hide--widget`),r.classList.add(`chatway--active`)):(n.classList.add(`hide--widget`),r.classList.remove(`chatway--active`))}checkVisibilityRules(){let e=g(`.chatway--container`);if(!e)return;let n=t.visibilityHours;if(t.visibilityHourTimezone==null||!n.length){t.isWidgetVisible=!0,this.checkForTriggers();return}let r=!1,i=new Date(new Date().toLocaleString(`en-US`,{timeZone:t.visibilityHourTimezone})),a=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,`0`)}-${String(i.getDate()).padStart(2,`0`)}`,o=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`][i.getDay()]?.toLowerCase(),s=n.filter(e=>e.is_custom&&e.custom_date===a);if(s.length)s.some(e=>!e.is_published&&(e.is_full_day||this.timeWithinRange(i,e.start_time,e.end_time)))||(r=s.some(e=>e.is_published)?s.some(e=>e.is_published&&(e.is_full_day||this.timeWithinRange(i,e.start_time,e.end_time))):!0);else{let e=n.filter(e=>!e.is_custom&&e.is_published&&e.day?.toLowerCase()===o);e.length&&(e.some(e=>e.hide_widget&&(e.is_full_day||this.timeWithinRange(i,e.start_time,e.end_time)))||(r=e.some(e=>!e.hide_widget)?e.some(e=>!e.hide_widget&&(e.is_full_day||this.timeWithinRange(i,e.start_time,e.end_time))):!0))}t.isWidgetVisible=r;let c=e.classList.contains(`widget--open`);r?(this.checkForTriggers(),this.checkPageRules()):c||(e.style.display=`none`,this.toggleWidgetVisibility(!1))}displayWidget(){let e=g(`.chatway--container`);e!==null&&e.classList.add(`has-loaded`),localStorage.setItem(`isWidgetVisible`,`true`)}checkForTriggers(){let{is_trigger_enabled:e,has_display_after_time:n,has_display_page_scroll:r,display_after_time:i,display_page_scroll:a}=t.widgetTriggers;if(this.toggleWidgetVisibility(!0),localStorage.getItem(`isWidgetVisible`)===`true`||!e){this.displayWidget();return}if(!n&&!r){this.displayWidget();return}n&&setTimeout(()=>this.displayWidget(),1e3*i),r&&(document.body.scrollHeight>window.innerHeight?window.onscroll=()=>{Math.ceil(window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100)>=a&&this.displayWidget()}:this.displayWidget())}timeWithinRange(e,t,n){let r=new Date(`${e.toDateString()} ${t}`),i=new Date(`${e.toDateString()} ${n}`);return e>=r&&e<=i}openContactChannel(e){if(e)try{let{channelUrl:t,target:n}=JSON.parse(e);window.open(t,n)}catch(e){new V().logError(e)}}copyToClipboard(e){if(e)try{let{text:t}=JSON.parse(e);navigator.clipboard.writeText(t)}
11catch(e){new V().logError(e)}}evaluatePageVisitTrigger=(e,t)=>{let{page:n,rule:r,domain:i}=e;if(!t)return console.warn(`Missing currentUrl in context for page visit trigger`),!1;try{t=new URL(t);let e=t.pathname,a=Ee(t.hostname),o=Ee(i);if(!a||!o||a!==o)return!1;switch(r){case`homepage`:return e===`/`||e===``;case`contains`:return t.href.includes(n);case`equals`:{let t=(n.startsWith(`/`)?n:`/${n}`).replace(/\/+$/,``);return e.replace(/\/+$/,``)===t}case`start-with`:return e.startsWith(n.startsWith(`/`)?n:`/${n}`);case`end-with`:return e.replace(/\/+$/,``).endsWith(n.replace(/\/+$/,``));case`any-page`:return!0;default:return console.warn(`Unknown page visit rule: ${r}`),!1}}catch(e){return console.error(`Error evaluating page visit trigger:`,e),!1}};triggerPageVisitedAutomation(e=window.location.href){!t.widgetData.has_paid_access||!t.widgetData.automation_triggers||t.widgetData.automation_triggers.filter(e=>e.type===`website_pages_are_visited`&&e.params).forEach(t=>{this.evaluatePageVisitTrigger(t.params,e)&&this.dispatchEvent(E.pageVisitAutomationTrigger,JSON.stringify(t))})}triggerLiveChatWidgetIsOpenedAutomation(){!t.widgetData.has_paid_access||!t.widgetData.automation_triggers||t.widgetData.automation_triggers.filter(e=>e.type===`live_chat_widget_is_opened`).forEach(e=>{this.dispatchEvent(E.liveChatWidgetIsOpenedAutomationTrigger,JSON.stringify(e))})}triggerQuickReplyVisibility(){if(g(`.chatway--container`)?.classList.contains(`hide--widget`))return;let e=new O().isWidgetVisible,n=sessionStorage.getItem(`ch_quick_reply_open_${t.widgetID}`);if(e||n===`false`)return;let r=t.widgetData,i=T(),a=r.device_preferences[i],o=a&&a.is_preview_text_enabled&&(a.is_enabled_reply_textbox||a.show_quick_responses&&a.quick_responses?.length),s=!(t.included?.filter(e=>e.type===`agents`)||[]).some(e=>e.attributes?.online_status?.toLowerCase()===`online`)&&a?.hide_automated_message_when_all_agent_offline&&!t.aiAssistant?.active,c=t.previewTextBubbleDelay*1e3;if(o&&!s){let e=g(`.chatway--frame-container`);if(!e)return;e.classList.remove(`chatway--chat--widget--container`),e.classList.remove(`chatway--preview--only--container`),setTimeout(()=>{g(`.chatway--container`)?.classList.contains(`hide--widget`)||new O().isWidgetVisible||(e.classList.add(`chatway--quick--reply--container`),sessionStorage.setItem(`ch_quick_reply_open_${t.widgetID}`,`true`),this.dispatchEvent(E.showQuickReplies,JSON.stringify({showQuickReply:!0})))},c)}else!s&&a&&a.is_preview_text_enabled&&setTimeout(()=>{new k().showPreviewInIframe()},c)}hideQuickReply(){if(sessionStorage.getItem(`ch_quick_reply_open_${t.widgetID}`)===`false`)return;let e=g(`.chatway--frame-container`);e&&(e.classList.remove(`chatway--quick--reply--container`),e.classList.remove(`chatway--preview--only--container`),e.classList.add(`chatway--chat--widget--container`)),h(this.appContainer,`quick--reply--open`),h(this.appContainer,`preview--open`),sessionStorage.setItem(`ch_quick_reply_open_${t.widgetID}`,`false`),this.dispatchEvent(E.hideQuickReplies,JSON.stringify({showQuickReply:!1}))}hidePreview(){new k().hidePreview()}expandedOriginalStyles=null;expandCleanupTimer=null;handleWidgetExpand(e){try{let n=typeof e==`string`?JSON.parse(e):e,r=g(`.chatway--frame-container`);if(!r)return;if(l()){let e=r.style.transition;r.style.transition=`none`,n?.isExpanded?(r.classList.remove(`chatway--no-mobile-fullscreen`),this.setupViewport(),ie(),this.triggerContainer&&m(this.triggerContainer,`hide--chatway-trigger-on-open`)):(r.classList.add(`chatway--no-mobile-fullscreen`),this.restoreViewport(),y()),requestAnimationFrame(()=>requestAnimationFrame(()=>{r.style.transition=e}));return}if(n?.isExpanded){this.expandCleanupTimer&&=(clearTimeout(this.expandCleanupTimer),null),this.triggerContainer?.parentElement?.classList.add(`chatway-trigger--behind`);let e=window.innerWidth;if(e>600){this.expandedOriginalStyles||={right:r.style.right,left:r.style.left};let n=t.widgetData,i=Math.min(688,e-40);if(n.position===`custom`){let t=n.side_spacing||0;if(n.custom_position_side===`left`){let n=e-i-20;r.style.left=`${Math.max(0,Math.min(t,n))}px`,r.style.right=``}else{let n=e-i-20;r.style.right=`${Math.max(0,Math.min(t,n))}px`,r.style.left=``}}else if(n.position===`left`){let t=parseInt(r.style.left,10)||20,n=e-i-20;t>n&&(r.style.left=`${Math.max(0,n)}px`)}else{let t=parseInt(r.style.right,10)||20,n=e-i-20;t>n&&(r.style.right=`${Math.max(0,n)}px`)}let a=(parseInt(r.style.bottom,10)||84)+20,o=document.getElementById(`chatway-expanded-style`);o||(o=document.createElement(`style`),o.id=`chatway-expanded-style`,document.head.appendChild(o)),o.textContent=`.chatway--chat--widget--container.chatway--expanded { height: calc(100vh - ${a}px) !important; max-height: calc(100vh - ${a}px) !important; }`}r.classList.add(`chatway--expanded`)}else this.triggerContainer?.parentElement?.classList.remove(`chatway-trigger--behind`),this.expandedOriginalStyles&&=(r.style.right=this.expandedOriginalStyles.right,r.style.left=this.expandedOriginalStyles.left,null),r.classList.remove(`chatway--expanded`),this.expandCleanupTimer=setTimeout(()=>{let e=document.getElementById(`chatway-expanded-style`);e&&e.remove(),this.expandCleanupTimer=null},220)}catch(e){new V().logError(e)}}
11resolveThemeFromBackground(){for(let e of[document.documentElement,document.body]){if(!e)continue;let t=getComputedStyle(e).backgroundColor.match(/[\d.]+/g)?.map(Number);if(!(!t||t.length<3)&&!((t[3]??1)<.9))return(.299*t[0]+.587*t[1]+.114*t[2])/255<.5?`dark`:`light`}return window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}sendTheme(){let e=getComputedStyle(document.documentElement).colorScheme,t;t=e===`dark`?`dark`:e===`light`?`light`:e===`light dark`||e===`dark light`?this.resolveThemeFromBackground():`auto`,this.dispatchEvent(E.themeUpdate,JSON.stringify({theme:t}))}setupViewport(){if(this.originalViewport!=null)return;let e=document.querySelector(`meta[name="viewport"]`);if(e)this.originalViewport={exists:!0,content:e.getAttribute(`content`)},e.setAttribute(`content`,`width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no`);else{this.originalViewport={exists:!1};let e=document.createElement(`meta`);e.name=`viewport`,e.content=`width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no`,document.head.appendChild(e)}}restoreViewport(){if(!this.originalViewport)return;let e=document.querySelector(`meta[name="viewport"]`);if(!e){if(this.originalViewport.exists){let e=document.createElement(`meta`);e.name=`viewport`,e.content=this.originalViewport.content||``,document.head.appendChild(e)}return}this.originalViewport.exists?e.setAttribute(`content`,this.originalViewport.content):e.remove(),this.originalViewport=null,document.body.offsetHeight}dispatchWidgetStateEvent(e){try{let t=new CustomEvent(e?`chatwayWidgetOpened`:`chatwayWidgetClosed`,{detail:{isOpen:e},bubbles:!0});document.dispatchEvent(t),typeof window.$chatwayWidgetStateChange==`function`&&window.$chatwayWidgetStateChange({isOpen:e})}catch(e){console.error(e)}}},De=class{constructor(e,t,n){this.widgetIcon=e,this.widgetColor=t,this.widgetImage=n}getChatIcon(){let e=null;switch(!0){case this.widgetIcon==`chat-base`:e=this.chatBase;break;case this.widgetIcon==`chat-smile`:e=this.chatSmile;break;case this.widgetIcon==`chat-bubble`:e=this.chatBubble;break;case this.widgetIcon==`chat-db`:e=this.chatDb;break;case this.widgetIcon==`chat-image`:e=this.chatImage;break;default:e=``;break}return this.widgetIcon==`chat-image`?this.parseImage(e):this.convertStringToElement(e)}hasCustomImage(){return this.widgetIcon==`chat-image`}getCloseIcon(){return this.convertStringToElement(this.closeIcon)}convertStringToElement(e){let t=new DOMParser().parseFromString(e,`image/svg+xml`),n=t.querySelectorAll(`.fill--element`);return n.length>0&&n.forEach(e=>e.setAttribute(`fill`,this.widgetColor)),t.documentElement}parseImage(e){return new DOMParser().parseFromString(e,`text/html`).querySelector(`img`)}get chatBase(){return` 12 <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"> 13 <path 14 fill-rule="evenodd" 15 clip-rule="evenodd" 16 d="M10.7322 5H24.5989C26.2878 5 27.71 6.42222 27.6211 8.11111V24.1111C27.6211 24.4667 27.4433 24.7334 27.1767 24.9111H26.91C26.5544 24.9111 26.4655 24.9111 26.2878 24.7333L24.5989 23.0444V12.7333C24.5989 10.1556 22.5544 8.11111 19.9766 8.11111H7.62109C7.62109 6.42222 9.04332 5 10.7322 5ZM6.11111 9.62305H19.9778C21.6667 9.62305 23.0889 11.0453 23.0889 12.7342V28.9119C23.0889 29.2675 22.9111 29.5341 22.6444 29.7119H22.3778C22.0222 29.7119 21.9333 29.7119 21.7556 29.5341L17.3111 25.0897H6.11111C4.42222 25.0897 3 23.6675 3 21.9786V12.7342C3 11.0453 4.42222 9.62305 6.11111 9.62305Z" 17 fill="currentColor" 18 /> 19 </svg> 20 `}get chatBubble(){return` 21 <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"> 22 <path 23 d="M13.2222 5H17.9333C20.6 5 23.2667 6.06669 25.1333 8.02224C27 9.88891 28.1556 12.5556 28.1556 15.2222C28.1556 20.5556 24.0667 25 18.7333 25.4444V29.3556C18.7333 29.7111 18.5556 29.9778 18.2889 30.1556C18.1111 30.1556 18.1111 30.1556 17.9333 30.1556C17.7556 30.1556 17.4889 29.9778 17.3111 29.8L13.2222 25.3556C10.5556 25.3556 7.88888 24.2889 6.02222 22.3333C4.15555 20.3778 3 17.8 3 15.1334C3 9.53335 7.62222 5 13.2222 5ZM21.8445 16.7333C22.8222 16.7333 23.4444 16.1111 23.4444 15.1334C23.4444 14.1556 22.8222 13.5334 21.8445 13.5334C20.8667 13.5334 20.2444 14.1556 20.2444 15.1334C20.3333 16.1111 20.9556 16.7333 21.8445 16.7333ZM15.6222 16.7333C16.6 16.7333 17.2222 16.1111 17.2222 15.1334C17.2222 14.1556 16.6 13.5334 15.6222 13.5334C14.6445 13.5334 14.0222 14.1556 14.0222 15.1334C14.0222 16.1111 14.6445 16.7333 15.6222 16.7333ZM9.31112 16.7333C10.2889 16.7333 10.9111 16.1111 10.9111 15.1334C10.9111 14.1556 10.2889 13.5334 9.31112 13.5334C8.33334 13.5334 7.71113 14.1556 7.71113 15.1334C7.71113 16.1111 8.33334 16.7333 9.31112 16.7333Z" 24 fill="currentColor" 25 /> 26 </svg> 27 `}get chatDb(){return` 28 <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"> 29 <path 30 d="M25.2891 6C27.0668 6.00009 28.5781 7.51134 28.7559 9.28906V27.4004C28.7557 27.6669 28.5779 28.0225 28.2227 28.2002H27.8662C27.5998 28.2002 27.4218 28.2001 27.2441 28.0225L22.4443 24.2227H5.28906C3.51137 24.2227 2.00015 22.8001 2 20.9336V9.28906C2 7.51128 3.4224 6 5.28906 6H25.2891ZM22.2441 15.3203C21.942 15.0372 21.4678 15.0524 21.1846 15.3545C17.72 19.0496 13.1582 18.5723 10.8984 17.749L10.4775 17.5811L10.4062 17.5537C10.0447 17.4366 9.64571 17.6096 9.48926 17.9648C9.33334 18.3199 9.47465 18.7314 9.80469 18.9189L9.87402 18.9541L10.1064 19.0518C12.6081 20.0554 18.1091 20.8267 22.2783 16.3799C22.5615 16.0778 22.546 15.6036 22.2441 15.3203ZM22.8223 12.5918C22.2936 12.4142 21.6916 12.3998 21.0254 12.5596C20.6227 12.6562 20.3742 13.0612 20.4707 13.4639C20.5676 13.8663 20.9725 14.1141 21.375 14.0176C21.8193 13.911 22.1293 13.9413 22.3447 14.0137C22.5591 14.0858 22.7339 14.2178 22.8809 14.4014C23.1549 14.7442 23.3069 15.2368 23.3662 15.6621L23.3857 15.8398L23.3965 15.916C23.4664 16.2894 23.8095 16.5576 24.1963 16.5254C24.6084 16.4905 24.915 16.1271 24.8809 15.7148C24.8302 15.108 24.6275 14.1836 24.0527 13.4648C23.7555 13.0934 23.3516 12.7697 22.8223 12.5918Z" 31 fill="currentColor" 32 /> 33 </svg> 34 `}get chatSmile(){return` 35 <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"> 36 <path 37 d="M23.9473 4C26.7378 4 29 6.26224 29 9.05273V22.2236C28.9998 25.0139 26.7376 27.2754 23.9473 27.2754H20.8984C20.1689 27.27
3754 19.4749 27.5911 18.9951 28.1406L17.2539 30.1367C16.8554 30.5934 16.1446 30.5934 15.7461 30.1367L14.0049 28.1406C13.5251 27.5911 12.8311 27.2754 12.1016 27.2754H9.05273C6.26238 27.2754 4.00022 25.0139 4 22.2236V9.05273C4 6.26224 6.26224 4 9.05273 4H23.9473ZM12.5 18.5C11.7903 18.5 11 18.4711 11 19.0518C11.0001 21.2325 13.3347 24 16 24H17C19.6653 24 21.9999 21.2325 22 19.0518C22 18.4711 21.2097 18.5 20.5 18.5H12.5Z" 38 fill="currentColor" 39 /> 40 </svg> 41 `}get chatImage(){return`<img class="" src="${this.widgetImage}" alt="">`}get closeIcon(){return` 42 <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"> 43 <path 44 d="M8 12L16 20L24 12" 45 stroke="currentColor" 46 stroke-width="2.67" 47 stroke-linecap="round" 48 stroke-linejoin="round" 49 /> 50 </svg> 51 `}},Oe=class{_svgBuilder;widgetData;constructor(){this.widgetData=t.widgetData,this._svgBuilder=new De(this.widgetData.widget_icon,v(this.widgetData.widget_color),this.widgetData.widget_icon_url)}makeIconContainer(){let e=document.createElement(`div`);return e.classList.add(`chatway-launcher`),e.style.background=this.widgetData.widget_color,new D().getShowAttentionEffect()&&this.widgetData.default_state===`click`&&e.classList.add(this.widgetData.attention_effect+`-effect`),e}makeLauncherContainer(){let e=document.createElement(`button`);e.classList.add(`launcher-icon`),e.classList.add(`launcher-default-open-icon`),e.classList.add(`launcher-default-open-animated`),e.style.color=this.getIconColor(),e.style.background=this.widgetData.widget_color;let n=this._svgBuilder.getChatIcon();n.setAttribute(`aria-hidden`,`true`);let r=document.createElement(`span`);return r.classList.add(`sr-only`),r.innerText=`Show Chatway Messenger`,this._svgBuilder.hasCustomImage()&&e.classList.add(`has-custom-image`),e.appendChild(n),e.appendChild(r),t.chatwayLauncherIcon=e,e}makeAnimatedContainer(){let e=document.createElement(`button`);e.classList.add(`launcher-icon`),e.classList.add(`animatedIcon`),e.style.background=this.widgetData.widget_color,e.style.color=this.getIconColor();let t=document.createElement(`dotlottie-player`);return t.setAttribute(`src`,`https://lottie.host/6468be3e-a133-4b36-aba2-01a8014e8406/LoRT0NHpMO.json`),t.setAttribute(`background`,`transparent`),t.setAttribute(`speed`,`1`),t.setAttribute(`style`,`width: inherit; height: inherit;`),t.setAttribute(`loop`,`true`),t.setAttribute(`autoplay`,`true`),e.appendChild(t),e}makeCloseContainer(){let e=document.createElement(`button`);e.classList.add(`launcher-icon`),e.classList.add(`launcher-minimize-icon`),e.style.background=this.widgetData.widget_color,e.style.color=this.getIconColor();let n=document.createElement(`span`);n.classList.add(`sr-only`),n.innerText=`Hide Chatway Messenger`;let r=this._svgBuilder.getCloseIcon();return e.appendChild(r),e.appendChild(n),t.chatwayCloseIcon=e,e}makeIcon(){let e=this.makeIconContainer(),t=this.makeLauncherContainer(),n=this.makeCloseContainer();return e.appendChild(t),e.appendChild(n),e}getIconColor(){let e=this.widgetData?.widget_icon_color?.trim().toUpperCase();return e&&e!==`#FFFFFF`&&e!==`#FFF`?this.widgetData.widget_icon_color:this.getTextColor(v(this.widgetData.widget_color))}getTextColor=e=>{if(!e)return`#ffffff`;let t=0,n=0,r=0;if(e.startsWith(`#`)){let i=e.slice(1);t=parseInt(i.slice(0,2),16),n=parseInt(i.slice(2,4),16),r=parseInt(i.slice(4,6),16)}else if(e.startsWith(`rgb`)){let i=e.match(/\d+/g);if(!i||i.length<3)return`#ffffff`;t=parseInt(i[0]),n=parseInt(i[1]),r=parseInt(i[2])}else return`#FFFFFF`;return.299*t+.587*n+.114*r>150?`#000000`:`#FFFFFF`}},Q=e=>new Promise(function(t,n){var r=new XMLHttpRequest;r.open(`GET`,e,!0),typeof r.setRequestHeader==`function`&&(r.setRequestHeader(`Content-Type`,`application/json`),r.setRequestHeader(`Accept`,`application/json`)),r.onload=function(){r.status==200?t(JSON.parse(r.responseText)):n(`Error `+r.status+`: `+r.statusText)},r.onerror=function(){n(`Network error`)},r.send()}),ke=new class{botPatterns;headlessAgents;constructor(){this.botPatterns=`bot.crawler.spider.scraper.facebookexternalhit.facebookcatalog.twitterbot.linkedinbot.whatsapp.slackbot.discord.telegram.skype.pinterest.tumblr.reddit.quora.lighthouse.gtmetrix.pingdom.uptimerobot.statuscake.newrelic.appinsights.googlebot.bingbot.yandexbot.duckduckbot.baiduspider.sogou.exabot.konqueror.ia_archiver.ahrefsbot.semrushbot.dotbot.mj12bot.blexbot.dataprovider.dataforseo.megaindex.serpstatbot.petalbot.amazonbot.applebot.chrome-lighthouse.headlesschrome.phantomjs.selenium.puppeteer.playwright.webdriver.wget.curl.python-requests.python-urllib.go-http-client.java/.apache-httpclient.okhttp.postman.insomnia.paw/.rest-client.ruby/.perl/.php/.node-fetch.axios/.got/.superagent`.split(`.`),this.headlessAgents=[`headlesschrome`,`phantomjs`,`slimerjs`,`selenium`,`puppeteer`]}isBot(){if(window.Cypress)return!1;let e=navigator.userAgent.toLowerCase();return!!(!e||e===`0`||this.botPatterns.some(t=>e.includes(t))||this.isHeadlessBrowser())}isHeadlessBrowser(){let e=navigator.userAgent.toLowerCase();if(this.headlessAgents.some(t=>e.includes(t))||navigator.webdriver)return!0;for(let e of[`__driver_evaluate`,`__webdriver_evaluate`,`__selenium_evaluate`,`__fxdriver_evaluate`,`_Selenium_IDE_Recorder`,`_WEBDRIVER_ELEM_CACHE`,`callSelenium`,`callPhantom`])if(e in window)return!0;return!1}},$=class{scriptId;widgetId;loadFromCdn;constructor(){}start(){this.isChatwayInstalled||ke.isBot()||(this.setupGlobalFunctions(),this.addWindowLoadEvent())}getEcwidShopID(){let e=0;return typeof window.Ecwid==`object`&&(e=window.Ecwid.getOwnerId()),e}async initialize(){if(!t.hasAlreadyLoaded)try{if(this.setChatLoadedStatus(!0),this.removeWindowLoadEvent(),this.setIdentifiers(),!this.scriptId&&!this.widgetId)return;te(),await this.fetchWidgetData()&&(this.checkForChatyScript(),this.buildApp())}catch(e){new V().logError(e)}}addWindowLoadEvent(){document.readyState==`complete`?this.initialize():window.addEventListener&&window.addEventListener(`load`,()=>{this.initialize()},!0)}addChatwayLoadedEvent(){typeof window.$chatwayOnLoad==`function`&&window.$chatwayOnLoad({widgetId:t.widgetID,timestamp:Date.now()}),document.dispatchEvent(new CustomEvent(`chatwayLoaded`,{detail:{widgetId:t.widgetID,timestamp:Date.now()},bubbles:!0}))}removeWindowLoadEvent(){window.removeEventListener(`load`,this.initialize),window.removeEventListener(`chatwayLoaded`,this.addChatwayLoadedEvent)}setIdentifiers(){this.scriptId=d(`chatway`,`id`),this.widgetId=d(`chatway`,`widget_id`),this.loadFromCdn=!!d(`chatway`,`cdn`),!this.scriptId&&window.wpChatwaySettings?.widgetId&&(this.scriptId=window.wpChatwaySettings.widgetId),!this.scriptId&&!window.wpChatwaySettings?.widgetId&&this.getEcwidShopID()&&(this.scriptId=this.getEcwidShopID().toString()),t.userID=this.scriptId}async fetchLocationData(){try{return await(await fetch(`https://www.cloudflare.com/cdn-cgi/trace`,{method:`GET`})).text()}catch(e){console.log(e)}return``}async fetchWidgetData(){try{let e=oe(await this.fetchLocationData()),n=e?.ip||``,r=e?.loc||``,i=l()?1:0,a=d(`chatway`,`id`),o=``;!a&&this.getEcwidShopID()&&(o=`ecwid`);let s=C(window.location.hostname),c=null,u=`include[]=faqs&ip=${n}&is_mobile=${i}&loc=${r}&channel=${o}&domain=${s}`;if(!this.loadFromCdn&&o!==`ecwid`){let e=`https://prod-api.chatway.app/
51api/v3/pixel/widget-version`,{data:t}=await Q(this.widgetId?`${e}/widget/${this.widgetId}?${u}`:`${e}/${this.scriptId}?${u}`);if(!t?.attributes?.url)throw Error(`No widget version JSON URL returned for ${this.scriptId}`);let n=await fetch(t.attributes.url);if(!n.ok)throw Error(`Failed to fetch widget JSON (${n.status}) for ${this.scriptId}`);c=await n.json()}else{let e=`https://prod-api.chatway.app/api/v2/pixel/widgets`,t=`${!a&&this.getEcwidShopID()?`site_identifier`:`user_identifier`}=${this.scriptId}`;c=await Q(this.widgetId?`${e}/${this.widgetId}?&include[]=agents&${u}`:`${e}?${t}&include[]=agents&${u}`)}if(!c||!c.data)throw Error(`No data returned from API for ${this.scriptId}`);let{data:f,included:p}=c;if(f?.attributes?.is_ch_ob==0)return!1;let m=null;if(Array.isArray(f)?f.length>1?(t.widgets=f,this.setupPushState(),m=this.getWidgetByPageRules()):f.length===1&&(m=f[0]):f&&f.attributes&&(m=f),!m||!m.attributes)return!1;let h=m.attributes;return h.is_blocked?!1:(!this.loadFromCdn&&o!==`ecwid`&&await this.fetchAgents(m.id,h.team_id),t.included=p,t.browserData=e,this.setWidgetId(m.id),this.setWidgetData(h),this.setPageTitle(document.title),this.setVisibilityHourTimezone(h.timezone),this.setPageRules(h),this.setWidgetVisibilityHour(),this.setWidgetTriggers(),this.setDevicePreferences(),!0)}catch(e){throw new V().logError(e),e}}async fetchAgents(e,n){try{let{data:r}=await Q(`https://prod-api.chatway.app/api/v2/pixel/widget-agents/${this.scriptId||n}/${e}`);r&&r.attributes.data.length>0&&(t.agents=r.attributes.data)}catch(e){throw console.log(e),new V().logError(e),e}}setupPushState(){let e=history.pushState;history.pushState=async(...t)=>{e.apply(history,t),this.handleWidgetOnPageChange()}}async handleWidgetOnPageChange(){let e=this.getWidgetByPageRules();if(!e||e.id==t.widgetID){new Z().checkVisibilityRules();return}let n=e.attributes;if(n.is_blocked){await this.destroyApp();return}this.setWidgetId(e.id),this.setWidgetData(n),this.setPageTitle(document.title),this.setVisibilityHourTimezone(n.timezone),this.setPageRules(n),this.setWidgetVisibilityHour(),this.setWidgetTriggers(),this.setDevicePreferences(),await this.destroyApp(),this.setChatLoadedStatus(!0),await this.buildApp()}getWidgetByPageRules(){let e=t.widgets.reduce((e,t)=>{let{id:n,attributes:r}=t;return r.page_targeting.is_enable&&r.page_targeting.rules.length>0&&(e[n]=r.page_targeting.rules),e},{});if(!Object.values(e)?.length)return t.widgets[0];let n=this.getWidgetIdByPageRules(e);return n?t.widgets.find(e=>e.id===n)||null:this.getFallbackWidget(e)}getWidgetIdByPageRules(e){for(let[t,n]of Object.entries(e)){let e=new Set(n.filter(e=>C(e.domain)==C(window.location.host)).map(e=>e.visibility));if(e.size===1){let r=[...e][0],i=n.some(e=>this.matchPageRule(e));if(r===`show`&&i||r===`hide`&&!i)return t}else{let e=n.some(e=>e.visibility===`hide`&&this.matchPageRule(e));if(n.some(e=>e.visibility===`show`&&this.matchPageRule(e))&&!e)return t}}return null}matchPageRule(e){let t=C(window.location.host);if(C(e.domain)!==t)return!1;let n=w(window.location.pathname),r=w(window.location.pathname+window.location.search+window.location.hash),i=w(e.page);switch(e.condition){case`equals`:return r===i;case`any-page`:return!0;case`contains`:return r.includes(i);case`start-with`:return r.startsWith(i);case`end-with`:return r.endsWith(i);case`homepage`:return n===`/`;default:return!1}}getFallbackWidget(e){return Object.entries(e).flatMap(([e,t])=>t.map(t=>({...t,widget_id:e}))).find(e=>!this.matchPageRule(e))?null:t.widgets.find(e=>!e.attributes.page_targeting.is_enable)||null}setWidgetId(e){t.widgetID=e}setWidgetData(e){t.widgetData={...e,browserData:t.browserData}}setPageTitle(e){t.pageTitle=e}setVisibilityHourTimezone(e){t.visibilityHourTimezone=e}setChatLoadedStatus(e){t.hasAlreadyLoaded=e}setDevicePreferences(){if(!t.included||!t.widgetID)return;let e=t.included.filter(e=>e.type===`device_preferences`&&e.attributes.widget_id===t.widgetID),n=t.widgetData,r=e.find(e=>e.attributes.is_mobile),i=e.find(e=>!e.attributes.is_mobile),a=t.included.filter(e=>e.type===`device_preference_quick_response`);if(r&&i)n.device_preferences={desktop:{...i.attributes,quick_responses:a.filter(e=>!e.attributes.is_mobile).map(e=>({order_id:e.attributes.order_id,text:e.attributes.text}))},mobile:{...r.attributes,quick_responses:a.filter(e=>e.attributes.is_mobile).map(e=>({order_id:e.attributes.order_id,text:e.attributes.text}))}};else{let e={position:n?.position,custom_position_side:n?.custom_position_side,bottom_spacing:n?.bottom_spacing,side_spacing:n?.side_spacing,custom_widget_size:n?.custom_widget_size,is_preview_text_enabled:!!n?.is_preview_text_enabled,preview_text_bubble_delay:n?.preview_text_bubble_delay,preview_text:n?.preview_text,is_welcome_text_enabled:n?.is_wel
51come_text_enabled,widget_size:n?.widget_size,is_enabled_reply_textbox:!1,show_quick_responses:!1,hide_automated_message_when_all_agent_offline:!1,quick_responses:[]};n.device_preferences={desktop:e,mobile:e}}if(!t.widgetData)return;let o=!n.is_separate_device_preference&&n.device_appearance===`both`?`desktop`:l()?`mobile`:`desktop`,s=n.device_preferences[o];Object.keys(s).forEach(e=>{t.widgetData[e]=s[e]}),t.previewText=this.getPreviewText(n.device_preferences[o].preview_text,o),t.previewTextBubbleDelay=n.device_preferences[o].preview_text_bubble_delay}setPageRules(e){e?.has_paid_access&&e?.page_targeting?.is_enable&&e?.page_targeting?.rules.length>0?t.pageRules=e?.page_targeting:t.pageRules={is_enable:!1,rules:[]}}setWidgetTriggers(){let e={is_trigger_enabled:!1,has_display_after_time:!1,display_after_time:0,has_display_page_scroll:!1,display_page_scroll:0,widget_id:``};if(!t.included||!t.widgetID){t.widgetTriggers=e;return}t.included.forEach(n=>{n.type===`widget_trigger`&&n.attributes.widget_id===t.widgetID&&(e=n.attributes)}),t.widgetTriggers=e}setWidgetVisibilityHour(){if(!t.included||!t.widgetID){t.visibilityHours=[];return}let e=[];t.included.forEach(n=>{n.type===`widget_visibility_hour`&&n.attributes.widget_id===t.widgetID&&e.push(n.attributes)}),t.visibilityHours=e}checkForChatyScript(){if(document.getElementById(`pixel-chaty`)){let e=document.getElementsByTagName(`body`)[0]?document.getElementsByTagName(`body`)[0]:null;e&&e.classList.add(`has--chaty`)}}async buildApp(){try{let e=new O,n=await e.makeAppContainer();if(!n)throw Error(`App container not found`);let r=e.makeFrameContainer();if(!r)throw Error(`Frame container not found`);let i=e.makeTriggerContainer();if(!i)throw Error(`Trigger container not found`);let a=new Oe().makeIcon();i.appendChild(a),t.appContainer=n,t.frameContainer=r,t.triggerContainer=i,t.iconToggler=a;let o=new Z;o.setupEvents(),o.addIconEvent(),o.emitIconState(),o.checkVisibilityRules(),setInterval(()=>{o.checkVisibilityRules()},6e4),this.addChatwayLoadedEvent()}catch(e){new V().logError(e)}}setupGlobalFunctions(){window.$chatway=window.$chatway||new W}get isChatwayInstalled(){return window.$chatway!==void 0}async destroyApp(){let e=new Z,n=new O;e.cleanupEvents(),e.closeWidget(),n.destroyAppContainer(),new D().removeVisitorDetails(),this.setChatLoadedStatus(!1),t.isWidgetReady=!1,t.pendingMessages=[]}getPreviewText(e,n){if(!t.included||!t.widgetID)return e;let r=t.included.filter(e=>e.type===`widget_langs`&&e.attributes.widget_id===t.widgetID),i=navigator.language;i!==`zh-TW`&&(i=i.split(`-`)[0]);let a=t.included.filter(e=>e.type===`device_preferences`&&e.attributes.widget_id===t.widgetID),o=r.find(e=>e.attributes.locale===i);if(o)return o.attributes[a.length?`widget_text_bubble_${n}`:`widget_text_bubble`];let s=r.find(e=>e.attributes?.is_default);if(s){let t=s.attributes[a.length?`widget_text_bubble_${n}`:`widget_text_bubble`];return t===e?t:e}return e}};new V().init(),new $().start()})()
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.