captivate-chat-api
Version:
This is a wrapper for captivate chat api socket custom channel
1 lines • 11.1 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.CaptivateChatAPI=t():e.CaptivateChatAPI=t()}(this,(()=>(()=>{"use strict";var e={86:function(e,t,s){var n=this&&this.__awaiter||function(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CaptivateChatAPI=void 0;const o=s(52);let i;if("undefined"!=typeof window&&window.WebSocket)i=window.WebSocket;else if(void 0!==s.g&&s.g.WebSocket)i=s.g.WebSocket;else try{i=s(591)}catch(e){throw new Error("WebSocket not available in this environment and ws module could not be loaded")}t.CaptivateChatAPI=class{constructor(e,t="prod"){this.apiKey=e,this.mode=t,this.url="prod"===this.mode?`wss://channel.wss.captivatechat.ai/dev?apiKey=${e}`:`wss://channel-dev.wss.captivatechat.ai/dev?apiKey=${e}`,this.socket=null,this.conversations=new Map}_send(e){this.socket&&this.socket.readyState===i.OPEN?this.socket.send(JSON.stringify(e)):console.error("Socket is not open. Message not sent:",e)}connect(){return n(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{try{this.socket=new i(this.url);const s=setTimeout((()=>{t(new Error("Connection timeout: socket_connected not received"))}),1e4);this.socket.onopen=()=>{console.log("WebSocket connected, waiting for API confirmation...")},this.socket.onmessage=t=>{var n;try{"socket_connected"===(null===(n=JSON.parse(t.data.toString()).event)||void 0===n?void 0:n.event_type)&&(console.log("API Successfully Connected"),clearTimeout(s),e())}catch(e){console.error("Error parsing message:",e)}},this.socket.onerror=e=>{console.error("WebSocket Error:",e.message||e),clearTimeout(s),t(new Error(e.message||"WebSocket error"))},this.socket.onclose=e=>{console.log("WebSocket connection closed with"),1e3!==e.code&&(console.log("Attempting to reconnect..."),setTimeout((()=>this.connect()),3e3))}}catch(e){t(e)}}))}))}createConversation(e){return n(this,arguments,void 0,(function*(e,t={},s={},n="bot-first"){return new Promise(((i,r)=>{var a;try{this._send({action:"sendMessage",event:{event_type:"conversation_start",event_payload:{userId:e,userBasicInfo:t,metadata:s}}});const c=e=>{var t,s;try{const a=JSON.parse(e.data.toString());if("conversation_start_success"===(null===(t=a.event)||void 0===t?void 0:t.event_type)){const e=a.event.event_payload.conversation_id;null===(s=this.socket)||void 0===s||s.removeEventListener("message",c);const t=new o.Conversation(e,this.socket);this.conversations.set(e,t),"bot-first"===n?t.sendMessage({type:"text",text:""}).then((()=>i(t))).catch(r):i(t)}}catch(e){console.error("Error processing message:",e)}};null===(a=this.socket)||void 0===a||a.addEventListener("message",c),setTimeout((()=>{var e;null===(e=this.socket)||void 0===e||e.removeEventListener("message",c),r(new Error("Timeout: No response for createConversation"))}),1e4)}catch(e){r(e)}}))}))}getConversation(e){let t=this.conversations.get(e);if(!t){if(null===this.socket)throw console.error("Socket is not initialized"),new Error("WebSocket connection not established");t=new o.Conversation(e,this.socket),this.conversations.set(e,t)}return null==t||t.restartListeners(),t}getUserConversations(e){return n(this,void 0,void 0,(function*(){const t=[];return new Promise(((s,n)=>{var i;try{this._send({action:"sendMessage",event:{event_type:"get_user_conversations",event_payload:{userId:e}}});const r=e=>{var i,a;try{const n=JSON.parse(e.data.toString());if("user_conversations"===(null===(i=n.event)||void 0===i?void 0:i.event_type)){null===(a=this.socket)||void 0===a||a.removeEventListener("message",r);const e=n.event.event_payload.conversations;for(const s of e){const{conversation_id:e,metadata:n}=s;null!==this.socket&&t.push(new o.Conversation(e,this.socket,n))}s(t)}}catch(e){console.error("Error processing message:",e),n(e)}};null===(i=this.socket)||void 0===i||i.addEventListener("message",r),setTimeout((()=>{var e;null===(e=this.socket)||void 0===e||e.removeEventListener("message",r),n(new Error("Timeout: No response for getUserConversations"))}),1e4)}catch(e){n(e)}}))}))}deleteUserConversations(e){return n(this,void 0,void 0,(function*(){return new Promise(((t,s)=>{var n;if(!e)return s(new Error("User ID must be provided."));try{this._send({action:"sendMessage",event:{event_type:"delete_conversation",event_payload:{userId:e}}});const o=n=>{var i,r;try{const s=JSON.parse(n.data.toString());"delete_conversation_success"===(null===(i=s.event)||void 0===i?void 0:i.event_type)&&s.event.event_payload.userId===e&&(null===(r=this.socket)||void 0===r||r.removeEventListener("message",o),t())}catch(e){s(e)}};null===(n=this.socket)||void 0===n||n.addEventListener("message",o),setTimeout((()=>{var t;null===(t=this.socket)||void 0===t||t.removeEventListener("message",o),s(new Error(`Timeout: No response for deleting conversations for user ${e}`))}),1e4)}catch(e){s(e)}}))}))}}},52:function(e,t){var s=this&&this.__awaiter||function(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Conversation=void 0,t.Conversation=class{constructor(e,t,s){this.conversationId=e,this.socket=t,this.listeners=new Map,this.metadata=s||null,this.local_id=Math.floor(1e4*Math.random()),this.socket.onmessage=this.handleMessage.bind(this)}handleMessage(e){var t,s;const n=JSON.parse(e.data),o=null===(t=n.event)||void 0===t?void 0:t.event_type;if(o&&this.listeners.has(o)){const e=n.event.event_payload;null===(s=this.listeners.get(o))||void 0===s||s.forEach((t=>t(e)))}}restartListeners(){this.socket.onmessage=this.handleMessage.bind(this)}addListener(e,t){var s;this.restartListeners(),this.listeners.has(e)||this.listeners.set(e,[]),null===(s=this.listeners.get(e))||void 0===s||s.push(t)}onMessage(e){this.addListener("bot_message",(t=>e(t.content,"ai_agent"))),this.addListener("livechat_message",(t=>e(t.content,"human_agent")))}onActionReceived(e){this.addListener("action",(t=>e(t.actions)))}onConversationUpdate(e){this.addListener("conversation_update",(t=>{e({type:t.type,conversationId:t.conversation_id,data:t.data})}))}onError(e){this.addListener("general_error",(t=>{e({conversationId:t.conversation_id,errorCode:t.error_code,errorDesc:t.error_desc})}))}sendMessage(e){return s(this,void 0,void 0,(function*(){return"string"==typeof e&&(e={type:"text",text:e}),this.sendPayload("user_message",{type:"message_create",client_msg_id:`unique-message-id-${Date.now()}`,conversation_id:this.conversationId,content:e})}))}setMetadata(e){return s(this,void 0,void 0,(function*(){if("object"!=typeof e||null===e)throw new Error("Metadata must be a non-null object.");return new Promise(((t,s)=>{const n={action:"sendMessage",event:{event_type:"metadata",event_payload:{metadata:e,client_msg_id:`metadata-${Date.now()}`,conversation_id:this.conversationId}}};this.socket.send(JSON.stringify(n));const o=e=>{e.conversation_id===this.conversationId&&(this.removeListener("metadata_update_success",o),t(e))};this.addListener("metadata_update_success",o),setTimeout((()=>{this.removeListener("metadata_update_success",o),s(new Error("Timeout: No response for metadata update"))}),15e3)}))}))}sendAction(e){return s(this,arguments,void 0,(function*(e,t={}){return this.sendPayload("action",{type:"normal",id:e,data:t,conversation_id:this.conversationId})}))}getTranscript(){return s(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s={action:"sendMessage",event:{event_type:"conversation_transcript_request",event_payload:{conversation_id:this.conversationId}}};this.socket.send(JSON.stringify(s));const n=t=>{t.conversation_id===this.conversationId&&(this.removeListener("conversation_transcript",n),e(t.transcript))};this.addListener("conversation_transcript",n),setTimeout((()=>{this.removeListener("conversation_transcript",n),t(new Error("Timeout: No response for transcript request"))}),1e4)}))}))}getMetadata(){return s(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s={action:"sendMessage",event:{event_type:"metadata_request",event_payload:{conversation_id:this.conversationId}}};this.socket.send(JSON.stringify(s));const n=t=>{t.conversation_id===this.conversationId&&(this.removeListener("conversation_metadata",n),e(t.content))};this.addListener("conversation_metadata",n),setTimeout((()=>{this.removeListener("conversation_metadata",n),t(new Error("Timeout: No response for metadata request"))}),1e4)}))}))}delete(){return s(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{try{const s={action:"sendMessage",event:{event_type:"delete_conversation",event_payload:{conversation_id:this.conversationId}}};this.socket.send(JSON.stringify(s));const n=t=>{var s;const o=JSON.parse(t.data);"delete_conversation_success"===(null===(s=o.event)||void 0===s?void 0:s.event_type)&&o.event.event_payload.conversation_id===this.conversationId&&(this.socket.removeEventListener("message",n),e())};this.socket.addEventListener("message",n),setTimeout((()=>{this.socket.removeEventListener("message",n),t(new Error(`Timeout: No response for deleting conversation ${this.conversationId}`))}),1e4)}catch(e){t(e)}}))}))}editMessage(e,t){return s(this,void 0,void 0,(function*(){return"string"==typeof t&&(t={type:"text",text:t}),new Promise(((s,n)=>{this.sendPayload("edit_message",{type:"message_create",client_msg_id:`edit-message-id-${Date.now()}`,conversation_id:this.conversationId,message_id:e,content:t});const o=t=>{console.log(t),t.conversation_id===this.conversationId&&t.message_id===e&&(this.removeListener("message_edited_success",o),s())};this.addListener("message_edited_success",o),setTimeout((()=>{this.removeListener("message_edited_success",o),n(new Error("Timeout: No response for message edit"))}),1e4)}))}))}sendPayload(e,t){return s(this,void 0,void 0,(function*(){return new Promise(((s,n)=>{try{const n={action:"sendMessage",event:{event_type:e,event_payload:t}};this.socket.send(JSON.stringify(n)),s()}catch(e){n(e)}}))}))}removeListener(e,t){const s=this.listeners.get(e);s&&this.listeners.set(e,s.filter((e=>e!==t)))}getConversationId(){return this.conversationId}}},591:e=>{e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}},t={};function s(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,s),i.exports}s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var n={};return(()=>{var e=n;const t=s(86);e.default=t.CaptivateChatAPI})(),n.default})()));