@iai-lib/any-chat-widget 0.1.0-alpha.40 → 0.1.0-alpha.41
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.
|
@@ -8492,10 +8492,7 @@ async function Fc({
|
|
|
8492
8492
|
await a.createConversation({
|
|
8493
8493
|
contact: u,
|
|
8494
8494
|
attributes: {
|
|
8495
|
-
...d && {
|
|
8496
|
-
gc_id: d,
|
|
8497
|
-
"Chat.gc_id": d
|
|
8498
|
-
},
|
|
8495
|
+
...d && { "Chat.gc_id": d },
|
|
8499
8496
|
Question: l,
|
|
8500
8497
|
"AI Summary": o
|
|
8501
8498
|
}
|
|
@@ -8537,8 +8534,8 @@ async function Fc({
|
|
|
8537
8534
|
});
|
|
8538
8535
|
}
|
|
8539
8536
|
function ka(s, e) {
|
|
8540
|
-
e.on("*", (
|
|
8541
|
-
console.log("event:",
|
|
8537
|
+
e.on("*", (a, o) => {
|
|
8538
|
+
console.log("event:", a, o);
|
|
8542
8539
|
}), e.on("conversationCreated", () => {
|
|
8543
8540
|
s.setInputDisabled(!1), localStorage.setItem(
|
|
8544
8541
|
gn(s.cleanOptions.config.historyKey),
|
|
@@ -8546,85 +8543,85 @@ function ka(s, e) {
|
|
|
8546
8543
|
);
|
|
8547
8544
|
}), e.on(
|
|
8548
8545
|
"conversationAccepted",
|
|
8549
|
-
(
|
|
8546
|
+
(a) => {
|
|
8550
8547
|
s.addMessage({
|
|
8551
8548
|
role: "system",
|
|
8552
|
-
content: `${
|
|
8549
|
+
content: `${a.displayName} has joined the chat`
|
|
8553
8550
|
});
|
|
8554
8551
|
}
|
|
8555
8552
|
), e.on("agentTyping", () => {
|
|
8556
8553
|
s.setTypingIndicatorVisible(!0);
|
|
8557
8554
|
}), e.on(
|
|
8558
8555
|
"agentJoined",
|
|
8559
|
-
(
|
|
8556
|
+
(a) => {
|
|
8560
8557
|
s.addMessage({
|
|
8561
8558
|
role: "system",
|
|
8562
|
-
content: `${
|
|
8559
|
+
content: `${a.displayName} has joined the chat`
|
|
8563
8560
|
});
|
|
8564
8561
|
}
|
|
8565
8562
|
), e.on(
|
|
8566
8563
|
"agentTransferredConversation",
|
|
8567
|
-
(
|
|
8564
|
+
(a) => {
|
|
8568
8565
|
s.addMessage({
|
|
8569
8566
|
role: "system",
|
|
8570
|
-
content: `You have been transferred to ${
|
|
8567
|
+
content: `You have been transferred to ${a.toDisplayName}`
|
|
8571
8568
|
});
|
|
8572
8569
|
}
|
|
8573
8570
|
), e.on(
|
|
8574
8571
|
"conversationTransferredToGroup",
|
|
8575
|
-
(
|
|
8572
|
+
(a) => {
|
|
8576
8573
|
s.addMessage({
|
|
8577
8574
|
role: "system",
|
|
8578
|
-
content: `You have been transferred to ${
|
|
8575
|
+
content: `You have been transferred to ${a.groupName}`
|
|
8579
8576
|
});
|
|
8580
8577
|
}
|
|
8581
8578
|
), e.on(
|
|
8582
8579
|
"agentLeftConversation",
|
|
8583
|
-
(
|
|
8580
|
+
(a) => {
|
|
8584
8581
|
s.addMessage({
|
|
8585
8582
|
role: "system",
|
|
8586
|
-
content: `${
|
|
8583
|
+
content: `${a.displayName} has left the chat`
|
|
8587
8584
|
});
|
|
8588
8585
|
}
|
|
8589
8586
|
), e.on(
|
|
8590
8587
|
"conversationTerminated",
|
|
8591
|
-
(
|
|
8588
|
+
(a) => {
|
|
8592
8589
|
s.addMessage({
|
|
8593
8590
|
role: "system",
|
|
8594
8591
|
content: "The chat has ended"
|
|
8595
8592
|
}), s.setInputDisabled(!0), localStorage.removeItem(gn(s.cleanOptions.config.historyKey));
|
|
8596
8593
|
}
|
|
8597
|
-
), e.on("message", (
|
|
8598
|
-
switch (
|
|
8594
|
+
), e.on("message", (a) => {
|
|
8595
|
+
switch (a.from) {
|
|
8599
8596
|
case "SYSTEM":
|
|
8600
8597
|
s.addMessage({
|
|
8601
8598
|
role: "system",
|
|
8602
|
-
content:
|
|
8599
|
+
content: a.text
|
|
8603
8600
|
});
|
|
8604
8601
|
break;
|
|
8605
8602
|
case "USER":
|
|
8606
8603
|
s.setTypingIndicatorVisible(!1), s.addMessage({
|
|
8607
8604
|
role: "assistant",
|
|
8608
|
-
name:
|
|
8609
|
-
content:
|
|
8605
|
+
name: a.displayName,
|
|
8606
|
+
content: a.text
|
|
8610
8607
|
});
|
|
8611
8608
|
break;
|
|
8612
8609
|
default:
|
|
8613
|
-
console.log("unhandled message:",
|
|
8610
|
+
console.log("unhandled message:", a);
|
|
8614
8611
|
break;
|
|
8615
8612
|
}
|
|
8616
8613
|
}), e.connect();
|
|
8617
|
-
const t = async (
|
|
8618
|
-
|
|
8614
|
+
const t = async (a) => {
|
|
8615
|
+
a.preventDefault(), s.addMessage({
|
|
8619
8616
|
role: "user",
|
|
8620
|
-
content:
|
|
8621
|
-
}), await e.sendMessage(
|
|
8617
|
+
content: a.detail.message
|
|
8618
|
+
}), await e.sendMessage(a.detail.message);
|
|
8622
8619
|
}, n = async () => {
|
|
8623
|
-
console.log("destroyed fired"), e.destroy(), s.removeEventListener("iai-chat-send-user-message", t), s.removeEventListener("iai-chat-reset",
|
|
8624
|
-
}, i = async () => {
|
|
8625
|
-
console.log("reset fired"), await e.terminateConversation(), await n(), localStorage.removeItem(gn(s.cleanOptions.config.historyKey));
|
|
8620
|
+
console.log("destroyed fired"), e.destroy(), s.removeEventListener("iai-chat-send-user-message", t), s.removeEventListener("iai-chat-reset", r), s.removeEventListener("iai-chat-destroy", n);
|
|
8621
|
+
}, i = s.cleanOptions.config.disclaimerMessage, r = async () => {
|
|
8622
|
+
console.log("reset fired"), await e.terminateConversation(), await n(), localStorage.removeItem(gn(s.cleanOptions.config.historyKey)), s.cleanOptions.config.disclaimerMessage = i;
|
|
8626
8623
|
};
|
|
8627
|
-
s.cleanOptions.config.disclaimerMessage = "
|
|
8624
|
+
s.cleanOptions.config.disclaimerMessage = "", s.addEventListener("iai-chat-send-user-message", t), s.addEventListener("iai-chat-reset", r), s.addEventListener("iai-chat-destroy", n);
|
|
8628
8625
|
}
|
|
8629
8626
|
class qc {
|
|
8630
8627
|
constructor(e, t) {
|
|
@@ -516,7 +516,7 @@ Please report this to https://github.com/markedjs/marked.`,s){const n="<p>An err
|
|
|
516
516
|
</div>
|
|
517
517
|
`)}
|
|
518
518
|
</iai-chat-carousel>
|
|
519
|
-
`}function Pc(s){return async function({id:t,params:n,chatWindow:i}){i.setInputDisabled(!0);const r={...n.guestCardId&&{guestCardId:n.guestCardId},...n.customerFirstName&&{firstName:n.customerFirstName},...n.customerLastName&&{lastName:n.customerLastName},...n.customerEmail&&{email:n.customerEmail},...n.customerPhoneNumber&&{phone:n.customerPhoneNumber},...n.desiredMoveInDate&&{moveInDate:n.desiredMoveInDate}},a=document.createElement("iai-chat-iframe-modal");a.title="Schedule a Tour",a.src=`${s}?${new URLSearchParams(r).toString()}`,a.showHeader=!1;const o=()=>{a.remove(),window.removeEventListener("beforeunload",u),i.setInputDisabled(!1)},l=async({detail:h})=>{if(h.type!=="tourScheduled")return;const{tourType:c,tourDate:f,tourTime:A,guestCardId:V}=h;o(),i.addMessage({role:"system",content:"Your tour has been scheduled!"}),await i.sendFunctionCallResponse(t,{status:"scheduled",tourType:c,tourDate:f,tourTime:A,guestCardId:V},!0)},d=async()=>{o(),i.addMessage({role:"system",content:"Tour Scheduler Closed"}),await i.sendFunctionCallResponse(t,{status:"canceled"},!0)},u=async()=>{o(),i.addMessage({role:"system",content:"Tour Scheduler Closed"})};a.addEventListener("message-received",l),a.addEventListener("close",d),window.addEventListener("beforeunload",u),document.body.appendChild(a),i.addMessage({role:"system",content:"Tour Scheduler Opened"})}}function ba(s){return{all:s=s||new Map,on:function(e,t){var n=s.get(e);n?n.push(t):s.set(e,[t])},off:function(e,t){var n=s.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):s.set(e,[]))},emit:function(e,t){var n=s.get(e);n&&n.slice().map(function(i){i(t)}),(n=s.get("*"))&&n.slice().map(function(i){i(e,t)})}}}class jc{constructor(e){this.chatWsUrl=e,this._emitter=ba(),this.on=this._emitter.on.bind(this._emitter),this.off=this._emitter.off.bind(this._emitter),this.reconnectCodes=new Set([1006]),this.reconnectAttempts=0,this.maxReconnectAttempts=10}connect(){const e=new WebSocket(this.chatWsUrl);e.onopen=async()=>{this.reconnectAttempts=0,e.send(JSON.stringify({type:"ready"}))},e.onmessage=t=>{const n=JSON.parse(t.data);this._emitter.emit(n.type,n.data)},e.onclose=t=>{console.log("Disconnected: ",t.code,t.reason||"No reason provided"),this._emitter.emit("disconnected",t),this.reconnectCodes.has(t.code)&&this.reconnectAttempts<this.maxReconnectAttempts&&(console.log("Reconnecting..."),this._emitter.emit("reconnecting"),this.reconnectAttempts++,setTimeout(()=>this.connect(),this.reconnectAttempts*1e3))},e.onerror=t=>{console.log("Error:",t),this._emitter.emit("error",t)},this.ws=e}reconnect(){this.reconnectAttempts=0,this.connect()}disconnect(){var e;(e=this.ws)==null||e.close()}destroy(){this.disconnect(),this._emitter.all.clear()}}var Ms;(s=>{(e=>{e.TEXT="TEXT"})(s.MessageType||(s.MessageType={})),(e=>{e.DELIVERED="DELIVERED",e.READ="READ",e.FAILED="FAILED"})(s.AcknowledgeType||(s.AcknowledgeType={})),(e=>{e.GENERIC="GENERIC",e.SMS="SMS",e.RCS="RCS",e.FACEBOOK="FACEBOOK",e.TWITTER="TWITTER",e.WHATSAPP="WHATSAPP",e.WECHAT="WECHAT",e.QQMOBILE="QQMOBILE",e.APPLE_BUSINESS_CHAT="APPLE_BUSINESS_CHAT",e.SKYPE="SKYPE",e.SNAPCHAT="SNAPCHAT",e.VIBER="VIBER",e.LINE="LINE",e.TELEGRAM="TELEGRAM",e.KAKAO="KAKAO"})(s.ContentType||(s.ContentType={})),(e=>{e.SYSTEM="SYSTEM",e.USER="USER"})(s.ConversationEventOrigin||(s.ConversationEventOrigin={})),(e=>{e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.TERMINATED="TERMINATED"})(s.ConversationStatus||(s.ConversationStatus={}))})(Ms||(Ms={}));const zc=Ms.AcknowledgeType,Dc="Anyone Home",Lc="IB Chat Leasing - Development";let Zc="https://five9.ah.inhabit.work";const Hc="https://five9.ah.inhabit.work".replace("http","ws").replace(/\/$/,""),Vn=class Vn{constructor(){Ei(this,Ke,void 0);Ei(this,zt,void 0);this._emitter=ba(),this.on=this._emitter.on.bind(this._emitter),this.off=this._emitter.off.bind(this._emitter),ut(this,Ke,null),ut(this,zt,null),this.conversationStarted=!1}serialize(){return JSON.stringify({sessionToken:this.sessionToken,conversationId:this.conversationId,conversationStarted:this.conversationStarted})}static deserialize(e){const t=JSON.parse(e),n=new Vn;return t.sessionToken&&n.setSession(t.sessionToken),t.conversationId&&n.setConversationId(t.conversationId),n.conversationStarted=t.conversationStarted||!1,n}static generateBaseUrl(e){return`https://${e}/appsvcs/rs/svc`}async createSession(){const e=await fetch(`${Vn.generateBaseUrl("app-scl.five9.com")}/auth/anon?cookieless=true`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({tenantName:Dc})});return ut(this,Ke,await e.json()),Ps(this,Ke)}setSession(e){ut(this,Ke,e)}setConversationId(e){ut(this,zt,e),this.five9WebSocket&&(this.five9WebSocket.destroy(),this.five9WebSocket=void 0,e&&this.connectToWebSocket())}connect(){if(!this.sessionToken)throw new Error("Session not created");if(!this.conversationId)throw new Error("Conversation not started");this.connectToWebSocket()}connectToWebSocket(){if(!this.conversationId)throw new Error("Conversation not started");this.five9WebSocket&&this.five9WebSocket.destroy();const e=new jc(`${Hc}/conversations/${this.conversationId}/ws`);e.on("*",(t,n)=>{this._emitter.emit(t,n)}),e.on("conversationCreated",t=>{this.conversationStarted=!0,console.log("Conversation Created:",t)}),e.on("conversationAccepted",t=>{console.log("Conversation Accepted:",t)}),e.on("agentJoined",t=>{console.log("Agent Joined:",t)}),e.on("agentTransferredConversation",t=>{console.log("Agent Transferred Conversation:",t)}),e.on("conversationTransferredToGroup",t=>{console.log("Conversation Transferred To Group:",t)}),e.on("agentLeftConversation",t=>{console.log("Agent Left Conversation:",t)}),e.on("agentTyping",t=>{console.log("Agent Typing:",t)}),e.on("message",async t=>{console.log("Message:",t),await this.acknowledgeMessage({messages:[{messageId:t.messageId,type:zc.READ}]})}),e.on("conversationTerminated",t=>{console.log("Conversation Terminated:",t)}),e.on("error",t=>{console.log("Error:",t)}),this.five9WebSocket=e,e.connect()}async authenticatedFetch(e,t={}){const{sessionToken:n}=this;if(!n)throw new Error("Session not found");e=e.startsWith("/")?e:`/${e}`;const i=n.metadata.dataCenters[0].apiUrls[0].host,r=await fetch(`${Vn.generateBaseUrl(i)}${e}`,{...t,headers:{...t.headers,"Content-Type":"application/json",Accept:"application/json",Authorization:n.tokenId,farmId:n.context.farmId}});return r.status===204?null:r.json()}async getMetadata(){if(!this.sessionToken)throw new Error("Session not created");return this.authenticatedFetch("/auth/metadata",{method:"GET"})}async createConversation(e){if(!this.sessionToken)throw new Error("Session not created");const t=e.contact||{};Object.keys(t).forEach(r=>{const a=r;t[a]||delete t[a]});const n={...e,campaignName:Lc,tenantId:this.tenantId,callbackUrl:Zc};console.log("body",n);const i=await this.authenticatedFetch("/conversations",{method:"POST",body:JSON.stringify(n)});return this.setConversationId(i.id),i}async sendMessage(e){const{conversationId:t,conversationStarted:n}=this;if(!t||!n)throw new Error("Conversation not started");const i={messageType:Ms.MessageType.TEXT,message:e};await this.authenticatedFetch(`/conversations/${t}/messages`,{method:"POST",body:JSON.stringify(i)})}async sendTyping(){const{conversationId:e}=this;if(!e)throw new Error("Conversation not started");await this.authenticatedFetch(`/conversations/${e}/messages/typing`,{method:"PUT"})}async acknowledgeMessage(e){const{conversationId:t}=this;if(!t)throw new Error("Conversation not started");await this.authenticatedFetch(`/conversations/${t}/messages/acknowledge`,{method:"PUT",body:JSON.stringify(e)})}async terminateConversation(){const{conversationId:e}=this;if(!e)throw new Error("Conversation not started");await this.authenticatedFetch(`/conversations/${e}/terminate`,{method:"POST"}),this.destroy()}destroy(){this.five9WebSocket&&this.five9WebSocket.destroy(),ut(this,Ke,null),ut(this,zt,null)}get sessionToken(){return Ps(this,Ke)}get conversationId(){return Ps(this,zt)}get dataCenter(){var e;return(e=this.sessionToken)==null?void 0:e.metadata.dataCenters[0]}get apiUrl(){var e;return(e=this.dataCenter)==null?void 0:e.apiUrls[0].host}get tenantId(){var e;return(e=this.sessionToken)==null?void 0:e.orgId}get tokenId(){var e;return(e=this.sessionToken)==null?void 0:e.tokenId}get farmId(){var e;return(e=this.sessionToken)==null?void 0:e.context.farmId}};Ke=new WeakMap,zt=new WeakMap;let Ns=Vn;function Wn(s){return`any-${s||"main"}-chatSession`}async function Uc({id:s,params:e,chatWindow:t,html:n}){t=t;const i=async()=>{t.removeMessage("transferMessageId"),await t.sendFunctionCallResponse(s,{transfer:"Declined"},!0),t.setInputDisabled(!1)},r=async()=>{t.setInputDisabled(!0),t.removeMessage("transferMessageId"),t.addMessage({role:"system",content:"Please wait while we connect you to a live agent"}),await t.chatManager.endChat("Transferred to live agent",!1);const a=new Ns;await a.createSession();const{summary:o,subject:l,guestCardId:d,...u}=e;await a.createConversation({contact:u,attributes:{...d&&{
|
|
519
|
+
`}function Pc(s){return async function({id:t,params:n,chatWindow:i}){i.setInputDisabled(!0);const r={...n.guestCardId&&{guestCardId:n.guestCardId},...n.customerFirstName&&{firstName:n.customerFirstName},...n.customerLastName&&{lastName:n.customerLastName},...n.customerEmail&&{email:n.customerEmail},...n.customerPhoneNumber&&{phone:n.customerPhoneNumber},...n.desiredMoveInDate&&{moveInDate:n.desiredMoveInDate}},a=document.createElement("iai-chat-iframe-modal");a.title="Schedule a Tour",a.src=`${s}?${new URLSearchParams(r).toString()}`,a.showHeader=!1;const o=()=>{a.remove(),window.removeEventListener("beforeunload",u),i.setInputDisabled(!1)},l=async({detail:h})=>{if(h.type!=="tourScheduled")return;const{tourType:c,tourDate:f,tourTime:A,guestCardId:V}=h;o(),i.addMessage({role:"system",content:"Your tour has been scheduled!"}),await i.sendFunctionCallResponse(t,{status:"scheduled",tourType:c,tourDate:f,tourTime:A,guestCardId:V},!0)},d=async()=>{o(),i.addMessage({role:"system",content:"Tour Scheduler Closed"}),await i.sendFunctionCallResponse(t,{status:"canceled"},!0)},u=async()=>{o(),i.addMessage({role:"system",content:"Tour Scheduler Closed"})};a.addEventListener("message-received",l),a.addEventListener("close",d),window.addEventListener("beforeunload",u),document.body.appendChild(a),i.addMessage({role:"system",content:"Tour Scheduler Opened"})}}function ba(s){return{all:s=s||new Map,on:function(e,t){var n=s.get(e);n?n.push(t):s.set(e,[t])},off:function(e,t){var n=s.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):s.set(e,[]))},emit:function(e,t){var n=s.get(e);n&&n.slice().map(function(i){i(t)}),(n=s.get("*"))&&n.slice().map(function(i){i(e,t)})}}}class jc{constructor(e){this.chatWsUrl=e,this._emitter=ba(),this.on=this._emitter.on.bind(this._emitter),this.off=this._emitter.off.bind(this._emitter),this.reconnectCodes=new Set([1006]),this.reconnectAttempts=0,this.maxReconnectAttempts=10}connect(){const e=new WebSocket(this.chatWsUrl);e.onopen=async()=>{this.reconnectAttempts=0,e.send(JSON.stringify({type:"ready"}))},e.onmessage=t=>{const n=JSON.parse(t.data);this._emitter.emit(n.type,n.data)},e.onclose=t=>{console.log("Disconnected: ",t.code,t.reason||"No reason provided"),this._emitter.emit("disconnected",t),this.reconnectCodes.has(t.code)&&this.reconnectAttempts<this.maxReconnectAttempts&&(console.log("Reconnecting..."),this._emitter.emit("reconnecting"),this.reconnectAttempts++,setTimeout(()=>this.connect(),this.reconnectAttempts*1e3))},e.onerror=t=>{console.log("Error:",t),this._emitter.emit("error",t)},this.ws=e}reconnect(){this.reconnectAttempts=0,this.connect()}disconnect(){var e;(e=this.ws)==null||e.close()}destroy(){this.disconnect(),this._emitter.all.clear()}}var Ms;(s=>{(e=>{e.TEXT="TEXT"})(s.MessageType||(s.MessageType={})),(e=>{e.DELIVERED="DELIVERED",e.READ="READ",e.FAILED="FAILED"})(s.AcknowledgeType||(s.AcknowledgeType={})),(e=>{e.GENERIC="GENERIC",e.SMS="SMS",e.RCS="RCS",e.FACEBOOK="FACEBOOK",e.TWITTER="TWITTER",e.WHATSAPP="WHATSAPP",e.WECHAT="WECHAT",e.QQMOBILE="QQMOBILE",e.APPLE_BUSINESS_CHAT="APPLE_BUSINESS_CHAT",e.SKYPE="SKYPE",e.SNAPCHAT="SNAPCHAT",e.VIBER="VIBER",e.LINE="LINE",e.TELEGRAM="TELEGRAM",e.KAKAO="KAKAO"})(s.ContentType||(s.ContentType={})),(e=>{e.SYSTEM="SYSTEM",e.USER="USER"})(s.ConversationEventOrigin||(s.ConversationEventOrigin={})),(e=>{e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.TERMINATED="TERMINATED"})(s.ConversationStatus||(s.ConversationStatus={}))})(Ms||(Ms={}));const zc=Ms.AcknowledgeType,Dc="Anyone Home",Lc="IB Chat Leasing - Development";let Zc="https://five9.ah.inhabit.work";const Hc="https://five9.ah.inhabit.work".replace("http","ws").replace(/\/$/,""),Vn=class Vn{constructor(){Ei(this,Ke,void 0);Ei(this,zt,void 0);this._emitter=ba(),this.on=this._emitter.on.bind(this._emitter),this.off=this._emitter.off.bind(this._emitter),ut(this,Ke,null),ut(this,zt,null),this.conversationStarted=!1}serialize(){return JSON.stringify({sessionToken:this.sessionToken,conversationId:this.conversationId,conversationStarted:this.conversationStarted})}static deserialize(e){const t=JSON.parse(e),n=new Vn;return t.sessionToken&&n.setSession(t.sessionToken),t.conversationId&&n.setConversationId(t.conversationId),n.conversationStarted=t.conversationStarted||!1,n}static generateBaseUrl(e){return`https://${e}/appsvcs/rs/svc`}async createSession(){const e=await fetch(`${Vn.generateBaseUrl("app-scl.five9.com")}/auth/anon?cookieless=true`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({tenantName:Dc})});return ut(this,Ke,await e.json()),Ps(this,Ke)}setSession(e){ut(this,Ke,e)}setConversationId(e){ut(this,zt,e),this.five9WebSocket&&(this.five9WebSocket.destroy(),this.five9WebSocket=void 0,e&&this.connectToWebSocket())}connect(){if(!this.sessionToken)throw new Error("Session not created");if(!this.conversationId)throw new Error("Conversation not started");this.connectToWebSocket()}connectToWebSocket(){if(!this.conversationId)throw new Error("Conversation not started");this.five9WebSocket&&this.five9WebSocket.destroy();const e=new jc(`${Hc}/conversations/${this.conversationId}/ws`);e.on("*",(t,n)=>{this._emitter.emit(t,n)}),e.on("conversationCreated",t=>{this.conversationStarted=!0,console.log("Conversation Created:",t)}),e.on("conversationAccepted",t=>{console.log("Conversation Accepted:",t)}),e.on("agentJoined",t=>{console.log("Agent Joined:",t)}),e.on("agentTransferredConversation",t=>{console.log("Agent Transferred Conversation:",t)}),e.on("conversationTransferredToGroup",t=>{console.log("Conversation Transferred To Group:",t)}),e.on("agentLeftConversation",t=>{console.log("Agent Left Conversation:",t)}),e.on("agentTyping",t=>{console.log("Agent Typing:",t)}),e.on("message",async t=>{console.log("Message:",t),await this.acknowledgeMessage({messages:[{messageId:t.messageId,type:zc.READ}]})}),e.on("conversationTerminated",t=>{console.log("Conversation Terminated:",t)}),e.on("error",t=>{console.log("Error:",t)}),this.five9WebSocket=e,e.connect()}async authenticatedFetch(e,t={}){const{sessionToken:n}=this;if(!n)throw new Error("Session not found");e=e.startsWith("/")?e:`/${e}`;const i=n.metadata.dataCenters[0].apiUrls[0].host,r=await fetch(`${Vn.generateBaseUrl(i)}${e}`,{...t,headers:{...t.headers,"Content-Type":"application/json",Accept:"application/json",Authorization:n.tokenId,farmId:n.context.farmId}});return r.status===204?null:r.json()}async getMetadata(){if(!this.sessionToken)throw new Error("Session not created");return this.authenticatedFetch("/auth/metadata",{method:"GET"})}async createConversation(e){if(!this.sessionToken)throw new Error("Session not created");const t=e.contact||{};Object.keys(t).forEach(r=>{const a=r;t[a]||delete t[a]});const n={...e,campaignName:Lc,tenantId:this.tenantId,callbackUrl:Zc};console.log("body",n);const i=await this.authenticatedFetch("/conversations",{method:"POST",body:JSON.stringify(n)});return this.setConversationId(i.id),i}async sendMessage(e){const{conversationId:t,conversationStarted:n}=this;if(!t||!n)throw new Error("Conversation not started");const i={messageType:Ms.MessageType.TEXT,message:e};await this.authenticatedFetch(`/conversations/${t}/messages`,{method:"POST",body:JSON.stringify(i)})}async sendTyping(){const{conversationId:e}=this;if(!e)throw new Error("Conversation not started");await this.authenticatedFetch(`/conversations/${e}/messages/typing`,{method:"PUT"})}async acknowledgeMessage(e){const{conversationId:t}=this;if(!t)throw new Error("Conversation not started");await this.authenticatedFetch(`/conversations/${t}/messages/acknowledge`,{method:"PUT",body:JSON.stringify(e)})}async terminateConversation(){const{conversationId:e}=this;if(!e)throw new Error("Conversation not started");await this.authenticatedFetch(`/conversations/${e}/terminate`,{method:"POST"}),this.destroy()}destroy(){this.five9WebSocket&&this.five9WebSocket.destroy(),ut(this,Ke,null),ut(this,zt,null)}get sessionToken(){return Ps(this,Ke)}get conversationId(){return Ps(this,zt)}get dataCenter(){var e;return(e=this.sessionToken)==null?void 0:e.metadata.dataCenters[0]}get apiUrl(){var e;return(e=this.dataCenter)==null?void 0:e.apiUrls[0].host}get tenantId(){var e;return(e=this.sessionToken)==null?void 0:e.orgId}get tokenId(){var e;return(e=this.sessionToken)==null?void 0:e.tokenId}get farmId(){var e;return(e=this.sessionToken)==null?void 0:e.context.farmId}};Ke=new WeakMap,zt=new WeakMap;let Ns=Vn;function Wn(s){return`any-${s||"main"}-chatSession`}async function Uc({id:s,params:e,chatWindow:t,html:n}){t=t;const i=async()=>{t.removeMessage("transferMessageId"),await t.sendFunctionCallResponse(s,{transfer:"Declined"},!0),t.setInputDisabled(!1)},r=async()=>{t.setInputDisabled(!0),t.removeMessage("transferMessageId"),t.addMessage({role:"system",content:"Please wait while we connect you to a live agent"}),await t.chatManager.endChat("Transferred to live agent",!1);const a=new Ns;await a.createSession();const{summary:o,subject:l,guestCardId:d,...u}=e;await a.createConversation({contact:u,attributes:{...d&&{"Chat.gc_id":d},Question:l,"AI Summary":o}}),localStorage.setItem(Wn(t.cleanOptions.config.historyKey),a.serialize()),wa(t,a)};t.addMessage({id:"transferMessageId",role:"system",contentHtmlTemplate:n`
|
|
520
520
|
<style>
|
|
521
521
|
.btn {
|
|
522
522
|
background-color: var(--iai-chat-i-message-user-bg);
|
|
@@ -544,4 +544,4 @@ Please report this to https://github.com/markedjs/marked.`,s){const n="<p>An err
|
|
|
544
544
|
<button class="btn btn-no" @click=${i}>No</button>
|
|
545
545
|
</div>
|
|
546
546
|
</div>
|
|
547
|
-
`})}function wa(s,e){e.on("*",(
|
|
547
|
+
`})}function wa(s,e){e.on("*",(a,o)=>{console.log("event:",a,o)}),e.on("conversationCreated",()=>{s.setInputDisabled(!1),localStorage.setItem(Wn(s.cleanOptions.config.historyKey),e.serialize())}),e.on("conversationAccepted",a=>{s.addMessage({role:"system",content:`${a.displayName} has joined the chat`})}),e.on("agentTyping",()=>{s.setTypingIndicatorVisible(!0)}),e.on("agentJoined",a=>{s.addMessage({role:"system",content:`${a.displayName} has joined the chat`})}),e.on("agentTransferredConversation",a=>{s.addMessage({role:"system",content:`You have been transferred to ${a.toDisplayName}`})}),e.on("conversationTransferredToGroup",a=>{s.addMessage({role:"system",content:`You have been transferred to ${a.groupName}`})}),e.on("agentLeftConversation",a=>{s.addMessage({role:"system",content:`${a.displayName} has left the chat`})}),e.on("conversationTerminated",a=>{s.addMessage({role:"system",content:"The chat has ended"}),s.setInputDisabled(!0),localStorage.removeItem(Wn(s.cleanOptions.config.historyKey))}),e.on("message",a=>{switch(a.from){case"SYSTEM":s.addMessage({role:"system",content:a.text});break;case"USER":s.setTypingIndicatorVisible(!1),s.addMessage({role:"assistant",name:a.displayName,content:a.text});break;default:console.log("unhandled message:",a);break}}),e.connect();const t=async a=>{a.preventDefault(),s.addMessage({role:"user",content:a.detail.message}),await e.sendMessage(a.detail.message)},n=async()=>{console.log("destroyed fired"),e.destroy(),s.removeEventListener("iai-chat-send-user-message",t),s.removeEventListener("iai-chat-reset",r),s.removeEventListener("iai-chat-destroy",n)},i=s.cleanOptions.config.disclaimerMessage,r=async()=>{console.log("reset fired"),await e.terminateConversation(),await n(),localStorage.removeItem(Wn(s.cleanOptions.config.historyKey)),s.cleanOptions.config.disclaimerMessage=i};s.cleanOptions.config.disclaimerMessage="",s.addEventListener("iai-chat-send-user-message",t),s.addEventListener("iai-chat-reset",r),s.addEventListener("iai-chat-destroy",n)}class Bc{constructor(e,t){const n=ws.parse({assistantId:"7e59c8c1-a4ff-40f1-9a68-86ea294a4e75",...e,config:{...e.config,styles:e.styles||{}}});n.handlers.functionCalls.transferToLiveAgent=Uc,n.handlers.functionCalls.showScheduleTourWidget=Pc(t.schedulerUrl),n.handlers.enhancedContent.unitList=Rc,this.chatWidget=new Nc(n);const i=localStorage.getItem(Wn(n.config.historyKey));if(i){const r=Ns.deserialize(i);setTimeout(()=>{wa(this.chatWidget.api.chatWindow,r)},0)}}destroy(){this.chatWidget.destroy()}}ie.AnyChatWidget=Bc,Object.defineProperty(ie,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iai-lib/any-chat-widget",
|
|
3
3
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
4
|
-
"version": "0.1.0-alpha.
|
|
4
|
+
"version": "0.1.0-alpha.41",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
7
7
|
},
|
|
@@ -37,5 +37,5 @@
|
|
|
37
37
|
"@iai-lib/chat-widget": "^1.0.0-alpha.41",
|
|
38
38
|
"mitt": "^3.0.1"
|
|
39
39
|
},
|
|
40
|
-
"gitHead": "
|
|
40
|
+
"gitHead": "1046931f493f870e1a349f82250875863c1e3750"
|
|
41
41
|
}
|