@meetelise/chat 1.43.33 → 1.43.34

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.
@@ -79,6 +79,7 @@ declare class MyPubnub {
79
79
  leadUserId: string;
80
80
  channel: string;
81
81
  leadSource: string | null;
82
+ private sessionToken;
82
83
  isCurrentlyStreamingMessage: boolean;
83
84
  chatListener: ((res: {
84
85
  messages: SimpleChatMessage[];
@@ -91,6 +92,12 @@ declare class MyPubnub {
91
92
  isFirstChatMessageSent: boolean;
92
93
  private streamingMessageTimeout;
93
94
  constructor(buildingSlug: string, buildingDetails: BuildingWebchatView | null, orgSlug: string, leadSource: string | null | undefined, leadUserId: string, leadSourceMultitouchClient: LeadSourceMultitouchClient | null, leadSourceClient?: LeadSourceClient | null, widgetType?: WidgetType);
95
+ initSession(buildingSlug: string, orgSlug: string): Promise<{
96
+ session_token: string;
97
+ lead_id: string;
98
+ channel: string;
99
+ expires_in_seconds: number;
100
+ } | null>;
94
101
  private checkAndHandleDelayStreamingMessages;
95
102
  checkAndHandleGTMForLeadEmail: (messageEvent: Pubnub.MessageEvent) => void;
96
103
  addChatListener(listener: (response: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meetelise/chat",
3
- "version": "1.43.33",
3
+ "version": "1.43.34",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/MeetElise/chat-ui#readme",
@@ -86,7 +86,7 @@
86
86
  "typescript-plugin-css-modules": "^5.0.0",
87
87
  "webpack": "^5.65.0",
88
88
  "webpack-bundle-analyzer": "^4.10.2",
89
- "webpack-cli": "^4.9.1",
89
+ "webpack-cli": "^5.1.4",
90
90
  "webpack-dev-server": "^5.0.0"
91
91
  }
92
92
  }
@@ -5634,7 +5634,7 @@ xmlns="http://www.w3.org/2000/svg"
5634
5634
  ${kr}
5635
5635
  ${Tr}
5636
5636
  ${_r}
5637
- `,Aa([ue({attribute:!0})],Sa.prototype,"isMinimized",void 0),Aa([ue()],Sa.prototype,"mobileStyles",void 0),Aa([ue({type:Boolean})],Sa.prototype,"isFirstMount",void 0),Aa([ue({attribute:!1})],Sa.prototype,"autoOpenChatWidget",void 0),Aa([ue()],Sa.prototype,"phoneNumber",void 0),Aa([ue({attribute:!0})],Sa.prototype,"buildingName",void 0),Aa([ue({attribute:!0})],Sa.prototype,"chatId",void 0),Aa([ue({attribute:!0})],Sa.prototype,"orgLegalName",void 0),Aa([ue({attribute:!0})],Sa.prototype,"chatCallUsHeader",void 0),Aa([ue({attribute:!1})],Sa.prototype,"buildingId",void 0),Aa([ue({attribute:!0})],Sa.prototype,"buildingSlug",void 0),Aa([ue({attribute:!0})],Sa.prototype,"orgSlug",void 0),Aa([ue({attribute:!0})],Sa.prototype,"sgtUrl",void 0),Aa([ue({attribute:!0})],Sa.prototype,"selfGuidedTourEnabled",void 0),Aa([ue({attribute:!0})],Sa.prototype,"selfGuidedToursTypeOffered",void 0),Aa([ue({attribute:!0})],Sa.prototype,"designConcept",void 0),Aa([ue({attribute:!0})],Sa.prototype,"featureFlagShowDropdown",void 0),Aa([ue({attribute:!1})],Sa.prototype,"leadSources",void 0),Aa([ue({attribute:!0})],Sa.prototype,"currentLeadSource",void 0),Aa([ue({attribute:!0})],Sa.prototype,"escortedToursLink",void 0),Aa([ue({attribute:!0})],Sa.prototype,"escortedToursTypeOffered",void 0),Aa([ue({attribute:!0})],Sa.prototype,"virtualToursLink",void 0),Aa([ue({attribute:!0})],Sa.prototype,"virtualToursTypeOffered",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasChatEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasChatEnabledMobile",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasEmailEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasEmailEnabledMobile",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasApplyNowEnabledDesktop",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasApplyNowEnabledMobile",void 0),Aa([ue({attribute:!0})],Sa.prototype,"applicationLink",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasCallUsEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasCallUsEnabledMobile",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasTextUsEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasTextUsEnabledMobile",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasSSTEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasSSTEnabledMobile",void 0),Aa([ue({attribute:!1})],Sa.prototype,"tourTypeOptions",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasDynamicSchedulingEnabled",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasPricingCalculatorEnabledDesktop",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasPricingCalculatorEnabledMobile",void 0),Aa([ue({attribute:!1})],Sa.prototype,"hasHideMobileFeatures",void 0),Aa([ue({type:Number})],Sa.prototype,"right",void 0),Aa([ue({type:Number})],Sa.prototype,"bottom",void 0),Aa([ue({type:Number})],Sa.prototype,"top",void 0),Aa([ue({type:Number})],Sa.prototype,"left",void 0),Aa([ue({attribute:!0})],Sa.prototype,"showTourNextToChat",void 0),Aa([ue({attribute:!1})],Sa.prototype,"onChatTapped",void 0),Aa([ue({attribute:!0})],Sa.prototype,"onClickMinimize",void 0),Aa([ue({attribute:!0})],Sa.prototype,"onSstClose",void 0),Aa([ue({attribute:!0})],Sa.prototype,"overrideRentgrata",void 0),Aa([ue({attribute:!1})],Sa.prototype,"launcherStyles",void 0),Aa([ue({attribute:!0})],Sa.prototype,"primaryColor",void 0),Aa([ue({attribute:!0})],Sa.prototype,"backgroundColor",void 0),Aa([ue({attribute:!0})],Sa.prototype,"foregroundColorOnPrimaryBackgroundColor",void 0),Aa([ue({attribute:!0})],Sa.prototype,"foregroundColorOnSecondaryBackgroundColor",void 0),Aa([ue({attribute:!0})],Sa.prototype,"leadSourceClient",void 0),Aa([ce()],Sa.prototype,"leadSourceMultitouchClient",void 0),Aa([ce()],Sa.prototype,"_isMobile",void 0),Aa([ce()],Sa.prototype,"isEmailWindowOpen",void 0),Aa([ce()],Sa.prototype,"isCallUsWindowOpen",void 0),Aa([ce()],Sa.prototype,"isSSTWindowOpen",void 0),Aa([ce()],Sa.prototype,"isTextUsWindowOpen",void 0),Aa([ce()],Sa.prototype,"isCalculatorWindowOpen",void 0),Aa([ce()],Sa.prototype,"isMobileFeaturesExpanded",void 0),Sa=Aa([se("meetelise-launcher")],Sa);const Ea=()=>{window.customElements.get("meetelise-launcher")||window.customElements.define("meetelise-launcher",Sa)},ka=["app.meetelise.com","staging.eliseai.com","localhost"],Ta={calculator:{desktop:"calcDesktop",mobile:"calcMobile"},email:{desktop:"emailDesktop",mobile:"emailMobile"},call:{desktop:"callDesktop",mobile:"callMobile"},text:{desktop:"textDesktop",mobile:"textMobile"},sst:{desktop:"sstDesktop",mobile:"sstMobile"}},_a=e=>{const t=window.location.hostname;if(!ka.includes(t))return e;const n=(e=>{if(!e)return{};try{return e.split(",").reduce((e,t)=>{const[n,i]=t.split(":");return n&&i&&n in Ta&&(e[n]="true"===i.toLowerCase()),e},{})}catch(e){return{}}})(new URLSearchParams(window.location.search).get("widgets"));if(0===Object.keys(n).length)return e;const i={...e};return Object.entries(n).forEach(([e,t])=>{const n=Ta[e];n&&(i[n.desktop]=t,i[n.mobile]=t)}),i};var Oa=n(5072),Pa=n.n(Oa),Ia=n(7825),Ma=n.n(Ia),Na=n(7659),Da=n.n(Na),La=n(5056),Ua=n.n(La),Ra=n(540),Ba=n.n(Ra),ja=n(1113),Fa=n.n(ja),Ha=n(5541),$a={};$a.styleTagTransform=Fa(),$a.setAttributes=Ua(),$a.insert=Da().bind(null,"head"),$a.domAPI=Ma(),$a.insertStyleElement=Ba();Pa()(Ha.A,$a);Ha.A&&Ha.A.locals&&Ha.A.locals;async function za(e,t){try{const n=await r().get(`https://app.meetelise.com/platformApi/webchat/${t}/lead-sources`);if(n.data){if("7e352741-1120-4ccf-9929-5dc99193a908"===e){const e=["Zillow","Apartments.com","Google PPC","Google Maps","Apple Maps","Social Media","Print Marketing"];return n.data.filter(t=>e.includes(t))}return Ga(n.data,t)}return[]}catch(e){return[]}}const Ga=(e,t)=>{let n=[];switch(t){case"d41619ec-0f79-11ee-8439-93855926ad58":n=["Forthea - PPC","HotPads","Forthea","Locator","Website-apartmentguide.com","Forthea - organic search","Tdc employee","University newspaper","Nashville apartment locators","Forthea - paid social","Apartment list","Off campus partners","Waze ads","Athletic event","Website-apartment guide"];break;case"d4160560-0f79-11ee-8438-fba837bf3a46":n=["Forthea - PPC","Rentgrata","Website-ApartmentFinder.com","Word of Mouth","Texas A&M A-Frame on Campus","Rent.com","Website-craigslist","Apartment List","Website-apartments.com","Forthea - paid social","Forthea - organic search","Website-apartmentguide.com","Forthea","Uhomes","Phone book","Property - website"];break;default:n=[]}return e.sort(),e.filter(e=>{const t=e.toLowerCase();return!n.map(e=>e.toLowerCase()).includes(t)})};var Qa,qa=n(8805),Wa=n.n(qa),Va=new Uint8Array(16);function Ya(){if(!Qa&&!(Qa="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Qa(Va)}const Ka=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;const Xa=function(e){return"string"==typeof e&&Ka.test(e)};for(var Za=[],Ja=0;Ja<256;++Ja)Za.push((Ja+256).toString(16).substr(1));const es=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(Za[e[t+0]]+Za[e[t+1]]+Za[e[t+2]]+Za[e[t+3]]+"-"+Za[e[t+4]]+Za[e[t+5]]+"-"+Za[e[t+6]]+Za[e[t+7]]+"-"+Za[e[t+8]]+Za[e[t+9]]+"-"+Za[e[t+10]]+Za[e[t+11]]+Za[e[t+12]]+Za[e[t+13]]+Za[e[t+14]]+Za[e[t+15]]).toLowerCase();if(!Xa(n))throw TypeError("Stringified UUID is invalid");return n};const ts=function(e,t,n){var i=(e=e||{}).random||(e.rng||Ya)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){n=n||0;for(var r=0;r<16;++r)t[n+r]=i[r];return t}return es(i)},ns=e=>localStorage.removeItem("com.elise.webchat.slug="+e),is=(e,t,n)=>{const i=On(new Date),r=n||`lead_${ts()}`;return localStorage.setItem("com.elise.webchat.slug="+e,JSON.stringify({buildingSlug:e,leadId:r,timestamp:i,initiatedChat:t})),{leadId:r,timestamp:Rn(i),buildingSlug:e,initiatedChat:t}},rs=e=>{const t=localStorage.getItem("com.elise.webchat.slug="+e);if(t)try{const n=JSON.parse(t),i={leadId:n.leadId,timestamp:new Date(n.timestamp),buildingSlug:n.buildingSlug,initiatedChat:n.initiatedChat};if(os(e,i))return i}catch(e){}return{leadId:null,timestamp:null,buildingSlug:null,initiatedChat:!1}},os=(e,t)=>{try{if(t.timestamp&&t.initiatedChat){const e=new Date("2024-06-06T21:30:00Z");if(dn(t.timestamp,e))return!1}}catch(e){}return!(t.buildingSlug!==e||!t.leadId||!t.timestamp)&&!wn(t.timestamp,24)};var as;!function(e){e.noReply="no-reply",e.text="text",e.media="media"}(as||(as={}));const ss=e=>e.type===us.text,ls=e=>e.type===us.media;var us;!function(e){e.text="text",e.media="media"}(us||(us={}));const cs=class{constructor(e,t,n,i=null,r,o,a=null,s=au.Default){this.apiHost="https://app.meetelise.com",this.leadSourceClient=null,this.leadSourceMultitouchClient=null,this.buildingWebchatView=null,this.eliseResponseTimeout=null,this.isWaitingForStreamingMessages=!1,this.widgetType=au.Default,this.pubnub=null,this.leadUserId="",this.channel="",this.leadSource=null,this.isCurrentlyStreamingMessage=!1,this.chatListener=null,this.rawPubnubMessages=[],this.simpleChatMessages=[],this.listenerParams={message:e=>{var t,n;const i={channel:e.channel,message:e.message,publisher:e.publisher,subscription:e.subscription,timetoken:+e.timetoken};this.rawPubnubMessages=[...this.rawPubnubMessages,i],this.markEveryPreviousNoReplyMessageDone(this.rawPubnubMessages),this.rawPubnubMessages=this.rawPubnubMessages.filter(e=>e.message.messageType!==as.noReply),this.simpleChatMessages=this.translatePubnubMessagesIntoSimpleChatMessages(this.rawPubnubMessages),this.checkAndHandleDelayStreamingMessages();const r="eliseai"!==e.publisher&&"elise_health_ai"!==e.publisher;if(null===(t=this.chatListener)||void 0===t||t.call(this,{messages:this.simpleChatMessages,isLoading:r}),!r&&this.eliseResponseTimeout&&clearTimeout(this.eliseResponseTimeout),this.isLoadingMessages=r,"ai_message"===e.message.customType){this.simpleChatMessages.some(e=>e.type===us.text&&e.message.includes("confirmed for your"))&&ai("scheduledTourEvent",{tourDetails:e.message,buildingId:null===(n=this.buildingWebchatView)||void 0===n?void 0:n.id,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,leadUserId:this.leadUserId,channel:this.channel})}this.checkAndHandleGTMForLeadEmail(e)}},this.isLoadingMessages=!1,this.isFirstChatMessageSent=!1,this.streamingMessageTimeout=null,this.checkAndHandleDelayStreamingMessages=({delayToFetchHistoryInMs:e=1e4}={})=>{this.streamingMessageTimeout&&(clearTimeout(this.streamingMessageTimeout),this.streamingMessageTimeout=null);const t=this.simpleChatMessages.some(e=>{if(!ss(e))return!1;const t=e.chunks.find(e=>e.isDone);return!t||e.chunks.length===t.order});t&&(this.streamingMessageTimeout=setTimeout(()=>{Ai({logTitle:"PUBNUB_WARN_DELAYED_STREAMING_MESSAGES",logData:{channel:this.channel},logType:xi.warn,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug}),this.getChannelHistory()},e))},this.checkAndHandleGTMForLeadEmail=e=>{var t;try{if("lead_message"!==e.message.customType)return;if(!(e=>{try{return/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b/.test(e)}catch(e){return!1}})(e.message.text))return;ai("leadProvidedEmail",{buildingId:null===(t=this.buildingWebchatView)||void 0===t?void 0:t.id,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,leadUserId:this.leadUserId,channel:this.channel})}catch(e){return}},this.markEveryPreviousNoReplyMessageDone=e=>{var t,n;for(let i=e.length-1;i>=0;i--){const r=null===(t=e[i])||void 0===t?void 0:t.message,o=i>0&&(null===(n=e[i-1])||void 0===n?void 0:n.message);(null==r?void 0:r.messageType)===as.noReply&&o&&(o.is_done=!0)}},this.checkMessageChunkValid=e=>{try{return!!e.message&&!!e.message.text&&e.message.text.length>0&&!!e.message.customType}catch(e){return!1}},this.handleChatListeners=()=>{if(this.pubnub&&this.channel)try{this.pubnub.subscribe({channels:[this.channel]}),this.pubnub.addListener(this.listenerParams)}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_ADDING_LISTENER",logData:{error:e,channel:this.channel,leadUserId:this.leadUserId,website:location.href},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}},this.handleDisconnect=()=>{this.eliseResponseTimeout&&(clearTimeout(this.eliseResponseTimeout),this.eliseResponseTimeout=null),this.streamingMessageTimeout&&(clearTimeout(this.streamingMessageTimeout),this.streamingMessageTimeout=null),this.removeChatListeners()},this.removeChatListeners=()=>{this.pubnub&&this.channel&&(this.pubnub.unsubscribe({channels:[this.channel]}),this.pubnub.removeListener(this.listenerParams))},this.sendMessage=async e=>{if(e){if(!this.pubnub){const e=is(this.buildingSlug,!0,this.leadUserId);if(!await this.initializePubnub(e))return}await this.withAuthToken(async()=>{var t,n,i,r,o,a,s,l,u;this.pubnub&&this.channel&&(this.eliseResponseTimeout&&(clearTimeout(this.eliseResponseTimeout),this.eliseResponseTimeout=null),this.eliseResponseTimeout=setTimeout(()=>{this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_ELISEAI_MESSAGE_TIMEOUT",logData:{channel:this.channel,leadUserId:this.leadUserId,message:e},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})},9e4),0===this.simpleChatMessages.length&&(null===(t=this.leadSourceClient)||void 0===t||t.checkAndHandleForLogLeadSource({webchatAction:"chat",stateId:null})),this.widgetType===au.Utilities?await this.pubnub.publish({channel:this.channel,message:{text:e,customType:"lead_message",widgetType:this.widgetType,isDevState:this.shouldCreateAsDevState(),orgSlug:this.orgSlug}}):(await this.pubnub.publish({channel:this.channel,message:{text:e,customType:"lead_message",buildingId:null===(n=this.buildingWebchatView)||void 0===n?void 0:n.id,buildingSlug:this.buildingSlug,userId:null===(i=this.buildingWebchatView)||void 0===i?void 0:i.userId,leadSource:this.leadSource,widgetType:this.widgetType,isDevState:this.shouldCreateAsDevState(),lead_sources_with_timestamps:(null!==(o=null===(r=this.leadSourceMultitouchClient)||void 0===r?void 0:r.getSafeLeadSourceTouchpointsWithDefault({includedUserSelectedLeadSource:null}))&&void 0!==o?o:[]).map(e=>gn({...e}))}}),null===(a=this.leadSourceClient)||void 0===a||a.resetLeadSource(),null===(s=this.leadSourceMultitouchClient)||void 0===s||s.resetLeadSourceTouchpoints()),this.isFirstChatMessageSent||(ai("firstChatMessageSent",{message:e,buildingId:null===(l=this.buildingWebchatView)||void 0===l?void 0:l.id,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,leadUserId:this.leadUserId,channel:this.channel}),this.isFirstChatMessageSent=!0),ai("chatMessageSent",{message:e,buildingId:null===(u=this.buildingWebchatView)||void 0===u?void 0:u.id,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,leadUserId:this.leadUserId,channel:this.channel}))}),!1===this.isLoadingMessages&&(this.isLoadingMessages=!0)}},this.isLeadMessage=e=>e.publisher.includes("lead_")&&"lead_message"===e.message.customType,this.removeDuplicatedRawPubnubMessages=e=>{const t=new Set;return e.filter(e=>{if("lead_message"===e.message.customType||!e.message.stream_id||!e.message.order)return!0;const n=`${e.message.stream_id}-${e.message.order}-${e.message.messageType}`;return t.has(n)?(Ai({logTitle:"PUBNUB_WARN_DUPLICATE_MESSAGE",logData:{message:e,channel:this.channel},logType:xi.warn,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug}),!1):(t.add(n),!0)})},this.translatePubnubMessagesIntoSimpleChatMessages=e=>{const t=[],n={};return this.removeDuplicatedRawPubnubMessages(e).forEach(e=>{var i;"media"===e.message.messageType?t.push({timestamp:e.timetoken,media:null!==(i=e.message.media)&&void 0!==i?i:[],isLeadMessage:this.isLeadMessage(e),type:us.media}):!e.message.stream_id||e.message.is_done&&0===e.message.order?t.push({timestamp:e.timetoken,message:e.message.text,isLeadMessage:this.isLeadMessage(e),chunks:[{text:e.message.text,order:0,isDone:!0}],type:us.text}):n[e.message.stream_id]?n[e.message.stream_id].push(e):n[e.message.stream_id]=[e]}),Object.keys(n).forEach(e=>{const i=n[e],r=this.getConsecutiveChunks(i.sort((e,t)=>{var n,i;return(null!==(n=e.message.order)&&void 0!==n?n:0)-(null!==(i=t.message.order)&&void 0!==i?i:0)})),o=r.map(e=>e.message.text).join(""),a=r[0],s={timestamp:a.timetoken,message:o,isLeadMessage:this.isLeadMessage(a),chunks:r.map(e=>{var t,n;return{text:e.message.text,order:null!==(t=e.message.order)&&void 0!==t?t:0,isDone:null!==(n=e.message.is_done)&&void 0!==n&&n}}),type:us.text};this.isCurrentlyStreamingMessage=this.isMessageStillStreamingChunks(r),t.push(s)}),t.sort((e,t)=>e.timestamp-t.timestamp),t},this.getConsecutiveChunks=e=>{var t,n;const i=e.sort((e,t)=>{var n,i;return(null!==(n=e.message.order)&&void 0!==n?n:0)-(null!==(i=t.message.order)&&void 0!==i?i:0)}),r=[];let o=null!==(t=i[0].message.order)&&void 0!==t?t:0;for(const e of i){if((null!==(n=e.message.order)&&void 0!==n?n:-1)!==o)break;r.push(e),o++}return r},this.isMessageStillStreamingChunks=e=>{const t=e.find(e=>e.message.is_done);return!t||e.length===t.message.order},this.buildingSlug=e,this.buildingWebchatView=t,this.orgSlug=n,this.leadSource=i,this.leadUserId=r,this.channel=`webchat_${r}`,this.leadSourceClient=a,this.leadSourceMultitouchClient=o,this.widgetType=s}addChatListener(e){this.chatListener=e}async initializePubnub(e){if(!e.leadId)return;this.leadUserId=e.leadId;const t=await this.fetchToken(this.leadUserId,this.channel);return t?(this.pubnub=new(Wa())({publishKey:t.keys.publish_key,subscribeKey:t.keys.subscribe_key,userId:this.leadUserId,authKey:t.auth.result.token,origin:"meetelise.pubnubapi.com"}),this.withAuthToken(()=>new Promise(()=>this.handleChatListeners())),await this.withAuthToken(()=>this.getChannelHistory()),this.pubnub):void 0}async fetchToken(e,t){try{return(await r().get(`${this.apiHost}/platformApi/webchat/pn/request-token?user_id=${e}&channel=${t}&${"healthcare"===this.widgetType?"industry=health_care":""}`)).data}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_FETCHING_TOKEN",logData:{error:e},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}return null}async fetchChannelExists(e){try{return(await r().get(`${this.apiHost}/platformApi/webchat/check-channel-exists?channel_name=${e}`)).data}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_FETCHING_CHANNEL_EXISTS",logData:{error:e},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}return!1}async withAuthToken(e){try{await e()}catch(t){if(t instanceof i.AxiosError&&t&&t.response&&403===t.response.status)try{if(!this.pubnub||!this.leadUserId||!this.channel)return;const t=await this.fetchToken(this.leadUserId,this.channel);if(!t)return;this.pubnub.setAuthKey(t.auth.result.token),await e()}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_REFETCHING_TOKEN",logData:{retryError:e},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}}}async getChannelHistory(e=1500){var t;try{let n=[],i=null;const r=100;for(let t=0;t<e;t+=r){const o=await new Promise((n,o)=>{if(!this.pubnub||!this.channel)return[];const a=Math.min(r,e-t);this.pubnub.fetchMessages({channels:[this.channel],count:a,start:null!=i?i:void 0},(e,t)=>{e.error?o(e):n(t)})}),a=o.channels[this.channel];if(!a)break;if(a.sort((e,t)=>+e.timetoken-+t.timetoken),!a||0===a.length)break;if(this.channel&&0!==Object.keys(o.channels).length){const e=o.channels[this.channel],t=[];e.forEach(e=>{e.uuid&&t.push({channel:e.channel,message:e.message,publisher:e.uuid,subscription:e.channel,timetoken:+e.timetoken})}),this.markEveryPreviousNoReplyMessageDone(t),n=n.concat(t.filter(e=>e.message.messageType!==as.noReply))}if(i=a[0].timetoken,n.length>=e||a.length<r)break}this.rawPubnubMessages=n.slice(0,e),this.simpleChatMessages=this.translatePubnubMessagesIntoSimpleChatMessages(this.rawPubnubMessages),null===(t=this.chatListener)||void 0===t||t.call(this,{messages:this.simpleChatMessages,isLoading:!1})}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_WARN_FETCHING_HISTORY",logData:{error:e},logType:xi.warn,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}}shouldCreateAsDevState(){return location.href.startsWith("https://app.meetelise.com/settings/widgets")||location.href.includes("demo/utilities")}},ds=(e,t,n)=>{const i=e.replace(/\D/g,"").replace(/^1(\d{10})$/,"$1"),r=`tel:${i}`,o=`sms:${i}`,a=`whatsapp://send?phone=${i}`,s=`facetime:${i}`,l=`facetime-audio:${i}`,u=/(?:\+1\s)?(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}/g,c=/(tel|sms):(?:\+1\s)?(?:(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}|\d{10,11})/g,d=/whatsapp:\/\/send\?phone=\d+/g,h=/(facetime|facetime-audio):\d+/g,p=document.body.getElementsByTagName("*");let f=!1;const g=i.replace(/(\d{3})(\d{3})(\d{4})/,"($1) $2-$3");let m=!1,y=!1,b=0;for(let e=0;e<p.length;e++)if(p[e].nodeType===Node.ELEMENT_NODE){if(1===p[e].childNodes.length&&p[e].childNodes[0].nodeType==Node.TEXT_NODE){const t=p[e].textContent;if(!t)continue;const n=t.replace(u,e=>e.startsWith("+1 ")?`+1 ${g}`:g);t!==n&&(b++,p[e].textContent=n),f=!0,m||(m=!0)}if(p[e].hasAttribute("href")){const t=p[e].getAttribute("href");if(!t)continue;let n="",i=c;t.startsWith("sms:")?n=o:t.startsWith("whatsapp:")?(n=a,i=d):t.startsWith("facetime:")?(n=s,i=h):t.startsWith("facetime-audio:")?(n=l,i=h):n=r;const u=t.replace(i,n);if(p[e].setAttribute("href",u),(t.startsWith("tel:")||t.startsWith("sms:"))&&u===t&&u!==n){t.replace(/\D/g,"").length>=7&&p[e].setAttribute("href",t.startsWith("tel:")?r:o)}y||(y=!0)}}return m&&Ai({logTitle:"DNI_WEBSITE_INSERTION",logData:{type:"text-insertion",newPhoneNumber:g,website:window.location.href},logType:xi.info,buildingSlug:n,orgSlug:t}),y&&Ai({logTitle:"DNI_WEBSITE_INSERTION",logData:{type:"href-insertion",newPhoneNumber:g,website:window.location.href},logType:xi.info,buildingSlug:n,orgSlug:t}),f||Ai({logTitle:"DNI_WEBSITE_INSERTION",logData:{type:"no-phone-number-found",website:window.location.href},logType:xi.warn,buildingSlug:n,orgSlug:t}),b};var hs=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a};let ps=class extends oe{constructor(){super(...arguments),this.onClick=()=>{},this.primaryColor=Ue,this.toExpand=!1}render(){return B`
5637
+ `,Aa([ue({attribute:!0})],Sa.prototype,"isMinimized",void 0),Aa([ue()],Sa.prototype,"mobileStyles",void 0),Aa([ue({type:Boolean})],Sa.prototype,"isFirstMount",void 0),Aa([ue({attribute:!1})],Sa.prototype,"autoOpenChatWidget",void 0),Aa([ue()],Sa.prototype,"phoneNumber",void 0),Aa([ue({attribute:!0})],Sa.prototype,"buildingName",void 0),Aa([ue({attribute:!0})],Sa.prototype,"chatId",void 0),Aa([ue({attribute:!0})],Sa.prototype,"orgLegalName",void 0),Aa([ue({attribute:!0})],Sa.prototype,"chatCallUsHeader",void 0),Aa([ue({attribute:!1})],Sa.prototype,"buildingId",void 0),Aa([ue({attribute:!0})],Sa.prototype,"buildingSlug",void 0),Aa([ue({attribute:!0})],Sa.prototype,"orgSlug",void 0),Aa([ue({attribute:!0})],Sa.prototype,"sgtUrl",void 0),Aa([ue({attribute:!0})],Sa.prototype,"selfGuidedTourEnabled",void 0),Aa([ue({attribute:!0})],Sa.prototype,"selfGuidedToursTypeOffered",void 0),Aa([ue({attribute:!0})],Sa.prototype,"designConcept",void 0),Aa([ue({attribute:!0})],Sa.prototype,"featureFlagShowDropdown",void 0),Aa([ue({attribute:!1})],Sa.prototype,"leadSources",void 0),Aa([ue({attribute:!0})],Sa.prototype,"currentLeadSource",void 0),Aa([ue({attribute:!0})],Sa.prototype,"escortedToursLink",void 0),Aa([ue({attribute:!0})],Sa.prototype,"escortedToursTypeOffered",void 0),Aa([ue({attribute:!0})],Sa.prototype,"virtualToursLink",void 0),Aa([ue({attribute:!0})],Sa.prototype,"virtualToursTypeOffered",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasChatEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasChatEnabledMobile",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasEmailEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasEmailEnabledMobile",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasApplyNowEnabledDesktop",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasApplyNowEnabledMobile",void 0),Aa([ue({attribute:!0})],Sa.prototype,"applicationLink",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasCallUsEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasCallUsEnabledMobile",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasTextUsEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasTextUsEnabledMobile",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasSSTEnabledDesktop",void 0),Aa([ue({type:Boolean})],Sa.prototype,"hasSSTEnabledMobile",void 0),Aa([ue({attribute:!1})],Sa.prototype,"tourTypeOptions",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasDynamicSchedulingEnabled",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasPricingCalculatorEnabledDesktop",void 0),Aa([ue({attribute:!0})],Sa.prototype,"hasPricingCalculatorEnabledMobile",void 0),Aa([ue({attribute:!1})],Sa.prototype,"hasHideMobileFeatures",void 0),Aa([ue({type:Number})],Sa.prototype,"right",void 0),Aa([ue({type:Number})],Sa.prototype,"bottom",void 0),Aa([ue({type:Number})],Sa.prototype,"top",void 0),Aa([ue({type:Number})],Sa.prototype,"left",void 0),Aa([ue({attribute:!0})],Sa.prototype,"showTourNextToChat",void 0),Aa([ue({attribute:!1})],Sa.prototype,"onChatTapped",void 0),Aa([ue({attribute:!0})],Sa.prototype,"onClickMinimize",void 0),Aa([ue({attribute:!0})],Sa.prototype,"onSstClose",void 0),Aa([ue({attribute:!0})],Sa.prototype,"overrideRentgrata",void 0),Aa([ue({attribute:!1})],Sa.prototype,"launcherStyles",void 0),Aa([ue({attribute:!0})],Sa.prototype,"primaryColor",void 0),Aa([ue({attribute:!0})],Sa.prototype,"backgroundColor",void 0),Aa([ue({attribute:!0})],Sa.prototype,"foregroundColorOnPrimaryBackgroundColor",void 0),Aa([ue({attribute:!0})],Sa.prototype,"foregroundColorOnSecondaryBackgroundColor",void 0),Aa([ue({attribute:!0})],Sa.prototype,"leadSourceClient",void 0),Aa([ce()],Sa.prototype,"leadSourceMultitouchClient",void 0),Aa([ce()],Sa.prototype,"_isMobile",void 0),Aa([ce()],Sa.prototype,"isEmailWindowOpen",void 0),Aa([ce()],Sa.prototype,"isCallUsWindowOpen",void 0),Aa([ce()],Sa.prototype,"isSSTWindowOpen",void 0),Aa([ce()],Sa.prototype,"isTextUsWindowOpen",void 0),Aa([ce()],Sa.prototype,"isCalculatorWindowOpen",void 0),Aa([ce()],Sa.prototype,"isMobileFeaturesExpanded",void 0),Sa=Aa([se("meetelise-launcher")],Sa);const Ea=()=>{window.customElements.get("meetelise-launcher")||window.customElements.define("meetelise-launcher",Sa)},ka=["app.meetelise.com","staging.eliseai.com","localhost"],Ta={calculator:{desktop:"calcDesktop",mobile:"calcMobile"},email:{desktop:"emailDesktop",mobile:"emailMobile"},call:{desktop:"callDesktop",mobile:"callMobile"},text:{desktop:"textDesktop",mobile:"textMobile"},sst:{desktop:"sstDesktop",mobile:"sstMobile"}},_a=e=>{const t=window.location.hostname;if(!ka.includes(t))return e;const n=(e=>{if(!e)return{};try{return e.split(",").reduce((e,t)=>{const[n,i]=t.split(":");return n&&i&&n in Ta&&(e[n]="true"===i.toLowerCase()),e},{})}catch(e){return{}}})(new URLSearchParams(window.location.search).get("widgets"));if(0===Object.keys(n).length)return e;const i={...e};return Object.entries(n).forEach(([e,t])=>{const n=Ta[e];n&&(i[n.desktop]=t,i[n.mobile]=t)}),i};var Oa=n(5072),Pa=n.n(Oa),Ia=n(7825),Ma=n.n(Ia),Na=n(7659),Da=n.n(Na),La=n(5056),Ua=n.n(La),Ra=n(540),Ba=n.n(Ra),ja=n(1113),Fa=n.n(ja),Ha=n(5541),$a={};$a.styleTagTransform=Fa(),$a.setAttributes=Ua(),$a.insert=Da().bind(null,"head"),$a.domAPI=Ma(),$a.insertStyleElement=Ba();Pa()(Ha.A,$a);Ha.A&&Ha.A.locals&&Ha.A.locals;async function za(e,t){try{const n=await r().get(`https://app.meetelise.com/platformApi/webchat/${t}/lead-sources`);if(n.data){if("7e352741-1120-4ccf-9929-5dc99193a908"===e){const e=["Zillow","Apartments.com","Google PPC","Google Maps","Apple Maps","Social Media","Print Marketing"];return n.data.filter(t=>e.includes(t))}return Ga(n.data,t)}return[]}catch(e){return[]}}const Ga=(e,t)=>{let n=[];switch(t){case"d41619ec-0f79-11ee-8439-93855926ad58":n=["Forthea - PPC","HotPads","Forthea","Locator","Website-apartmentguide.com","Forthea - organic search","Tdc employee","University newspaper","Nashville apartment locators","Forthea - paid social","Apartment list","Off campus partners","Waze ads","Athletic event","Website-apartment guide"];break;case"d4160560-0f79-11ee-8438-fba837bf3a46":n=["Forthea - PPC","Rentgrata","Website-ApartmentFinder.com","Word of Mouth","Texas A&M A-Frame on Campus","Rent.com","Website-craigslist","Apartment List","Website-apartments.com","Forthea - paid social","Forthea - organic search","Website-apartmentguide.com","Forthea","Uhomes","Phone book","Property - website"];break;default:n=[]}return e.sort(),e.filter(e=>{const t=e.toLowerCase();return!n.map(e=>e.toLowerCase()).includes(t)})};var Qa,qa=n(8805),Wa=n.n(qa),Va=new Uint8Array(16);function Ya(){if(!Qa&&!(Qa="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Qa(Va)}const Ka=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;const Xa=function(e){return"string"==typeof e&&Ka.test(e)};for(var Za=[],Ja=0;Ja<256;++Ja)Za.push((Ja+256).toString(16).substr(1));const es=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(Za[e[t+0]]+Za[e[t+1]]+Za[e[t+2]]+Za[e[t+3]]+"-"+Za[e[t+4]]+Za[e[t+5]]+"-"+Za[e[t+6]]+Za[e[t+7]]+"-"+Za[e[t+8]]+Za[e[t+9]]+"-"+Za[e[t+10]]+Za[e[t+11]]+Za[e[t+12]]+Za[e[t+13]]+Za[e[t+14]]+Za[e[t+15]]).toLowerCase();if(!Xa(n))throw TypeError("Stringified UUID is invalid");return n};const ts=function(e,t,n){var i=(e=e||{}).random||(e.rng||Ya)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){n=n||0;for(var r=0;r<16;++r)t[n+r]=i[r];return t}return es(i)},ns=e=>localStorage.removeItem("com.elise.webchat.slug="+e),is=(e,t,n)=>{const i=On(new Date),r=n||`lead_${ts()}`;return localStorage.setItem("com.elise.webchat.slug="+e,JSON.stringify({buildingSlug:e,leadId:r,timestamp:i,initiatedChat:t})),{leadId:r,timestamp:Rn(i),buildingSlug:e,initiatedChat:t}},rs=e=>{const t=localStorage.getItem("com.elise.webchat.slug="+e);if(t)try{const n=JSON.parse(t),i={leadId:n.leadId,timestamp:new Date(n.timestamp),buildingSlug:n.buildingSlug,initiatedChat:n.initiatedChat};if(os(e,i))return i}catch(e){}return{leadId:null,timestamp:null,buildingSlug:null,initiatedChat:!1}},os=(e,t)=>{try{if(t.timestamp&&t.initiatedChat){const e=new Date("2024-06-06T21:30:00Z");if(dn(t.timestamp,e))return!1}}catch(e){}return!(t.buildingSlug!==e||!t.leadId||!t.timestamp)&&!wn(t.timestamp,24)};var as;!function(e){e.noReply="no-reply",e.text="text",e.media="media"}(as||(as={}));const ss=e=>e.type===us.text,ls=e=>e.type===us.media;var us;!function(e){e.text="text",e.media="media"}(us||(us={}));const cs=class{constructor(e,t,n,i=null,r,o,a=null,s=au.Default){this.apiHost="https://app.meetelise.com",this.leadSourceClient=null,this.leadSourceMultitouchClient=null,this.buildingWebchatView=null,this.eliseResponseTimeout=null,this.isWaitingForStreamingMessages=!1,this.widgetType=au.Default,this.pubnub=null,this.leadUserId="",this.channel="",this.leadSource=null,this.sessionToken=null,this.isCurrentlyStreamingMessage=!1,this.chatListener=null,this.rawPubnubMessages=[],this.simpleChatMessages=[],this.listenerParams={message:e=>{var t,n;const i={channel:e.channel,message:e.message,publisher:e.publisher,subscription:e.subscription,timetoken:+e.timetoken};this.rawPubnubMessages=[...this.rawPubnubMessages,i],this.markEveryPreviousNoReplyMessageDone(this.rawPubnubMessages),this.rawPubnubMessages=this.rawPubnubMessages.filter(e=>e.message.messageType!==as.noReply),this.simpleChatMessages=this.translatePubnubMessagesIntoSimpleChatMessages(this.rawPubnubMessages),this.checkAndHandleDelayStreamingMessages();const r="eliseai"!==e.publisher&&"elise_health_ai"!==e.publisher;if(null===(t=this.chatListener)||void 0===t||t.call(this,{messages:this.simpleChatMessages,isLoading:r}),!r&&this.eliseResponseTimeout&&clearTimeout(this.eliseResponseTimeout),this.isLoadingMessages=r,"ai_message"===e.message.customType){this.simpleChatMessages.some(e=>e.type===us.text&&e.message.includes("confirmed for your"))&&ai("scheduledTourEvent",{tourDetails:e.message,buildingId:null===(n=this.buildingWebchatView)||void 0===n?void 0:n.id,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,leadUserId:this.leadUserId,channel:this.channel})}this.checkAndHandleGTMForLeadEmail(e)}},this.isLoadingMessages=!1,this.isFirstChatMessageSent=!1,this.streamingMessageTimeout=null,this.checkAndHandleDelayStreamingMessages=({delayToFetchHistoryInMs:e=1e4}={})=>{this.streamingMessageTimeout&&(clearTimeout(this.streamingMessageTimeout),this.streamingMessageTimeout=null);const t=this.simpleChatMessages.some(e=>{if(!ss(e))return!1;const t=e.chunks.find(e=>e.isDone);return!t||e.chunks.length===t.order});t&&(this.streamingMessageTimeout=setTimeout(()=>{Ai({logTitle:"PUBNUB_WARN_DELAYED_STREAMING_MESSAGES",logData:{channel:this.channel},logType:xi.warn,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug}),this.getChannelHistory()},e))},this.checkAndHandleGTMForLeadEmail=e=>{var t;try{if("lead_message"!==e.message.customType)return;if(!(e=>{try{return/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b/.test(e)}catch(e){return!1}})(e.message.text))return;ai("leadProvidedEmail",{buildingId:null===(t=this.buildingWebchatView)||void 0===t?void 0:t.id,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,leadUserId:this.leadUserId,channel:this.channel})}catch(e){return}},this.markEveryPreviousNoReplyMessageDone=e=>{var t,n;for(let i=e.length-1;i>=0;i--){const r=null===(t=e[i])||void 0===t?void 0:t.message,o=i>0&&(null===(n=e[i-1])||void 0===n?void 0:n.message);(null==r?void 0:r.messageType)===as.noReply&&o&&(o.is_done=!0)}},this.checkMessageChunkValid=e=>{try{return!!e.message&&!!e.message.text&&e.message.text.length>0&&!!e.message.customType}catch(e){return!1}},this.handleChatListeners=()=>{if(this.pubnub&&this.channel)try{this.pubnub.subscribe({channels:[this.channel]}),this.pubnub.addListener(this.listenerParams)}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_ADDING_LISTENER",logData:{error:e,channel:this.channel,leadUserId:this.leadUserId,website:location.href},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}},this.handleDisconnect=()=>{this.eliseResponseTimeout&&(clearTimeout(this.eliseResponseTimeout),this.eliseResponseTimeout=null),this.streamingMessageTimeout&&(clearTimeout(this.streamingMessageTimeout),this.streamingMessageTimeout=null),this.removeChatListeners()},this.removeChatListeners=()=>{this.pubnub&&this.channel&&(this.pubnub.unsubscribe({channels:[this.channel]}),this.pubnub.removeListener(this.listenerParams))},this.sendMessage=async e=>{if(e){if(!this.pubnub){const e=is(this.buildingSlug,!0,this.leadUserId);if(!await this.initializePubnub(e))return}await this.withAuthToken(async()=>{var t,n,i,r,o,a,s,l,u;this.pubnub&&this.channel&&(this.eliseResponseTimeout&&(clearTimeout(this.eliseResponseTimeout),this.eliseResponseTimeout=null),this.eliseResponseTimeout=setTimeout(()=>{this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_ELISEAI_MESSAGE_TIMEOUT",logData:{channel:this.channel,leadUserId:this.leadUserId,message:e},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})},9e4),0===this.simpleChatMessages.length&&(null===(t=this.leadSourceClient)||void 0===t||t.checkAndHandleForLogLeadSource({webchatAction:"chat",stateId:null})),this.widgetType===au.Utilities?await this.pubnub.publish({channel:this.channel,message:{text:e,customType:"lead_message",widgetType:this.widgetType,isDevState:this.shouldCreateAsDevState(),orgSlug:this.orgSlug}}):(await this.pubnub.publish({channel:this.channel,message:{text:e,customType:"lead_message",buildingId:null===(n=this.buildingWebchatView)||void 0===n?void 0:n.id,buildingSlug:this.buildingSlug,userId:null===(i=this.buildingWebchatView)||void 0===i?void 0:i.userId,leadSource:this.leadSource,widgetType:this.widgetType,isDevState:this.shouldCreateAsDevState(),lead_sources_with_timestamps:(null!==(o=null===(r=this.leadSourceMultitouchClient)||void 0===r?void 0:r.getSafeLeadSourceTouchpointsWithDefault({includedUserSelectedLeadSource:null}))&&void 0!==o?o:[]).map(e=>gn({...e}))}}),null===(a=this.leadSourceClient)||void 0===a||a.resetLeadSource(),null===(s=this.leadSourceMultitouchClient)||void 0===s||s.resetLeadSourceTouchpoints()),this.isFirstChatMessageSent||(ai("firstChatMessageSent",{message:e,buildingId:null===(l=this.buildingWebchatView)||void 0===l?void 0:l.id,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,leadUserId:this.leadUserId,channel:this.channel}),this.isFirstChatMessageSent=!0),ai("chatMessageSent",{message:e,buildingId:null===(u=this.buildingWebchatView)||void 0===u?void 0:u.id,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,leadUserId:this.leadUserId,channel:this.channel}))}),!1===this.isLoadingMessages&&(this.isLoadingMessages=!0)}},this.isLeadMessage=e=>e.publisher.includes("lead_")&&"lead_message"===e.message.customType,this.removeDuplicatedRawPubnubMessages=e=>{const t=new Set;return e.filter(e=>{if("lead_message"===e.message.customType||!e.message.stream_id||!e.message.order)return!0;const n=`${e.message.stream_id}-${e.message.order}-${e.message.messageType}`;return t.has(n)?(Ai({logTitle:"PUBNUB_WARN_DUPLICATE_MESSAGE",logData:{message:e,channel:this.channel},logType:xi.warn,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug}),!1):(t.add(n),!0)})},this.translatePubnubMessagesIntoSimpleChatMessages=e=>{const t=[],n={};return this.removeDuplicatedRawPubnubMessages(e).forEach(e=>{var i;"media"===e.message.messageType?t.push({timestamp:e.timetoken,media:null!==(i=e.message.media)&&void 0!==i?i:[],isLeadMessage:this.isLeadMessage(e),type:us.media}):!e.message.stream_id||e.message.is_done&&0===e.message.order?t.push({timestamp:e.timetoken,message:e.message.text,isLeadMessage:this.isLeadMessage(e),chunks:[{text:e.message.text,order:0,isDone:!0}],type:us.text}):n[e.message.stream_id]?n[e.message.stream_id].push(e):n[e.message.stream_id]=[e]}),Object.keys(n).forEach(e=>{const i=n[e],r=this.getConsecutiveChunks(i.sort((e,t)=>{var n,i;return(null!==(n=e.message.order)&&void 0!==n?n:0)-(null!==(i=t.message.order)&&void 0!==i?i:0)})),o=r.map(e=>e.message.text).join(""),a=r[0],s={timestamp:a.timetoken,message:o,isLeadMessage:this.isLeadMessage(a),chunks:r.map(e=>{var t,n;return{text:e.message.text,order:null!==(t=e.message.order)&&void 0!==t?t:0,isDone:null!==(n=e.message.is_done)&&void 0!==n&&n}}),type:us.text};this.isCurrentlyStreamingMessage=this.isMessageStillStreamingChunks(r),t.push(s)}),t.sort((e,t)=>e.timestamp-t.timestamp),t},this.getConsecutiveChunks=e=>{var t,n;const i=e.sort((e,t)=>{var n,i;return(null!==(n=e.message.order)&&void 0!==n?n:0)-(null!==(i=t.message.order)&&void 0!==i?i:0)}),r=[];let o=null!==(t=i[0].message.order)&&void 0!==t?t:0;for(const e of i){if((null!==(n=e.message.order)&&void 0!==n?n:-1)!==o)break;r.push(e),o++}return r},this.isMessageStillStreamingChunks=e=>{const t=e.find(e=>e.message.is_done);return!t||e.length===t.message.order},this.buildingSlug=e,this.buildingWebchatView=t,this.orgSlug=n,this.leadSource=i,this.leadUserId=r,this.channel=`webchat_${r}`,this.leadSourceClient=a,this.leadSourceMultitouchClient=o,this.widgetType=s}async initSession(e,t){try{const n=await r().post(`${this.apiHost}/platformApi/webchat/init`,{building_slug:e,org_slug:t});return this.sessionToken=n.data.session_token,this.leadUserId=n.data.lead_id,this.channel=n.data.channel,n.data}catch(e){return this.buildingWebchatView&&Ai({logTitle:"WEBCHAT_INIT_SESSION_ERROR",logData:{error:e},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug}),null}}addChatListener(e){this.chatListener=e}async initializePubnub(e){if(!e.leadId)return;this.leadUserId=e.leadId;const t=await this.fetchToken(this.leadUserId,this.channel);return t?(this.pubnub=new(Wa())({publishKey:t.keys.publish_key,subscribeKey:t.keys.subscribe_key,userId:this.leadUserId,authKey:t.auth.result.token,origin:"meetelise.pubnubapi.com"}),this.withAuthToken(()=>new Promise(()=>this.handleChatListeners())),await this.withAuthToken(()=>this.getChannelHistory()),this.pubnub):void 0}async fetchToken(e,t){try{if(this.sessionToken){const e="healthcare"===this.widgetType?"?industry=health_care":"";return(await r().get(`${this.apiHost}/platformApi/webchat/pn/v2/request-token${e}`,{headers:{"X-Session-Token":this.sessionToken}})).data}return(await r().get(`${this.apiHost}/platformApi/webchat/pn/request-token?user_id=${e}&channel=${t}&${"healthcare"===this.widgetType?"industry=health_care":""}`)).data}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_FETCHING_TOKEN",logData:{error:e},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}return null}async fetchChannelExists(e){try{return(await r().get(`${this.apiHost}/platformApi/webchat/check-channel-exists?channel_name=${e}`)).data}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_FETCHING_CHANNEL_EXISTS",logData:{error:e},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}return!1}async withAuthToken(e){try{await e()}catch(t){if(t instanceof i.AxiosError&&t&&t.response&&403===t.response.status)try{if(!this.pubnub||!this.leadUserId||!this.channel)return;const t=await this.fetchToken(this.leadUserId,this.channel);if(!t)return;this.pubnub.setAuthKey(t.auth.result.token),await e()}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_ERROR_REFETCHING_TOKEN",logData:{retryError:e},logType:xi.error,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}}}async getChannelHistory(e=1500){var t;try{let n=[],i=null;const r=100;for(let t=0;t<e;t+=r){const o=await new Promise((n,o)=>{if(!this.pubnub||!this.channel)return[];const a=Math.min(r,e-t);this.pubnub.fetchMessages({channels:[this.channel],count:a,start:null!=i?i:void 0},(e,t)=>{e.error?o(e):n(t)})}),a=o.channels[this.channel];if(!a)break;if(a.sort((e,t)=>+e.timetoken-+t.timetoken),!a||0===a.length)break;if(this.channel&&0!==Object.keys(o.channels).length){const e=o.channels[this.channel],t=[];e.forEach(e=>{e.uuid&&t.push({channel:e.channel,message:e.message,publisher:e.uuid,subscription:e.channel,timetoken:+e.timetoken})}),this.markEveryPreviousNoReplyMessageDone(t),n=n.concat(t.filter(e=>e.message.messageType!==as.noReply))}if(i=a[0].timetoken,n.length>=e||a.length<r)break}this.rawPubnubMessages=n.slice(0,e),this.simpleChatMessages=this.translatePubnubMessagesIntoSimpleChatMessages(this.rawPubnubMessages),null===(t=this.chatListener)||void 0===t||t.call(this,{messages:this.simpleChatMessages,isLoading:!1})}catch(e){this.buildingWebchatView&&Ai({logTitle:"PUBNUB_WARN_FETCHING_HISTORY",logData:{error:e},logType:xi.warn,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug})}}shouldCreateAsDevState(){return location.href.startsWith("https://app.meetelise.com/settings/widgets")||location.href.includes("demo/utilities")}},ds=(e,t,n)=>{const i=e.replace(/\D/g,"").replace(/^1(\d{10})$/,"$1"),r=`tel:${i}`,o=`sms:${i}`,a=`whatsapp://send?phone=${i}`,s=`facetime:${i}`,l=`facetime-audio:${i}`,u=/(?:\+1\s)?(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}/g,c=/(tel|sms):(?:\+1\s)?(?:(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}|\d{10,11})/g,d=/whatsapp:\/\/send\?phone=\d+/g,h=/(facetime|facetime-audio):\d+/g,p=document.body.getElementsByTagName("*");let f=!1;const g=i.replace(/(\d{3})(\d{3})(\d{4})/,"($1) $2-$3");let m=!1,y=!1,b=0;for(let e=0;e<p.length;e++)if(p[e].nodeType===Node.ELEMENT_NODE){if(1===p[e].childNodes.length&&p[e].childNodes[0].nodeType==Node.TEXT_NODE){const t=p[e].textContent;if(!t)continue;const n=t.replace(u,e=>e.startsWith("+1 ")?`+1 ${g}`:g);t!==n&&(b++,p[e].textContent=n),f=!0,m||(m=!0)}if(p[e].hasAttribute("href")){const t=p[e].getAttribute("href");if(!t)continue;let n="",i=c;t.startsWith("sms:")?n=o:t.startsWith("whatsapp:")?(n=a,i=d):t.startsWith("facetime:")?(n=s,i=h):t.startsWith("facetime-audio:")?(n=l,i=h):n=r;const u=t.replace(i,n);if(p[e].setAttribute("href",u),(t.startsWith("tel:")||t.startsWith("sms:"))&&u===t&&u!==n){t.replace(/\D/g,"").length>=7&&p[e].setAttribute("href",t.startsWith("tel:")?r:o)}y||(y=!0)}}return m&&Ai({logTitle:"DNI_WEBSITE_INSERTION",logData:{type:"text-insertion",newPhoneNumber:g,website:window.location.href},logType:xi.info,buildingSlug:n,orgSlug:t}),y&&Ai({logTitle:"DNI_WEBSITE_INSERTION",logData:{type:"href-insertion",newPhoneNumber:g,website:window.location.href},logType:xi.info,buildingSlug:n,orgSlug:t}),f||Ai({logTitle:"DNI_WEBSITE_INSERTION",logData:{type:"no-phone-number-found",website:window.location.href},logType:xi.warn,buildingSlug:n,orgSlug:t}),b};var hs=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a};let ps=class extends oe{constructor(){super(...arguments),this.onClick=()=>{},this.primaryColor=Ue,this.toExpand=!1}render(){return B`
5638
5638
  <button
5639
5639
  class=${this.toExpand?"button-container mini":"button-container"}
5640
5640
  @click=${this.onClick}
@@ -6806,7 +6806,7 @@ xmlns="http://www.w3.org/2000/svg"
6806
6806
  </button>
6807
6807
  </div>
6808
6808
  </div>
6809
- `}};Dl.styles=[kn,ms,gs,fs,Pl],Nl([ue({type:Number})],Dl.prototype,"right",void 0),Nl([ue({type:Number})],Dl.prototype,"bottom",void 0),Nl([ue({type:Number})],Dl.prototype,"top",void 0),Nl([ue({type:Number})],Dl.prototype,"left",void 0),Nl([ue({attribute:!0})],Dl.prototype,"onMount",void 0),Nl([ue({attribute:!0})],Dl.prototype,"channel",void 0),Nl([ue({attribute:!0})],Dl.prototype,"isHealthChat",void 0),Nl([ue({attribute:!0})],Dl.prototype,"myPubnub",void 0),Nl([ue({attribute:!0})],Dl.prototype,"orgSlug",void 0),Nl([ue({attribute:!0})],Dl.prototype,"buildingSlug",void 0),Nl([ue({attribute:!0})],Dl.prototype,"widgetType",void 0),Nl([ue({attribute:!0})],Dl.prototype,"building",void 0),Nl([ue({attribute:!0})],Dl.prototype,"primaryColor",void 0),Nl([ue({attribute:!0})],Dl.prototype,"backgroundColor",void 0),Nl([ue({attribute:!0})],Dl.prototype,"onClickExit",void 0),Nl([ue({attribute:!0})],Dl.prototype,"requiresConsent",void 0),Nl([de("#message-input",!0)],Dl.prototype,"messageInput",void 0),Nl([de("#conversation-body",!0)],Dl.prototype,"messageBody",void 0),Nl([ce()],Dl.prototype,"_isMobile",void 0),Nl([ce()],Dl.prototype,"messages",void 0),Nl([ce()],Dl.prototype,"isLoadingMessages",void 0),Nl([ce()],Dl.prototype,"hasReceivedConsent",void 0),Nl([ce()],Dl.prototype,"privacyPolicyUrl",void 0),Nl([ce()],Dl.prototype,"websitePreviewMapping",void 0),Dl=Nl([se("pubnub-chat")],Dl);const Ll="cdn.skypack.dev/@meetelise/chat",Ul="cdn.eliseai.com/@meetelise/chat",Rl=async(e,t)=>{try{if(Math.random()>=.15)return;const n=(()=>{try{const e=document.getElementsByTagName("script");for(const t of e){const e=t.src||"",n=t.textContent||"";if(e.includes(Ll)||n.includes(Ll))return"skypack";if(e.includes(Ul)||n.includes(Ul))return"eliseai"}return"unknown"}catch(e){return"unknown"}})();await r().post("https://app.meetelise.com/platformApi/webchat/cdn-version",{cdn_version:n},{params:{cdn_version:n},headers:{"Content-Type":"application/json","building-slug":t,"org-slug":e}})}catch(e){}},Bl=(e,t)=>["floor plan","floorplan","floor plans","floorplans","apply here"].some(t=>e.toLowerCase().includes(t))?`${t}/units`:t,jl=["Check Availability","Apply Now"],Fl=(e,t,n,i)=>{if(!(e=>{var t;if(!e.classList.contains("floorplan-button"))return!1;const n=e.getElementsByTagName("span");if(1!==n.length)return!1;const i=null===(t=n[0].textContent)||void 0===t?void 0:t.trim();return null!=i&&jl.includes(i)})(e))return!1;if(e.getAttribute("href")===t)return!1;const r=e.getAttribute("href");return e.setAttribute("href",t),e.setAttribute("target","_blank"),Ai({logTitle:"CHECK_AVAIL_OVERWRITE",logData:{oldHref:r,newHref:t,website:window.location.href},logType:xi.info,buildingSlug:i,orgSlug:n}),!0},Hl=(e,t,n,i)=>{for(let r=0;r<e.length;r++){const o=e[r];if(o.nodeType!==Node.ELEMENT_NODE)continue;const a=o;"A"===a.tagName&&Fl(a,t,n,i);const s=a.getElementsByTagName("a");for(let e=0;e<s.length;e++)Fl(s[e],t,n,i)}},$l=(e,t,n)=>{((e,t,n)=>{const i=document.body.getElementsByTagName("a");for(let r=0;r<i.length;r++)Fl(i[r],e,t,n)})(n,e,t);new MutationObserver(i=>{for(const r of i)Hl(r.addedNodes,n,e,t)}).observe(document.body,{childList:!0,subtree:!0})};class zl{constructor(e,t){this.persistLeadSourceTTLDays=30,this.maxSourcesNonPropertyWebsiteCount=3,this._generateLeadSourceLocalStorageKey=()=>`com.eliseai.webchat.leadsources.v2.buildingslug=${this.buildingSlug}`,this._generateNewExpirationTimestamp=()=>On(Pn(new Date,this.persistLeadSourceTTLDays)),this._generateLeadSourceParameters=()=>{const e=Ei();return{websiteOrigin:window.location.origin,websiteSearch:window.location.search,queryParameters:e,referrer:document.referrer,parsedUtmSource:e?e.utm_source:null,campaignSources:Object.values(Ci()).filter(e=>e)}},this.addSafeLeadSourceTouchpoint=e=>{const t=this.getLocalStorageMultitouchValue(),n=this._generateLeadSourceLocalStorageKey();if(!t||this.isExpiredTimestamp(t.timestampExpires)){const t={timestampExpires:this._generateNewExpirationTimestamp(),leadSources:[{parameters:this._generateLeadSourceParameters(),leadSourceValue:e,timestampInitiallyLogged:On(new Date),type:"touchpoint"}]};localStorage.setItem(n,JSON.stringify(t))}else{if(t.leadSources.find(t=>t.leadSourceValue===e))return;if(t.leadSources.length<this.maxSourcesNonPropertyWebsiteCount)return t.leadSources.push({parameters:this._generateLeadSourceParameters(),leadSourceValue:e,timestampInitiallyLogged:On(new Date),type:"touchpoint"}),t.timestampExpires=this._generateNewExpirationTimestamp(),void localStorage.setItem(n,JSON.stringify(t));Ai({logType:xi.warn,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,logTitle:"TOO_MANY_LEAD_SOURCES",logData:{buildingSlug:this.buildingSlug}})}},this.getSafeLeadSourceTouchpointsWithDefault=({includedUserSelectedLeadSource:e})=>{const t=this.getLocalStorageMultitouchValue(),n=Oi(this.orgSlug);if(!t){const t=[{leadSourceValue:n,timestampInitiallyLogged:On(new Date),type:"default"}];return e&&t.push({leadSourceValue:e,timestampInitiallyLogged:On(new Date),type:"user-selected"}),t}const i=t.leadSources.length>0?t.leadSources.sort((e,t)=>Rn(e.timestampInitiallyLogged).getTime()-Rn(t.timestampInitiallyLogged).getTime())[0].timestampInitiallyLogged:On(new Date),r=[{timestampInitiallyLogged:i,leadSourceValue:n,type:"default"},...t.leadSources.map(e=>({timestampInitiallyLogged:e.timestampInitiallyLogged,leadSourceValue:e.leadSourceValue,type:e.type}))];return e&&r.push({leadSourceValue:e,timestampInitiallyLogged:On(new Date),type:"user-selected"}),r},this.getLocalStorageMultitouchValue=()=>{const e=this._generateLeadSourceLocalStorageKey(),t=localStorage.getItem(e);if(!t)return null;return JSON.parse(t)},this.isExpiredTimestamp=e=>Rn(e)<new Date,this.resetLeadSourceTouchpoints=()=>{const e=this._generateLeadSourceLocalStorageKey();return localStorage.removeItem(e),!0},this.orgSlug=e,this.buildingSlug=t}}var Gl,Ql=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a};let ql=Gl=class extends oe{constructor(){super(...arguments),this.buildingSlug="",this.orgSlug="",this.launcherStyles={},this.mobileStyles={},this.isMinimized=!1,this.primaryColor=null,this.backgroundColor=null,this.foregroundColorOnPrimaryBackgroundColor=null,this.foregroundColorOnSecondaryBackgroundColor=null,this._isMobile=bn(),this.chatId="",this.analytics=null,this.launcher=null,this.buildingWebchatView=null,this.designConcept=null,this.leadSources=null,this.currentLeadSource=null,this.featureFlagShowDropdown=ri.always,this.phoneNumberForSource=null,this.hasMounted=!1,this.hideLauncher=!1,this.isLoading=!0,this.showTourNextToChat=!1,this.displayPubnubChat=!1,this.myPubnub=null,this.LeadSourceClient=null,this.LeadSourceMultitouchClient=null,this.sampleRateToUse=.05,this.right=void 0,this.bottom=void 0,this.top=void 0,this.left=void 0,this.overrideRentgrata=!1,this.widgetType=au.Default,this.onWidgetLoaded=Ca(),this.onSstClose=Ca(),this.enabledChatWidgets={callDesktop:!1,callMobile:!1,chatMobile:!1,chatDesktop:!1,emailDesktop:!1,emailMobile:!1,textDesktop:!1,textMobile:!1,sstDesktop:!1,sstMobile:!1,calcDesktop:!1,calcMobile:!1},this.webchatConfigHasAutoOpenChat=!1,this.requiresConsent=!1,this.hideMobileFeatures=!1,this.privacyPolicyUrl="http://bit.ly/me_privacy_policy",this.launcherRef=ke(),this.firstUpdated=async()=>this.setupWebchat(),this.setupWebchat=async()=>{if(!this.buildingSlug||!this.orgSlug)return;const e=await Ui(this.orgSlug,this.buildingSlug);if(Math.random()<.2)try{(async(e,t)=>{const n=window.rentgrata;if(!n)return;const i=n.Widget;if(!i)return;const o=i.config;if(!o)return;const a=o.widgetKey;a&&await r().post(`https://app.meetelise.com/platformApi/webchat/rentgrata?token=${a}`,{},{headers:{"Content-Type":"application/json","building-slug":null!=e?e:"","org-slug":null!=t?t:""}})})(this.buildingSlug,this.orgSlug)}catch(e){}try{Rl(this.orgSlug,this.buildingSlug)}catch(e){}await Er(e,this.buildingSlug,this.orgSlug)&&(Si({params:{org_slug:this.orgSlug,building_slug:this.buildingSlug,is_pixel_on_site:!0,is_any_webchat_showing:!0},sampleRate:(null==e?void 0:e.launchedDateTime)?.01:.05}),this.buildingWebchatView=e,await this.initializeChatVariables(),await this.handleChatInitializeAnalytics(),await this.setBuildingDerivedInfo(),this.attachOnClickToLauncher(),this.shouldAutoOpenChat(this.webchatConfigHasAutoOpenChat)&&(this.displayPubnubChat=!0,this.hideLauncher=!0,this.hasMounted=!0,this.updateAlreadyAutoOpenedTimestamp()),this.isLoading=!1,"true"===localStorage.getItem("isChatOpen")&&(this.hideLauncher=!0,this.displayPubnubChat=!0))},this.setBuildingDerivedInfo=async()=>{var e,t,n,i,o,a,s,l,u,c,d,h,p,f,g,m,y,b,v,w,C,x,A,S,E,k,T,_,O,P,I,M,N,D,L,U,R,B,j,F,H,$,z,G,Q,q,W,V;const Y=this.buildingWebchatView;if(!Y)return;Y&&this.orgSlug&&Vl(this.orgSlug,null!==(t=null===(e=this.LeadSourceClient)||void 0===e?void 0:e.chatId)&&void 0!==t?t:null,this.sampleRateToUse,this.buildingSlug,null!==(i=null===(n=this.LeadSourceClient)||void 0===n?void 0:n.leadSource)&&void 0!==i?i:null);const K=Y.featureFlagWebchatMarketingSourceDropdownConfiguration,X=Y.featureFlagWebchatUseDniPhoneNumberBySource,Z=Y.featureFlagInsertDniIntoWebsite,J=Y.featureFlagWebchatReplaceAnyScheduleTourCtaWebsite,[ee,te]=await Promise.all([za(this.orgSlug,this.buildingSlug),oi(this.buildingSlug)]);this.buildingWebchatView&&(this.buildingWebchatView.phoneNumber=Ie(Y.phoneNumber)),this.leadSources=ee,this.featureFlagShowDropdown=K;const ne=Y.textWithUsPhoneNumber?Y.textWithUsPhoneNumber:await(async e=>{try{const t="https://app.meetelise.com",n=await r().get(`${t}/platformApi/webchat/${e}/phone-number`);if(n.data)return n.data}catch(t){return Ai({logType:xi.error,buildingSlug:e,logTitle:"[ERROR_GETTING_PHONE_NUMBERS]",logData:{error:t}}),null}return null})(this.buildingSlug),ie=null!==(a=null===(o=this.buildingWebchatView)||void 0===o?void 0:o.shouldShowPricingCalculatorDesktop)&&void 0!==a&&a,re=null!==(l=null===(s=this.buildingWebchatView)||void 0===s?void 0:s.shouldShowPricingCalculatorMobile)&&void 0!==l&&l,oe={callDesktop:null!==(c=null===(u=this.buildingWebchatView)||void 0===u?void 0:u.shouldShowPhoneDesktop)&&void 0!==c&&c,callMobile:null!==(h=null===(d=this.buildingWebchatView)||void 0===d?void 0:d.shouldShowPhoneMobile)&&void 0!==h&&h,chatDesktop:null!==(f=null===(p=this.buildingWebchatView)||void 0===p?void 0:p.shouldShowChatDesktop)&&void 0!==f&&f,chatMobile:null!==(m=null===(g=this.buildingWebchatView)||void 0===g?void 0:g.shouldShowChatMobile)&&void 0!==m&&m,emailDesktop:null!==(b=null===(y=this.buildingWebchatView)||void 0===y?void 0:y.shouldShowEmailDesktop)&&void 0!==b&&b,emailMobile:null!==(w=null===(v=this.buildingWebchatView)||void 0===v?void 0:v.shouldShowEmailMobile)&&void 0!==w&&w,textDesktop:null!==(x=(null===(C=this.buildingWebchatView)||void 0===C?void 0:C.shouldShowTextDesktop)&&!!ne)&&void 0!==x&&x,textMobile:null!==(S=(null===(A=this.buildingWebchatView)||void 0===A?void 0:A.shouldShowTextMobile)&&!!ne)&&void 0!==S&&S,sstDesktop:null!==(k=null===(E=this.buildingWebchatView)||void 0===E?void 0:E.shouldShowSstDesktop)&&void 0!==k&&k,sstMobile:null!==(_=null===(T=this.buildingWebchatView)||void 0===T?void 0:T.shouldShowSstMobile)&&void 0!==_&&_,calcDesktop:ie,calcMobile:re};var ae,se;this.enabledChatWidgets=_a(oe),this.enabledChatWidgets.sstDesktop||this.enabledChatWidgets.sstMobile||"radco"===this.orgSlug?(se=this.handleTourClicked,document.querySelectorAll("a").forEach(function(e){const t=e.getAttribute("href");t&&t.startsWith("https://app.meetelise.com/")&&e.addEventListener("click",e=>{e.preventDefault(),se(e)})}),J&&(e=>{document.querySelectorAll('a[href$="schedule-a-tour"]').forEach(t=>{t&&t.addEventListener("click",t=>{t.preventDefault(),e(t)})})})(this.handleTourClicked),"radco"===this.orgSlug&&(e=>{document.querySelectorAll('a[href^="#leaseleads-tour-open"]').forEach(t=>{var n;if(!t)return;const i=document.createElement("a");i.textContent=t.textContent,i.style.cursor="pointer",i.addEventListener("click",t=>{t.preventDefault(),e(t)}),null===(n=t.parentNode)||void 0===n||n.replaceChild(i,t)})})(this.handleTourClicked)):(null===(O=this.LeadSourceClient)||void 0===O?void 0:O.leadSource)&&(ae=null!==(I=null===(P=this.LeadSourceClient)||void 0===P?void 0:P.leadSource)&&void 0!==I?I:null,document.querySelectorAll("a").forEach(function(e){const t=e.getAttribute("href");if(t&&t.startsWith("https://app.meetelise.com/")){const n=t.includes("?")?"&":"?";e.setAttribute("href",t+n+`eliseParsedLeadSource=${encodeURIComponent(ae)}`)}})),this.buildingWebchatView&&(this.primaryColor=null!==(M=this.buildingWebchatView.primaryColor)&&void 0!==M?M:null,this.backgroundColor=null!==(N=this.buildingWebchatView.secondaryColor)&&void 0!==N?N:null,this.foregroundColorOnPrimaryBackgroundColor=null!==(D=this.buildingWebchatView.foregroundColorOnPrimaryBackgroundColor)&&void 0!==D?D:null,this.foregroundColorOnSecondaryBackgroundColor=null!==(L=this.buildingWebchatView.foregroundColorOnSecondaryBackgroundColor)&&void 0!==L?L:null,this.webchatConfigHasAutoOpenChat=null!==(U=this.buildingWebchatView.autoOpenChat)&&void 0!==U&&U,this.requiresConsent=null!==(R=this.buildingWebchatView.requiresConsentForChat)&&void 0!==R&&R,this.hideMobileFeatures=null!==(B=this.buildingWebchatView.collapseMobileFeatures)&&void 0!==B&&B,this.privacyPolicyUrl=null!==(j=this.buildingWebchatView.privacyPolicyUrlForChat)&&void 0!==j?j:this.privacyPolicyUrl,this.buildingWebchatView.displayStyle===Mi.MINIMIZED&&(this.isMinimized=!0),this.buildingWebchatView.displayStyle===Mi.PILLS&&(this.designConcept=null),this.buildingWebchatView.displayStyle===Mi.EMOJI&&(this.designConcept=Mi.EMOJI),this.onWidgetLoaded()),null===this.primaryColor&&(this.primaryColor=Ue),null===this.backgroundColor&&(this.backgroundColor=Re);const le=null!==(H=null===(F=this.buildingWebchatView)||void 0===F?void 0:F.phoneNumber)&&void 0!==H?H:"";let ue=null;if(X&&(ue=await async function(e,t){try{const n=await r().get(`https://app.meetelise.com/platformApi/webchat/${e}/phone-number-by-source`,{params:{source:t}});return n.data?{number:Ie(n.data.number),isMatch:n.data.match,isPropertyWebsiteCatchall:n.data.isPropertyWebsiteCatchall}:null}catch(e){return null}}(this.buildingSlug,null!==(z=null===($=this.LeadSourceClient)||void 0===$?void 0:$.leadSource)&&void 0!==z?z:null),ue&&!ue.isMatch&&(ue.number=le)),Z&&(null==ue?void 0:ue.number)){const e=ds(ue.number,this.orgSlug,this.buildingSlug);e>0&&Si({params:{org_slug:this.orgSlug,building_slug:this.buildingSlug,is_dni_insert_override_success:!0,extra_data:{total_replacements:e}},sampleRate:this.sampleRateToUse})}const ce=localStorage.getItem("eliseai_phone_number_devtest");ce&&ds(ce,this.orgSlug,this.buildingSlug),this.phoneNumberForSource=ue||{number:le,isMatch:!1,isPropertyWebsiteCatchall:!0};const de=null!==(Q=null===(G=this.LeadSourceClient)||void 0===G?void 0:G.leadSource)&&void 0!==Q?Q:null;if(de&&(this.leadSources.includes(de)||this.leadSources.push(de)),Vn(Y.id),te&&this.buildingSlug&&(null===(q=this.buildingWebchatView)||void 0===q?void 0:q.isLiveOnApplications)){const e=((e,t,n)=>{var i;const r=[/thehavenatgreenhill\.securecafe\.com\/onlineleasing\/the-haven-at-greenhill\/oleapplication\.aspx(\?.*)?$/,/securecafe\.com\/onlineleasing.*\/oleapplication\.aspx(\?.*)?$/,/\/onlineleasing.*\/oleapplication\.aspx(\?.*)?$/,/vsc\.myresman\.com\/Portal\/Applicants\/Availability(\?.*)?$/,/vsc\.myresman\.com\/Portal\/Applicants\/New\/.*(\?.*)?$/,/busboomgroup\.myresman\.com\/Portal\/Applicants\/Availability(\?.*)?$/],o=document.body.getElementsByTagName("a");let a=0;for(let s=0;s<o.length;s++){const l=o[s];if(l.nodeType===Node.ELEMENT_NODE&&r.some(e=>e.test(l.href))){const r=l.getAttribute("href"),o=(null===(i=l.textContent)||void 0===i?void 0:i.toLowerCase())||"",s=Bl(o,e);l.setAttribute("href",s),a++,Ai({logTitle:"SELECT_BUTTON_LINK_REPLACEMENT",logData:{type:"link-replacement",oldHref:r,newHref:s,website:window.location.href},logType:xi.info,buildingSlug:n,orgSlug:t})}}return 0===a&&Ai({logTitle:"SELECT_BUTTON_LINK_REPLACEMENT",logData:{type:"no-select-buttons-found",website:window.location.href},logType:xi.warn,buildingSlug:n,orgSlug:t}),a})(`https://applications.eliseai.com/building/${this.buildingSlug}`,this.orgSlug,this.buildingSlug);e>0&&Si({params:{org_slug:this.orgSlug,building_slug:this.buildingSlug,is_application_link_replacement_success:!0,extra_data:{total_replacements:e}},sampleRate:this.sampleRateToUse})}this.buildingSlug&&(null===(W=this.buildingWebchatView)||void 0===W?void 0:W.isLiveOnApplications)&&(null===(V=this.buildingWebchatView)||void 0===V?void 0:V.applicationLink)&&"c954426c-12ab-4f8e-8384-8218e79eaf72"===this.orgSlug&&$l(this.orgSlug,this.buildingSlug,this.buildingWebchatView.applicationLink)},this.initializeChatVariables=async()=>{var e,t,n,i,r,o,a;if(!this.buildingWebchatView)return;const s=rs(this.buildingSlug),l=os(this.buildingSlug,s)?s:is(this.buildingSlug,!1);if(!l.leadId)throw new Error("Lead ID is null");this.LeadSourceClient=new Pi,this.LeadSourceMultitouchClient=new zl(this.orgSlug,this.buildingSlug),this.myPubnub=new cs(this.buildingSlug,this.buildingWebchatView,this.orgSlug,null,l.leadId,this.LeadSourceMultitouchClient,this.LeadSourceClient,this.widgetType),this.LeadSourceClient.chatId=this.myPubnub.channel;const u=await(null===(e=this.LeadSourceClient)||void 0===e?void 0:e.generateUserLeadSource({leadId:null!==(n=null===(t=this.myPubnub)||void 0===t?void 0:t.leadUserId)&&void 0!==n?n:"",orgSlug:this.orgSlug,buildingSlug:this.buildingSlug}));u&&this.LeadSourceMultitouchClient.addSafeLeadSourceTouchpoint(u),"property-website"!==Oi(this.orgSlug)?this.myPubnub.leadSource=null!==(r=null===(i=this.LeadSourceClient)||void 0===i?void 0:i.leadSource)&&void 0!==r?r:Oi(this.orgSlug):this.myPubnub.leadSource=null!==(a=null===(o=this.LeadSourceClient)||void 0===o?void 0:o.leadSource)&&void 0!==a?a:null,l.initiatedChat&&await this.myPubnub.initializePubnub(s)},this.shouldAutoOpenChat=e=>{const t=sessionStorage.getItem("alreadyAutoOpenedTimestamp"),n=!t||!(t&&!Dn(Rn(t)));return!!e&&!!n&&!bn()},this.updateAlreadyAutoOpenedTimestamp=()=>{sessionStorage.setItem("alreadyAutoOpenedTimestamp",On(function(e,t){return Ge(2,arguments),st(e,6e4*at(t))}(new Date,15)))},this.handleContactClicked=e=>{var t;this.displayPubnubChat=!1,this.hideLauncher=!1,this.showTourNextToChat=!1,null===(t=this.launcherRef.value)||void 0===t||t.onClickEmailOption(e)},this.handleTourClicked=e=>{var t,n;this.showTourNextToChat?null===(t=this.launcherRef.value)||void 0===t||t.onClickSSTOption(e):(this.hideLauncher?this.showTourNextToChat=!0:this.displayPubnubChat=!1,this.hideLauncher=!1,null===(n=this.launcherRef.value)||void 0===n||n.onClickSSTOption(e))},this.handleContactTabClicked=e=>{var t;this.displayPubnubChat=!1,this.showTourNextToChat=!1,this.hideLauncher=!1,null===(t=this.launcherRef.value)||void 0===t||t.onClickPhoneOption(e)},this.adjustPositionChatAdditionalActions=()=>{var e,t,n,i;const r=null===(e=this.shadowRoot)||void 0===e?void 0:e.getElementById("chatAdditionalActionsPubnub");if(!r)return;const o=null===(i=null===(n=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById("pubnub-chat"))||void 0===n?void 0:n.shadowRoot)||void 0===i?void 0:i.getElementById("pubnub-chat-container"),a=null==o?void 0:o.getBoundingClientRect();a&&(r.style.left=`${a.left}px`,r.style.top=`${a.bottom}px`)},this.handleKeydownTab=e=>{var t,n,i,r,o,a,s;if("Tab"===e.key){const l=null===(n=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById("meetelise-launcher"))||void 0===n?void 0:n.shadowRoot,u=this.displayPubnubChat?null===(o=null===(r=null===(i=this.shadowRoot)||void 0===i?void 0:i.getElementById("pubnub-chat"))||void 0===r?void 0:r.shadowRoot)||void 0===o?void 0:o.getElementById("pubnub-chat-container"):null!==(s=null!==(a=null==l?void 0:l.getElementById("email-us-window"))&&void 0!==a?a:null==l?void 0:l.getElementById("tour-scheduler-window"))&&void 0!==s?s:null==l?void 0:l.getElementById("call-us-window");if(!u)return;e.preventDefault();const c=this.displayPubnubChat?Array.from(u.querySelectorAll(Gl.FOCUSABLE_SELECTOR)):this.collectFocusableElements(u),d=this.getDeepActiveElement(),h=c.findIndex(e=>e===d);c[e.shiftKey?(h-1+c.length)%c.length:(h+1)%c.length].focus()}},this.onClickMinimize=e=>{e.preventDefault(),e.stopPropagation(),this.isMinimized=!this.isMinimized,this.showTourNextToChat=!1},this.attachOnClickToLauncher=()=>{const e=this.launcherRef.value;e&&(e.onChatTapped=async()=>{this.displayPubnubChat=!0,this.hideLauncher=!0,this.hasMounted=!0,localStorage.setItem("isChatOpen","true")},e.onExitChat=this.onExitChat)},this.onExitChat=()=>{this.displayPubnubChat=!1,this.hideLauncher=!1,this.showTourNextToChat=!1,localStorage.setItem("isChatOpen","false")}}async handleChatInitializeAnalytics(){var e,t,n,i;this.analytics=new wi(this.orgSlug,this.buildingSlug,null!==(t=null===(e=this.myPubnub)||void 0===e?void 0:e.channel)&&void 0!==t?t:"",null!==(i=null===(n=this.LeadSourceClient)||void 0===n?void 0:n.leadSource)&&void 0!==i?i:null),Math.random()<.05&&this.analytics.ping("webchat_heartbeat")}async restartConversation(){var e;null===(e=this.myPubnub)||void 0===e||e.handleDisconnect(),ns(this.buildingSlug),this.myPubnub=null,this.displayPubnubChat=!1,await this.setupWebchat(),this.hideLauncher=!1}show(){this.launcher&&(this.launcher.style.display="")}hide(){this.launcher&&(this.launcher.style.display="none")}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.adjustPositionChatAdditionalActions),window.addEventListener("keydown",this.handleKeydownTab),this._cleanupMobileListener=vn(e=>{this._isMobile=e})}static isFocusable(e){return!("disabled"in e)||!e.disabled}collectFocusableElements(e){const t=[];e instanceof Element&&e.shadowRoot&&t.push(...this.collectFocusableElements(e.shadowRoot));const n=e.querySelectorAll("*");for(const e of Array.from(n))e.matches(Gl.FOCUSABLE_SELECTOR)&&Gl.isFocusable(e)&&t.push(e),e.shadowRoot&&t.push(...this.collectFocusableElements(e.shadowRoot));return t}getDeepActiveElement(){let e=document.activeElement,t=0;for(;(null==e?void 0:e.shadowRoot)&&(null==e?void 0:e.shadowRoot.activeElement);)if(t+=1,e=null==e?void 0:e.shadowRoot.activeElement,t>100){Ai({logType:xi.error,buildingSlug:this.buildingSlug,logTitle:"[ERROR_GETTING_DEEP_ELEMENT]",logData:{message:"error getting deep active element"}});break}return e}updated(){this.adjustPositionChatAdditionalActions()}disconnectedCallback(){var e,t;null===(e=this.myPubnub)||void 0===e||e.handleDisconnect(),window.removeEventListener("resize",this.adjustPositionChatAdditionalActions),window.removeEventListener("keydown",this.handleKeydownTab),null===(t=this._cleanupMobileListener)||void 0===t||t.call(this),super.disconnectedCallback()}render(){var e,t,n,i,r,o,a,s,l,u,c,d,h,p,f,g,m,y,b,v,w,C,x,A,S,E,k,T,_,O,P,I,M,N,D,L,U;Ea();const R=this.hideLauncher&&!this.isLoading&&!this._isMobile;return B`
6809
+ `}};Dl.styles=[kn,ms,gs,fs,Pl],Nl([ue({type:Number})],Dl.prototype,"right",void 0),Nl([ue({type:Number})],Dl.prototype,"bottom",void 0),Nl([ue({type:Number})],Dl.prototype,"top",void 0),Nl([ue({type:Number})],Dl.prototype,"left",void 0),Nl([ue({attribute:!0})],Dl.prototype,"onMount",void 0),Nl([ue({attribute:!0})],Dl.prototype,"channel",void 0),Nl([ue({attribute:!0})],Dl.prototype,"isHealthChat",void 0),Nl([ue({attribute:!0})],Dl.prototype,"myPubnub",void 0),Nl([ue({attribute:!0})],Dl.prototype,"orgSlug",void 0),Nl([ue({attribute:!0})],Dl.prototype,"buildingSlug",void 0),Nl([ue({attribute:!0})],Dl.prototype,"widgetType",void 0),Nl([ue({attribute:!0})],Dl.prototype,"building",void 0),Nl([ue({attribute:!0})],Dl.prototype,"primaryColor",void 0),Nl([ue({attribute:!0})],Dl.prototype,"backgroundColor",void 0),Nl([ue({attribute:!0})],Dl.prototype,"onClickExit",void 0),Nl([ue({attribute:!0})],Dl.prototype,"requiresConsent",void 0),Nl([de("#message-input",!0)],Dl.prototype,"messageInput",void 0),Nl([de("#conversation-body",!0)],Dl.prototype,"messageBody",void 0),Nl([ce()],Dl.prototype,"_isMobile",void 0),Nl([ce()],Dl.prototype,"messages",void 0),Nl([ce()],Dl.prototype,"isLoadingMessages",void 0),Nl([ce()],Dl.prototype,"hasReceivedConsent",void 0),Nl([ce()],Dl.prototype,"privacyPolicyUrl",void 0),Nl([ce()],Dl.prototype,"websitePreviewMapping",void 0),Dl=Nl([se("pubnub-chat")],Dl);const Ll="cdn.skypack.dev/@meetelise/chat",Ul="cdn.eliseai.com/@meetelise/chat",Rl=async(e,t)=>{try{if(Math.random()>=.15)return;const n=(()=>{try{const e=document.getElementsByTagName("script");for(const t of e){const e=t.src||"",n=t.textContent||"";if(e.includes(Ll)||n.includes(Ll))return"skypack";if(e.includes(Ul)||n.includes(Ul))return"eliseai"}return"unknown"}catch(e){return"unknown"}})();await r().post("https://app.meetelise.com/platformApi/webchat/cdn-version",{cdn_version:n},{params:{cdn_version:n},headers:{"Content-Type":"application/json","building-slug":t,"org-slug":e}})}catch(e){}},Bl=(e,t)=>["floor plan","floorplan","floor plans","floorplans","apply here"].some(t=>e.toLowerCase().includes(t))?`${t}/units`:t,jl=["Check Availability","Apply Now"],Fl=(e,t,n,i)=>{if(!(e=>{var t;if(!e.classList.contains("floorplan-button"))return!1;const n=e.getElementsByTagName("span");if(1!==n.length)return!1;const i=null===(t=n[0].textContent)||void 0===t?void 0:t.trim();return null!=i&&jl.includes(i)})(e))return!1;if(e.getAttribute("href")===t)return!1;const r=e.getAttribute("href");return e.setAttribute("href",t),e.setAttribute("target","_blank"),Ai({logTitle:"CHECK_AVAIL_OVERWRITE",logData:{oldHref:r,newHref:t,website:window.location.href},logType:xi.info,buildingSlug:i,orgSlug:n}),!0},Hl=(e,t,n,i)=>{for(let r=0;r<e.length;r++){const o=e[r];if(o.nodeType!==Node.ELEMENT_NODE)continue;const a=o;"A"===a.tagName&&Fl(a,t,n,i);const s=a.getElementsByTagName("a");for(let e=0;e<s.length;e++)Fl(s[e],t,n,i)}},$l=(e,t,n)=>{((e,t,n)=>{const i=document.body.getElementsByTagName("a");for(let r=0;r<i.length;r++)Fl(i[r],e,t,n)})(n,e,t);new MutationObserver(i=>{for(const r of i)Hl(r.addedNodes,n,e,t)}).observe(document.body,{childList:!0,subtree:!0})};class zl{constructor(e,t){this.persistLeadSourceTTLDays=30,this.maxSourcesNonPropertyWebsiteCount=3,this._generateLeadSourceLocalStorageKey=()=>`com.eliseai.webchat.leadsources.v2.buildingslug=${this.buildingSlug}`,this._generateNewExpirationTimestamp=()=>On(Pn(new Date,this.persistLeadSourceTTLDays)),this._generateLeadSourceParameters=()=>{const e=Ei();return{websiteOrigin:window.location.origin,websiteSearch:window.location.search,queryParameters:e,referrer:document.referrer,parsedUtmSource:e?e.utm_source:null,campaignSources:Object.values(Ci()).filter(e=>e)}},this.addSafeLeadSourceTouchpoint=e=>{const t=this.getLocalStorageMultitouchValue(),n=this._generateLeadSourceLocalStorageKey();if(!t||this.isExpiredTimestamp(t.timestampExpires)){const t={timestampExpires:this._generateNewExpirationTimestamp(),leadSources:[{parameters:this._generateLeadSourceParameters(),leadSourceValue:e,timestampInitiallyLogged:On(new Date),type:"touchpoint"}]};localStorage.setItem(n,JSON.stringify(t))}else{if(t.leadSources.find(t=>t.leadSourceValue===e))return;if(t.leadSources.length<this.maxSourcesNonPropertyWebsiteCount)return t.leadSources.push({parameters:this._generateLeadSourceParameters(),leadSourceValue:e,timestampInitiallyLogged:On(new Date),type:"touchpoint"}),t.timestampExpires=this._generateNewExpirationTimestamp(),void localStorage.setItem(n,JSON.stringify(t));Ai({logType:xi.warn,buildingSlug:this.buildingSlug,orgSlug:this.orgSlug,logTitle:"TOO_MANY_LEAD_SOURCES",logData:{buildingSlug:this.buildingSlug}})}},this.getSafeLeadSourceTouchpointsWithDefault=({includedUserSelectedLeadSource:e})=>{const t=this.getLocalStorageMultitouchValue(),n=Oi(this.orgSlug);if(!t){const t=[{leadSourceValue:n,timestampInitiallyLogged:On(new Date),type:"default"}];return e&&t.push({leadSourceValue:e,timestampInitiallyLogged:On(new Date),type:"user-selected"}),t}const i=t.leadSources.length>0?t.leadSources.sort((e,t)=>Rn(e.timestampInitiallyLogged).getTime()-Rn(t.timestampInitiallyLogged).getTime())[0].timestampInitiallyLogged:On(new Date),r=[{timestampInitiallyLogged:i,leadSourceValue:n,type:"default"},...t.leadSources.map(e=>({timestampInitiallyLogged:e.timestampInitiallyLogged,leadSourceValue:e.leadSourceValue,type:e.type}))];return e&&r.push({leadSourceValue:e,timestampInitiallyLogged:On(new Date),type:"user-selected"}),r},this.getLocalStorageMultitouchValue=()=>{const e=this._generateLeadSourceLocalStorageKey(),t=localStorage.getItem(e);if(!t)return null;return JSON.parse(t)},this.isExpiredTimestamp=e=>Rn(e)<new Date,this.resetLeadSourceTouchpoints=()=>{const e=this._generateLeadSourceLocalStorageKey();return localStorage.removeItem(e),!0},this.orgSlug=e,this.buildingSlug=t}}var Gl,Ql=function(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a};let ql=Gl=class extends oe{constructor(){super(...arguments),this.buildingSlug="",this.orgSlug="",this.launcherStyles={},this.mobileStyles={},this.isMinimized=!1,this.primaryColor=null,this.backgroundColor=null,this.foregroundColorOnPrimaryBackgroundColor=null,this.foregroundColorOnSecondaryBackgroundColor=null,this._isMobile=bn(),this.chatId="",this.analytics=null,this.launcher=null,this.buildingWebchatView=null,this.designConcept=null,this.leadSources=null,this.currentLeadSource=null,this.featureFlagShowDropdown=ri.always,this.phoneNumberForSource=null,this.hasMounted=!1,this.hideLauncher=!1,this.isLoading=!0,this.showTourNextToChat=!1,this.displayPubnubChat=!1,this.myPubnub=null,this.LeadSourceClient=null,this.LeadSourceMultitouchClient=null,this.sampleRateToUse=.05,this.right=void 0,this.bottom=void 0,this.top=void 0,this.left=void 0,this.overrideRentgrata=!1,this.widgetType=au.Default,this.onWidgetLoaded=Ca(),this.onSstClose=Ca(),this.enabledChatWidgets={callDesktop:!1,callMobile:!1,chatMobile:!1,chatDesktop:!1,emailDesktop:!1,emailMobile:!1,textDesktop:!1,textMobile:!1,sstDesktop:!1,sstMobile:!1,calcDesktop:!1,calcMobile:!1},this.webchatConfigHasAutoOpenChat=!1,this.requiresConsent=!1,this.hideMobileFeatures=!1,this.privacyPolicyUrl="http://bit.ly/me_privacy_policy",this.launcherRef=ke(),this.firstUpdated=async()=>this.setupWebchat(),this.setupWebchat=async()=>{if(!this.buildingSlug||!this.orgSlug)return;const e=await Ui(this.orgSlug,this.buildingSlug);if(Math.random()<.2)try{(async(e,t)=>{const n=window.rentgrata;if(!n)return;const i=n.Widget;if(!i)return;const o=i.config;if(!o)return;const a=o.widgetKey;a&&await r().post(`https://app.meetelise.com/platformApi/webchat/rentgrata?token=${a}`,{},{headers:{"Content-Type":"application/json","building-slug":null!=e?e:"","org-slug":null!=t?t:""}})})(this.buildingSlug,this.orgSlug)}catch(e){}try{Rl(this.orgSlug,this.buildingSlug)}catch(e){}await Er(e,this.buildingSlug,this.orgSlug)&&(Si({params:{org_slug:this.orgSlug,building_slug:this.buildingSlug,is_pixel_on_site:!0,is_any_webchat_showing:!0},sampleRate:(null==e?void 0:e.launchedDateTime)?.01:.05}),this.buildingWebchatView=e,await this.initializeChatVariables(),await this.handleChatInitializeAnalytics(),await this.setBuildingDerivedInfo(),this.attachOnClickToLauncher(),this.shouldAutoOpenChat(this.webchatConfigHasAutoOpenChat)&&(this.displayPubnubChat=!0,this.hideLauncher=!0,this.hasMounted=!0,this.updateAlreadyAutoOpenedTimestamp()),this.isLoading=!1,"true"===localStorage.getItem("isChatOpen")&&(this.hideLauncher=!0,this.displayPubnubChat=!0))},this.setBuildingDerivedInfo=async()=>{var e,t,n,i,o,a,s,l,u,c,d,h,p,f,g,m,y,b,v,w,C,x,A,S,E,k,T,_,O,P,I,M,N,D,L,U,R,B,j,F,H,$,z,G,Q,q,W,V;const Y=this.buildingWebchatView;if(!Y)return;Y&&this.orgSlug&&Vl(this.orgSlug,null!==(t=null===(e=this.LeadSourceClient)||void 0===e?void 0:e.chatId)&&void 0!==t?t:null,this.sampleRateToUse,this.buildingSlug,null!==(i=null===(n=this.LeadSourceClient)||void 0===n?void 0:n.leadSource)&&void 0!==i?i:null);const K=Y.featureFlagWebchatMarketingSourceDropdownConfiguration,X=Y.featureFlagWebchatUseDniPhoneNumberBySource,Z=Y.featureFlagInsertDniIntoWebsite,J=Y.featureFlagWebchatReplaceAnyScheduleTourCtaWebsite,[ee,te]=await Promise.all([za(this.orgSlug,this.buildingSlug),oi(this.buildingSlug)]);this.buildingWebchatView&&(this.buildingWebchatView.phoneNumber=Ie(Y.phoneNumber)),this.leadSources=ee,this.featureFlagShowDropdown=K;const ne=Y.textWithUsPhoneNumber?Y.textWithUsPhoneNumber:await(async e=>{try{const t="https://app.meetelise.com",n=await r().get(`${t}/platformApi/webchat/${e}/phone-number`);if(n.data)return n.data}catch(t){return Ai({logType:xi.error,buildingSlug:e,logTitle:"[ERROR_GETTING_PHONE_NUMBERS]",logData:{error:t}}),null}return null})(this.buildingSlug),ie=null!==(a=null===(o=this.buildingWebchatView)||void 0===o?void 0:o.shouldShowPricingCalculatorDesktop)&&void 0!==a&&a,re=null!==(l=null===(s=this.buildingWebchatView)||void 0===s?void 0:s.shouldShowPricingCalculatorMobile)&&void 0!==l&&l,oe={callDesktop:null!==(c=null===(u=this.buildingWebchatView)||void 0===u?void 0:u.shouldShowPhoneDesktop)&&void 0!==c&&c,callMobile:null!==(h=null===(d=this.buildingWebchatView)||void 0===d?void 0:d.shouldShowPhoneMobile)&&void 0!==h&&h,chatDesktop:null!==(f=null===(p=this.buildingWebchatView)||void 0===p?void 0:p.shouldShowChatDesktop)&&void 0!==f&&f,chatMobile:null!==(m=null===(g=this.buildingWebchatView)||void 0===g?void 0:g.shouldShowChatMobile)&&void 0!==m&&m,emailDesktop:null!==(b=null===(y=this.buildingWebchatView)||void 0===y?void 0:y.shouldShowEmailDesktop)&&void 0!==b&&b,emailMobile:null!==(w=null===(v=this.buildingWebchatView)||void 0===v?void 0:v.shouldShowEmailMobile)&&void 0!==w&&w,textDesktop:null!==(x=(null===(C=this.buildingWebchatView)||void 0===C?void 0:C.shouldShowTextDesktop)&&!!ne)&&void 0!==x&&x,textMobile:null!==(S=(null===(A=this.buildingWebchatView)||void 0===A?void 0:A.shouldShowTextMobile)&&!!ne)&&void 0!==S&&S,sstDesktop:null!==(k=null===(E=this.buildingWebchatView)||void 0===E?void 0:E.shouldShowSstDesktop)&&void 0!==k&&k,sstMobile:null!==(_=null===(T=this.buildingWebchatView)||void 0===T?void 0:T.shouldShowSstMobile)&&void 0!==_&&_,calcDesktop:ie,calcMobile:re};var ae,se;this.enabledChatWidgets=_a(oe),this.enabledChatWidgets.sstDesktop||this.enabledChatWidgets.sstMobile||"radco"===this.orgSlug?(se=this.handleTourClicked,document.querySelectorAll("a").forEach(function(e){const t=e.getAttribute("href");t&&t.startsWith("https://app.meetelise.com/")&&e.addEventListener("click",e=>{e.preventDefault(),se(e)})}),J&&(e=>{document.querySelectorAll('a[href$="schedule-a-tour"]').forEach(t=>{t&&t.addEventListener("click",t=>{t.preventDefault(),e(t)})})})(this.handleTourClicked),"radco"===this.orgSlug&&(e=>{document.querySelectorAll('a[href^="#leaseleads-tour-open"]').forEach(t=>{var n;if(!t)return;const i=document.createElement("a");i.textContent=t.textContent,i.style.cursor="pointer",i.addEventListener("click",t=>{t.preventDefault(),e(t)}),null===(n=t.parentNode)||void 0===n||n.replaceChild(i,t)})})(this.handleTourClicked)):(null===(O=this.LeadSourceClient)||void 0===O?void 0:O.leadSource)&&(ae=null!==(I=null===(P=this.LeadSourceClient)||void 0===P?void 0:P.leadSource)&&void 0!==I?I:null,document.querySelectorAll("a").forEach(function(e){const t=e.getAttribute("href");if(t&&t.startsWith("https://app.meetelise.com/")){const n=t.includes("?")?"&":"?";e.setAttribute("href",t+n+`eliseParsedLeadSource=${encodeURIComponent(ae)}`)}})),this.buildingWebchatView&&(this.primaryColor=null!==(M=this.buildingWebchatView.primaryColor)&&void 0!==M?M:null,this.backgroundColor=null!==(N=this.buildingWebchatView.secondaryColor)&&void 0!==N?N:null,this.foregroundColorOnPrimaryBackgroundColor=null!==(D=this.buildingWebchatView.foregroundColorOnPrimaryBackgroundColor)&&void 0!==D?D:null,this.foregroundColorOnSecondaryBackgroundColor=null!==(L=this.buildingWebchatView.foregroundColorOnSecondaryBackgroundColor)&&void 0!==L?L:null,this.webchatConfigHasAutoOpenChat=null!==(U=this.buildingWebchatView.autoOpenChat)&&void 0!==U&&U,this.requiresConsent=null!==(R=this.buildingWebchatView.requiresConsentForChat)&&void 0!==R&&R,this.hideMobileFeatures=null!==(B=this.buildingWebchatView.collapseMobileFeatures)&&void 0!==B&&B,this.privacyPolicyUrl=null!==(j=this.buildingWebchatView.privacyPolicyUrlForChat)&&void 0!==j?j:this.privacyPolicyUrl,this.buildingWebchatView.displayStyle===Mi.MINIMIZED&&(this.isMinimized=!0),this.buildingWebchatView.displayStyle===Mi.PILLS&&(this.designConcept=null),this.buildingWebchatView.displayStyle===Mi.EMOJI&&(this.designConcept=Mi.EMOJI),this.onWidgetLoaded()),null===this.primaryColor&&(this.primaryColor=Ue),null===this.backgroundColor&&(this.backgroundColor=Re);const le=null!==(H=null===(F=this.buildingWebchatView)||void 0===F?void 0:F.phoneNumber)&&void 0!==H?H:"";let ue=null;if(X&&(ue=await async function(e,t){try{const n=await r().get(`https://app.meetelise.com/platformApi/webchat/${e}/phone-number-by-source`,{params:{source:t}});return n.data?{number:Ie(n.data.number),isMatch:n.data.match,isPropertyWebsiteCatchall:n.data.isPropertyWebsiteCatchall}:null}catch(e){return null}}(this.buildingSlug,null!==(z=null===($=this.LeadSourceClient)||void 0===$?void 0:$.leadSource)&&void 0!==z?z:null),ue&&!ue.isMatch&&(ue.number=le)),Z&&(null==ue?void 0:ue.number)){const e=ds(ue.number,this.orgSlug,this.buildingSlug);e>0&&Si({params:{org_slug:this.orgSlug,building_slug:this.buildingSlug,is_dni_insert_override_success:!0,extra_data:{total_replacements:e}},sampleRate:this.sampleRateToUse})}const ce=localStorage.getItem("eliseai_phone_number_devtest");ce&&ds(ce,this.orgSlug,this.buildingSlug),this.phoneNumberForSource=ue||{number:le,isMatch:!1,isPropertyWebsiteCatchall:!0};const de=null!==(Q=null===(G=this.LeadSourceClient)||void 0===G?void 0:G.leadSource)&&void 0!==Q?Q:null;if(de&&(this.leadSources.includes(de)||this.leadSources.push(de)),Vn(Y.id),te&&this.buildingSlug&&(null===(q=this.buildingWebchatView)||void 0===q?void 0:q.isLiveOnApplications)){const e=((e,t,n)=>{var i;const r=[/thehavenatgreenhill\.securecafe\.com\/onlineleasing\/the-haven-at-greenhill\/oleapplication\.aspx(\?.*)?$/,/securecafe\.com\/onlineleasing.*\/oleapplication\.aspx(\?.*)?$/,/\/onlineleasing.*\/oleapplication\.aspx(\?.*)?$/,/vsc\.myresman\.com\/Portal\/Applicants\/Availability(\?.*)?$/,/vsc\.myresman\.com\/Portal\/Applicants\/New\/.*(\?.*)?$/,/busboomgroup\.myresman\.com\/Portal\/Applicants\/Availability(\?.*)?$/],o=document.body.getElementsByTagName("a");let a=0;for(let s=0;s<o.length;s++){const l=o[s];if(l.nodeType===Node.ELEMENT_NODE&&r.some(e=>e.test(l.href))){const r=l.getAttribute("href"),o=(null===(i=l.textContent)||void 0===i?void 0:i.toLowerCase())||"",s=Bl(o,e);l.setAttribute("href",s),a++,Ai({logTitle:"SELECT_BUTTON_LINK_REPLACEMENT",logData:{type:"link-replacement",oldHref:r,newHref:s,website:window.location.href},logType:xi.info,buildingSlug:n,orgSlug:t})}}return 0===a&&Ai({logTitle:"SELECT_BUTTON_LINK_REPLACEMENT",logData:{type:"no-select-buttons-found",website:window.location.href},logType:xi.warn,buildingSlug:n,orgSlug:t}),a})(`https://applications.eliseai.com/building/${this.buildingSlug}`,this.orgSlug,this.buildingSlug);e>0&&Si({params:{org_slug:this.orgSlug,building_slug:this.buildingSlug,is_application_link_replacement_success:!0,extra_data:{total_replacements:e}},sampleRate:this.sampleRateToUse})}this.buildingSlug&&(null===(W=this.buildingWebchatView)||void 0===W?void 0:W.isLiveOnApplications)&&(null===(V=this.buildingWebchatView)||void 0===V?void 0:V.applicationLink)&&"c954426c-12ab-4f8e-8384-8218e79eaf72"===this.orgSlug&&$l(this.orgSlug,this.buildingSlug,this.buildingWebchatView.applicationLink)},this.initializeChatVariables=async()=>{var e,t,n,i,r,o,a;if(!this.buildingWebchatView)return;const s=rs(this.buildingSlug),l=os(this.buildingSlug,s),u=l?s:is(this.buildingSlug,!1);if(!u.leadId)throw new Error("Lead ID is null");if(this.LeadSourceClient=new Pi,this.LeadSourceMultitouchClient=new zl(this.orgSlug,this.buildingSlug),this.myPubnub=new cs(this.buildingSlug,this.buildingWebchatView,this.orgSlug,null,u.leadId,this.LeadSourceMultitouchClient,this.LeadSourceClient,this.widgetType),!l){const e=await this.myPubnub.initSession(this.buildingSlug,this.orgSlug);e&&is(this.buildingSlug,!1,e.lead_id)}this.LeadSourceClient.chatId=this.myPubnub.channel;const c=await(null===(e=this.LeadSourceClient)||void 0===e?void 0:e.generateUserLeadSource({leadId:null!==(n=null===(t=this.myPubnub)||void 0===t?void 0:t.leadUserId)&&void 0!==n?n:"",orgSlug:this.orgSlug,buildingSlug:this.buildingSlug}));c&&this.LeadSourceMultitouchClient.addSafeLeadSourceTouchpoint(c),"property-website"!==Oi(this.orgSlug)?this.myPubnub.leadSource=null!==(r=null===(i=this.LeadSourceClient)||void 0===i?void 0:i.leadSource)&&void 0!==r?r:Oi(this.orgSlug):this.myPubnub.leadSource=null!==(a=null===(o=this.LeadSourceClient)||void 0===o?void 0:o.leadSource)&&void 0!==a?a:null,u.initiatedChat&&await this.myPubnub.initializePubnub(s)},this.shouldAutoOpenChat=e=>{const t=sessionStorage.getItem("alreadyAutoOpenedTimestamp"),n=!t||!(t&&!Dn(Rn(t)));return!!e&&!!n&&!bn()},this.updateAlreadyAutoOpenedTimestamp=()=>{sessionStorage.setItem("alreadyAutoOpenedTimestamp",On(function(e,t){return Ge(2,arguments),st(e,6e4*at(t))}(new Date,15)))},this.handleContactClicked=e=>{var t;this.displayPubnubChat=!1,this.hideLauncher=!1,this.showTourNextToChat=!1,null===(t=this.launcherRef.value)||void 0===t||t.onClickEmailOption(e)},this.handleTourClicked=e=>{var t,n;this.showTourNextToChat?null===(t=this.launcherRef.value)||void 0===t||t.onClickSSTOption(e):(this.hideLauncher?this.showTourNextToChat=!0:this.displayPubnubChat=!1,this.hideLauncher=!1,null===(n=this.launcherRef.value)||void 0===n||n.onClickSSTOption(e))},this.handleContactTabClicked=e=>{var t;this.displayPubnubChat=!1,this.showTourNextToChat=!1,this.hideLauncher=!1,null===(t=this.launcherRef.value)||void 0===t||t.onClickPhoneOption(e)},this.adjustPositionChatAdditionalActions=()=>{var e,t,n,i;const r=null===(e=this.shadowRoot)||void 0===e?void 0:e.getElementById("chatAdditionalActionsPubnub");if(!r)return;const o=null===(i=null===(n=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById("pubnub-chat"))||void 0===n?void 0:n.shadowRoot)||void 0===i?void 0:i.getElementById("pubnub-chat-container"),a=null==o?void 0:o.getBoundingClientRect();a&&(r.style.left=`${a.left}px`,r.style.top=`${a.bottom}px`)},this.handleKeydownTab=e=>{var t,n,i,r,o,a,s;if("Tab"===e.key){const l=null===(n=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById("meetelise-launcher"))||void 0===n?void 0:n.shadowRoot,u=this.displayPubnubChat?null===(o=null===(r=null===(i=this.shadowRoot)||void 0===i?void 0:i.getElementById("pubnub-chat"))||void 0===r?void 0:r.shadowRoot)||void 0===o?void 0:o.getElementById("pubnub-chat-container"):null!==(s=null!==(a=null==l?void 0:l.getElementById("email-us-window"))&&void 0!==a?a:null==l?void 0:l.getElementById("tour-scheduler-window"))&&void 0!==s?s:null==l?void 0:l.getElementById("call-us-window");if(!u)return;e.preventDefault();const c=this.displayPubnubChat?Array.from(u.querySelectorAll(Gl.FOCUSABLE_SELECTOR)):this.collectFocusableElements(u),d=this.getDeepActiveElement(),h=c.findIndex(e=>e===d);c[e.shiftKey?(h-1+c.length)%c.length:(h+1)%c.length].focus()}},this.onClickMinimize=e=>{e.preventDefault(),e.stopPropagation(),this.isMinimized=!this.isMinimized,this.showTourNextToChat=!1},this.attachOnClickToLauncher=()=>{const e=this.launcherRef.value;e&&(e.onChatTapped=async()=>{this.displayPubnubChat=!0,this.hideLauncher=!0,this.hasMounted=!0,localStorage.setItem("isChatOpen","true")},e.onExitChat=this.onExitChat)},this.onExitChat=()=>{this.displayPubnubChat=!1,this.hideLauncher=!1,this.showTourNextToChat=!1,localStorage.setItem("isChatOpen","false")}}async handleChatInitializeAnalytics(){var e,t,n,i;this.analytics=new wi(this.orgSlug,this.buildingSlug,null!==(t=null===(e=this.myPubnub)||void 0===e?void 0:e.channel)&&void 0!==t?t:"",null!==(i=null===(n=this.LeadSourceClient)||void 0===n?void 0:n.leadSource)&&void 0!==i?i:null),Math.random()<.05&&this.analytics.ping("webchat_heartbeat")}async restartConversation(){var e;null===(e=this.myPubnub)||void 0===e||e.handleDisconnect(),ns(this.buildingSlug),this.myPubnub=null,this.displayPubnubChat=!1,await this.setupWebchat(),this.hideLauncher=!1}show(){this.launcher&&(this.launcher.style.display="")}hide(){this.launcher&&(this.launcher.style.display="none")}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.adjustPositionChatAdditionalActions),window.addEventListener("keydown",this.handleKeydownTab),this._cleanupMobileListener=vn(e=>{this._isMobile=e})}static isFocusable(e){return!("disabled"in e)||!e.disabled}collectFocusableElements(e){const t=[];e instanceof Element&&e.shadowRoot&&t.push(...this.collectFocusableElements(e.shadowRoot));const n=e.querySelectorAll("*");for(const e of Array.from(n))e.matches(Gl.FOCUSABLE_SELECTOR)&&Gl.isFocusable(e)&&t.push(e),e.shadowRoot&&t.push(...this.collectFocusableElements(e.shadowRoot));return t}getDeepActiveElement(){let e=document.activeElement,t=0;for(;(null==e?void 0:e.shadowRoot)&&(null==e?void 0:e.shadowRoot.activeElement);)if(t+=1,e=null==e?void 0:e.shadowRoot.activeElement,t>100){Ai({logType:xi.error,buildingSlug:this.buildingSlug,logTitle:"[ERROR_GETTING_DEEP_ELEMENT]",logData:{message:"error getting deep active element"}});break}return e}updated(){this.adjustPositionChatAdditionalActions()}disconnectedCallback(){var e,t;null===(e=this.myPubnub)||void 0===e||e.handleDisconnect(),window.removeEventListener("resize",this.adjustPositionChatAdditionalActions),window.removeEventListener("keydown",this.handleKeydownTab),null===(t=this._cleanupMobileListener)||void 0===t||t.call(this),super.disconnectedCallback()}render(){var e,t,n,i,r,o,a,s,l,u,c,d,h,p,f,g,m,y,b,v,w,C,x,A,S,E,k,T,_,O,P,I,M,N,D,L,U;Ea();const R=this.hideLauncher&&!this.isLoading&&!this._isMobile;return B`
6810
6810
  <meta name="viewport" content="width=device-width, initial-scale=1">
6811
6811
  <div id="aria-describe-info" style="display: none;">
6812
6812
  EliseAI widget that allows you to chat with a virtual assistant, book
package/src/MyPubnub.ts CHANGED
@@ -111,6 +111,7 @@ class MyPubnub {
111
111
  leadUserId = "";
112
112
  channel = "";
113
113
  leadSource: string | null = null;
114
+ private sessionToken: string | null = null;
114
115
 
115
116
  isCurrentlyStreamingMessage = false;
116
117
 
@@ -206,6 +207,38 @@ class MyPubnub {
206
207
  this.widgetType = widgetType;
207
208
  }
208
209
 
210
+ async initSession(
211
+ buildingSlug: string,
212
+ orgSlug: string
213
+ ): Promise<{
214
+ session_token: string;
215
+ lead_id: string;
216
+ channel: string;
217
+ expires_in_seconds: number;
218
+ } | null> {
219
+ try {
220
+ const response = await axios.post(
221
+ `${this.apiHost}/platformApi/webchat/init`,
222
+ { building_slug: buildingSlug, org_slug: orgSlug }
223
+ );
224
+ this.sessionToken = response.data.session_token;
225
+ this.leadUserId = response.data.lead_id;
226
+ this.channel = response.data.channel;
227
+ return response.data;
228
+ } catch (error) {
229
+ if (this.buildingWebchatView) {
230
+ sendLoggingEvent({
231
+ logTitle: "WEBCHAT_INIT_SESSION_ERROR",
232
+ logData: { error },
233
+ logType: LogType.error,
234
+ buildingSlug: this.buildingSlug,
235
+ orgSlug: this.orgSlug,
236
+ });
237
+ }
238
+ return null;
239
+ }
240
+ }
241
+
209
242
  private checkAndHandleDelayStreamingMessages = ({
210
243
  delayToFetchHistoryInMs = 10000,
211
244
  }: { delayToFetchHistoryInMs?: number } = {}): void => {
@@ -298,6 +331,20 @@ class MyPubnub {
298
331
  channel: string
299
332
  ): Promise<TokenResponse | null> {
300
333
  try {
334
+ // Use v2 endpoint when we have a session token, fall back to v1 for old sessions
335
+ if (this.sessionToken) {
336
+ const industryParam =
337
+ this.widgetType === "healthcare" ? "?industry=health_care" : "";
338
+ const response = await axios.get(
339
+ `${this.apiHost}/platformApi/webchat/pn/v2/request-token${industryParam}`,
340
+ {
341
+ headers: { "X-Session-Token": this.sessionToken },
342
+ }
343
+ );
344
+ return response.data;
345
+ }
346
+
347
+ // v1 fallback for returning users with existing localStorage sessions
301
348
  const response = await axios.get(
302
349
  `${
303
350
  this.apiHost
@@ -562,10 +562,14 @@ export class MEChat extends LitElement {
562
562
 
563
563
  // important to distinguish between a user who has never opened the chat and a user who has opened the chat but closed it
564
564
  const currentChatStorageKey = getChatStorageKey(this.buildingSlug);
565
- const updatedChatStorageKey = isChatKeyValid(
565
+ const isReturningUser = isChatKeyValid(
566
566
  this.buildingSlug,
567
567
  currentChatStorageKey
568
- )
568
+ );
569
+
570
+ // For returning users, keep their existing leadId. For new users, create a
571
+ // temporary client-generated one (will be overwritten by server session below).
572
+ const updatedChatStorageKey = isReturningUser
569
573
  ? currentChatStorageKey
570
574
  : createChatStorageKey(this.buildingSlug, false);
571
575
 
@@ -589,6 +593,23 @@ export class MEChat extends LitElement {
589
593
  this.LeadSourceClient,
590
594
  this.widgetType
591
595
  );
596
+
597
+ // For new users, create a server-side session for secure v2 token endpoint.
598
+ // initSession() overwrites myPubnub.leadUserId and myPubnub.channel with
599
+ // server-generated values and stores the session token for v2 auth.
600
+ if (!isReturningUser) {
601
+ const session = await this.myPubnub.initSession(
602
+ this.buildingSlug,
603
+ this.orgSlug
604
+ );
605
+ if (session) {
606
+ // Persist the server-provided leadId to localStorage
607
+ createChatStorageKey(this.buildingSlug, false, session.lead_id);
608
+ }
609
+ // If initSession fails, we fall back to the client-generated leadId
610
+ // and fetchToken will use the v1 endpoint (which has channel ownership enforcement)
611
+ }
612
+
592
613
  this.LeadSourceClient.chatId = this.myPubnub.channel;
593
614
  const generatedLeadSource =
594
615
  await this.LeadSourceClient?.generateUserLeadSource({