@aikaara/chat-sdk 0.1.1 → 0.1.3
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.
- package/dist/cdn/aikaara-chat.iife.js +2 -2
- package/dist/{headless-DRPEUzcS.mjs → headless-CXRux2Q-.mjs} +2 -2
- package/dist/{headless-B4uSGJMp.cjs → headless-DDmLD-ag.cjs} +1 -1
- package/dist/headless.cjs +1 -1
- package/dist/headless.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/ui.cjs +3 -3
- package/dist/ui.d.ts +1 -0
- package/dist/ui.mjs +10 -7
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o,h,g)=>h in o?te(o,h,{enumerable:!0,configurable:!0,writable:!0,value:g}):o[h]=g;var a=(o,h,g)=>se(o,typeof h!="symbol"?h+"":h,g);class h{constructor(t,e){a(this,"identifier");a(this,"callbacks",{});a(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class g{constructor(t){a(this,"ws",null);a(this,"url");a(this,"subscriptions",new Map);a(this,"welcomePromise",null);a(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var i;const s=new Error("WebSocket connection error");(i=this.welcomePromise)==null||i.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new h(e,i=>{this.send({command:"message",identifier:e,data:JSON.stringify(i)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((i,n)=>{this.pendingSubscriptions.set(s,{resolve:()=>i(e),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),n(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyConnected();const c=this.pendingSubscriptions.get(i);c&&(c.resolve(),this.pendingSubscriptions.delete(i));break}case"reject_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyRejected(),this.subscriptions.delete(i);const c=this.pendingSubscriptions.get(i);c&&(c.reject(new Error(`Subscription rejected: ${i}`)),this.pendingSubscriptions.delete(i));break}case"disconnect":this.subscriptions.forEach(i=>i._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const i=this.subscriptions.get(e.identifier);i==null||i._notifyReceived(e.message)}break}}}}class k{constructor(){a(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(i=>{try{i(e)}catch(n){console.error(`Error in event handler for "${t}":`,n)}})}removeAllListeners(){this.handlers.clear()}}const N=1e3,q=10,P=400,R=600,S="#6366f1",j=12,W="system-ui, -apple-system, sans-serif",_="Type a message...",K="bottom-right",J="light",Y={x:20,y:20},w="aikaara_conversation_id";class C extends k{constructor(e){super();a(this,"client");a(this,"config");a(this,"state","disconnected");a(this,"reconnectAttempt",0);a(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new g(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const i=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(i,"send_message",{content:s})}sendUserEvent(e,s,i,n){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...i&&{value:i},...n&&{source:n}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??q;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const i=(this.config.reconnectInterval??N)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const n=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new g(n),await this.connect()}catch{}},i)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class T{constructor(t,e,s){a(this,"baseUrl");a(this,"apiKey");a(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}},...t.extUid&&{ext_uid:t.extUid}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const i={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(i["X-Api-Key"]=this.apiKey);const n=`${this.baseUrl}${e}`,c={method:t,headers:i};s&&(c.body=JSON.stringify(s));const d=await fetch(n,c);if(!d.ok){const b=await d.text();let m;try{const y=JSON.parse(b);m=y.error||y.message||b}catch{m=b}throw new Error(`API error ${d.status}: ${m}`)}const u=await d.json();if(u&&typeof u=="object"&&"success"in u){if(!u.success)throw new Error(`API error: ${u.message||"Request failed"}`);return u.data}return u}}class M{constructor(){a(this,"_messages",[]);a(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const i={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(i),i}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class A{constructor(t,e=!0){a(this,"_conversationId");a(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(w)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(w)}catch{return null}}saveToStorage(t){try{localStorage.setItem(w,t)}catch{}}}class E extends k{constructor(e){super();a(this,"connection");a(this,"api");a(this,"messageStore");a(this,"conversationManager");a(this,"subscription",null);a(this,"config");this.config=e,this.connection=new C(e),this.api=new T(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new M,this.conversationManager=new A(e.conversationId),this.connection.on("connection:state",s=>{var i,n;this.emit("connection:state",s),(n=(i=this.config).onConnectionStateChange)==null||n.call(i,s)}),this.connection.on("error",s=>{var i,n;this.emit("error",s),(n=(i=this.config).onError)==null||n.call(i,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var n,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const i=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",i),(c=(n=this.config).onMessage)==null||c.call(n,i),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,i){const n=this.conversationManager.conversationId;if(!n)throw new Error("No active conversation");this.connection.sendUserEvent(n,e,s,i)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var i,n,c,d,u,b,m,y;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const l=e.status;this.emit("status",l),(n=(i=this.config).onStatusChange)==null||n.call(i,l),l==="processing"&&this.emit("typing:start",void 0);break}case"error":{const l=new Error(e.message||"Unknown error");this.emit("error",l),(d=(c=this.config).onError)==null||d.call(c,l);break}case"message_start":{if(e.role==="assistant"){const l=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:l.id}),this.emit("typing:start",void 0)}break}case"message_update":{const l=e.content||"",p=e.delta||"";this.messageStore.updateStreaming(l),this.emit("stream:update",{delta:p,content:l}),(b=(u=this.config).onStreamUpdate)==null||b.call(u,p,l);break}case"message_end":{const l=e.usage,p=this.messageStore.finalizeStreaming(l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0);this.emit("typing:stop",void 0),p&&(this.emit("stream:end",{messageId:p.id,usage:l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0}),this.emit("message:received",p),(y=(m=this.config).onMessage)==null||y.call(m,p));break}case"message_queued":{const l=this.messageStore.messages.findLast(p=>p.status==="sending");l&&this.messageStore.confirmOptimistic(l.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class G{constructor(t,e){a(this,"client");a(this,"panel");a(this,"bubble");a(this,"header");a(this,"messageList");a(this,"input");a(this,"errorBanner");a(this,"isOpen",!1);this.client=new E(t),this.bubble=e.querySelector("aikaara-chat-bubble"),this.panel=e.querySelector(".aikaara-panel"),this.header=e.querySelector("aikaara-chat-header"),this.messageList=e.querySelector("aikaara-message-list"),this.input=e.querySelector("aikaara-chat-input"),this.errorBanner=e.querySelector("aikaara-error-banner"),t.welcomeMessage&&this.messageList.setWelcomeMessage(t.welcomeMessage),t.showTimestamps!==void 0&&this.messageList.setShowTimestamps(t.showTimestamps),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble.addEventListener("toggle",()=>{this.togglePanel()}),this.header.addEventListener("close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(t=>{this.handleSend(t.detail.content)})),this.client.on("message:sent",t=>{this.messageList.addMessage(t)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const t=this.client.messages[this.client.messages.length-1];t&&this.messageList.addMessage(t)}),this.client.on("stream:update",({content:t})=>{this.messageList.updateStreamingContent(t)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const t=this.client.messages,e=t[t.length-1];(!e||e.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",t=>{this.header.setStatus(t),t==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):t==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):t==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",t=>{this.errorBanner.show(t.message,5e3)})}async handleSend(t){try{await this.client.sendMessage(t)}catch{this.errorBanner.show("Failed to send message",3e3)}}togglePanel(t){this.isOpen=t!==void 0?t:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200))}}class L extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"controller",null);a(this,"_config",{});this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["base-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url"]}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){var e;(e=this.controller)==null||e.disconnect()}attributeChangedCallback(e,s,i){s!==i&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||J,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||S,position:this.getAttribute("position")||this._config.position||K,width:Number(this.getAttribute("width"))||this._config.width||P,height:Number(this.getAttribute("height"))||this._config.height||R,fontFamily:this._config.fontFamily||W,borderRadius:this._config.borderRadius??j,placeholder:this.getAttribute("placeholder")||this._config.placeholder||_,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showBubble:this._config.showBubble??!0,offset:this._config.offset||Y,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange}}render(){var s,i;const e=this.getConfig();this.shadow.innerHTML=`
|
|
1
|
+
var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o,h,g)=>h in o?te(o,h,{enumerable:!0,configurable:!0,writable:!0,value:g}):o[h]=g;var a=(o,h,g)=>se(o,typeof h!="symbol"?h+"":h,g);class h{constructor(t,e){a(this,"identifier");a(this,"callbacks",{});a(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class g{constructor(t){a(this,"ws",null);a(this,"url");a(this,"subscriptions",new Map);a(this,"welcomePromise",null);a(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var i;const s=new Error("WebSocket connection error");(i=this.welcomePromise)==null||i.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new h(e,i=>{this.send({command:"message",identifier:e,data:JSON.stringify(i)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((i,n)=>{this.pendingSubscriptions.set(s,{resolve:()=>i(e),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),n(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyConnected();const c=this.pendingSubscriptions.get(i);c&&(c.resolve(),this.pendingSubscriptions.delete(i));break}case"reject_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyRejected(),this.subscriptions.delete(i);const c=this.pendingSubscriptions.get(i);c&&(c.reject(new Error(`Subscription rejected: ${i}`)),this.pendingSubscriptions.delete(i));break}case"disconnect":this.subscriptions.forEach(i=>i._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const i=this.subscriptions.get(e.identifier);i==null||i._notifyReceived(e.message)}break}}}}class k{constructor(){a(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(i=>{try{i(e)}catch(n){console.error(`Error in event handler for "${t}":`,n)}})}removeAllListeners(){this.handlers.clear()}}const N=1e3,q=10,P=400,R=600,S="#6366f1",j=12,W="system-ui, -apple-system, sans-serif",_="Type a message...",K="bottom-right",J="light",Y={x:20,y:20},w="aikaara_conversation_id";class C extends k{constructor(e){super();a(this,"client");a(this,"config");a(this,"state","disconnected");a(this,"reconnectAttempt",0);a(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new g(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const i=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(i,"send_message",{content:s})}sendUserEvent(e,s,i,n){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...i&&{value:i},...n&&{source:n}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??q;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const i=(this.config.reconnectInterval??N)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const n=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new g(n),await this.connect()}catch{}},i)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class T{constructor(t,e,s){a(this,"baseUrl");a(this,"apiKey");a(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.extUid&&{ext_uid:t.extUid},...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const i={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(i["X-Api-Key"]=this.apiKey);const n=`${this.baseUrl}${e}`,c={method:t,headers:i};s&&(c.body=JSON.stringify(s));const d=await fetch(n,c);if(!d.ok){const b=await d.text();let m;try{const y=JSON.parse(b);m=y.error||y.message||b}catch{m=b}throw new Error(`API error ${d.status}: ${m}`)}const u=await d.json();if(u&&typeof u=="object"&&"success"in u){if(!u.success)throw new Error(`API error: ${u.message||"Request failed"}`);return u.data}return u}}class M{constructor(){a(this,"_messages",[]);a(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const i={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(i),i}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class A{constructor(t,e=!0){a(this,"_conversationId");a(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(w)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(w)}catch{return null}}saveToStorage(t){try{localStorage.setItem(w,t)}catch{}}}class E extends k{constructor(e){super();a(this,"connection");a(this,"api");a(this,"messageStore");a(this,"conversationManager");a(this,"subscription",null);a(this,"config");this.config=e,this.connection=new C(e),this.api=new T(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new M,this.conversationManager=new A(e.conversationId),this.connection.on("connection:state",s=>{var i,n;this.emit("connection:state",s),(n=(i=this.config).onConnectionStateChange)==null||n.call(i,s)}),this.connection.on("error",s=>{var i,n;this.emit("error",s),(n=(i=this.config).onError)==null||n.call(i,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var n,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const i=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",i),(c=(n=this.config).onMessage)==null||c.call(n,i),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,i){const n=this.conversationManager.conversationId;if(!n)throw new Error("No active conversation");this.connection.sendUserEvent(n,e,s,i)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var i,n,c,d,u,b,m,y;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const l=e.status;this.emit("status",l),(n=(i=this.config).onStatusChange)==null||n.call(i,l),l==="processing"&&this.emit("typing:start",void 0);break}case"error":{const l=new Error(e.message||"Unknown error");this.emit("error",l),(d=(c=this.config).onError)==null||d.call(c,l);break}case"message_start":{if(e.role==="assistant"){const l=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:l.id}),this.emit("typing:start",void 0)}break}case"message_update":{const l=e.content||"",p=e.delta||"";this.messageStore.updateStreaming(l),this.emit("stream:update",{delta:p,content:l}),(b=(u=this.config).onStreamUpdate)==null||b.call(u,p,l);break}case"message_end":{const l=e.usage,p=this.messageStore.finalizeStreaming(l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0);this.emit("typing:stop",void 0),p&&(this.emit("stream:end",{messageId:p.id,usage:l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0}),this.emit("message:received",p),(y=(m=this.config).onMessage)==null||y.call(m,p));break}case"message_queued":{const l=this.messageStore.messages.findLast(p=>p.status==="sending");l&&this.messageStore.confirmOptimistic(l.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class G{constructor(t,e){a(this,"client");a(this,"panel");a(this,"bubble");a(this,"header");a(this,"messageList");a(this,"input");a(this,"errorBanner");a(this,"isOpen",!1);this.client=new E(t),this.bubble=e.querySelector("aikaara-chat-bubble"),this.panel=e.querySelector(".aikaara-panel"),this.header=e.querySelector("aikaara-chat-header"),this.messageList=e.querySelector("aikaara-message-list"),this.input=e.querySelector("aikaara-chat-input"),this.errorBanner=e.querySelector("aikaara-error-banner"),t.welcomeMessage&&this.messageList.setWelcomeMessage(t.welcomeMessage),t.showTimestamps!==void 0&&this.messageList.setShowTimestamps(t.showTimestamps),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble.addEventListener("toggle",()=>{this.togglePanel()}),this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(t=>{this.handleSend(t.detail.content)})),this.client.on("message:sent",t=>{this.messageList.addMessage(t)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const t=this.client.messages[this.client.messages.length-1];t&&this.messageList.addMessage(t)}),this.client.on("stream:update",({content:t})=>{this.messageList.updateStreamingContent(t)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const t=this.client.messages,e=t[t.length-1];(!e||e.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",t=>{this.header.setStatus(t),t==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):t==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):t==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",t=>{this.errorBanner.show(t.message,5e3)})}async handleSend(t){try{await this.client.sendMessage(t)}catch{this.errorBanner.show("Failed to send message",3e3)}}togglePanel(t){this.isOpen=t!==void 0?t:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200))}}class L extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"controller",null);a(this,"_config",{});this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["base-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url"]}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){var e;(e=this.controller)==null||e.disconnect()}attributeChangedCallback(e,s,i){s!==i&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||J,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||S,position:this.getAttribute("position")||this._config.position||K,width:Number(this.getAttribute("width"))||this._config.width||P,height:Number(this.getAttribute("height"))||this._config.height||R,fontFamily:this._config.fontFamily||W,borderRadius:this._config.borderRadius??j,placeholder:this.getAttribute("placeholder")||this._config.placeholder||_,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showBubble:this._config.showBubble??!0,offset:this._config.offset||Y,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange}}render(){var s,i;const e=this.getConfig();this.shadow.innerHTML=`
|
|
2
2
|
<style>
|
|
3
3
|
:host {
|
|
4
4
|
--aikaara-primary: ${e.primaryColor};
|
|
@@ -101,7 +101,7 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
|
|
|
101
101
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
|
102
102
|
</svg>
|
|
103
103
|
</button>
|
|
104
|
-
`}setIcon(e){const s=this.shadow.querySelector(".bubble");s&&(s.innerHTML=e)}}class $ extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["title","subtitle","avatar-url","status"]}connectedCallback(){
|
|
104
|
+
`}setIcon(e){const s=this.shadow.querySelector(".bubble");s&&(s.innerHTML=e)}}class $ extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["title","subtitle","avatar-url","status"]}connectedCallback(){this.render(),this.bindClose()}attributeChangedCallback(){this.render(),this.bindClose()}bindClose(){var e;(e=this.shadow.querySelector(".close-btn"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))})}render(){const e=this.getAttribute("title")||"Chat",s=this.getAttribute("subtitle")||"",i=this.getAttribute("avatar-url"),n=this.getAttribute("status")||"connected",c=n==="connected"?"#10b981":n==="connecting"||n==="reconnecting"?"#f59e0b":"#ef4444";this.shadow.innerHTML=`
|
|
105
105
|
<style>
|
|
106
106
|
.header {
|
|
107
107
|
display: flex;
|
|
@@ -271,11 +271,11 @@ class k {
|
|
|
271
271
|
async createConversation(t) {
|
|
272
272
|
const e = {
|
|
273
273
|
conversation: {
|
|
274
|
+
...t.extUid && { ext_uid: t.extUid },
|
|
274
275
|
...t.systemPromptId && { system_prompt_id: t.systemPromptId },
|
|
275
276
|
...t.channel && { channel: t.channel },
|
|
276
277
|
...t.title && { title: t.title }
|
|
277
|
-
}
|
|
278
|
-
...t.extUid && { ext_uid: t.extUid }
|
|
278
|
+
}
|
|
279
279
|
};
|
|
280
280
|
return this.request("POST", "/api/v1/conversations", e);
|
|
281
281
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var E=Object.defineProperty;var T=(a,t,e)=>t in a?E(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var o=(a,t,e)=>T(a,typeof t!="symbol"?t+"":t,e);class b{constructor(t,e){o(this,"identifier");o(this,"callbacks",{});o(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class f{constructor(t){o(this,"ws",null);o(this,"url");o(this,"subscriptions",new Map);o(this,"welcomePromise",null);o(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var n;const s=new Error("WebSocket connection error");(n=this.welcomePromise)==null||n.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new b(e,n=>{this.send({command:"message",identifier:e,data:JSON.stringify(n)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((n,i)=>{this.pendingSubscriptions.set(s,{resolve:()=>n(e),reject:i}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),i(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyConnected();const c=this.pendingSubscriptions.get(n);c&&(c.resolve(),this.pendingSubscriptions.delete(n));break}case"reject_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyRejected(),this.subscriptions.delete(n);const c=this.pendingSubscriptions.get(n);c&&(c.reject(new Error(`Subscription rejected: ${n}`)),this.pendingSubscriptions.delete(n));break}case"disconnect":this.subscriptions.forEach(n=>n._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const n=this.subscriptions.get(e.identifier);n==null||n._notifyReceived(e.message)}break}}}}class _{constructor(){o(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(n=>{try{n(e)}catch(i){console.error(`Error in event handler for "${t}":`,i)}})}removeAllListeners(){this.handlers.clear()}}const I=1e3,A=10,k=400,C=600,M="#6366f1",O=12,U="system-ui, -apple-system, sans-serif",D="Type a message...",F="bottom-right",L="light",R={x:20,y:20},p="aikaara_conversation_id";class S extends _{constructor(e){super();o(this,"client");o(this,"config");o(this,"state","disconnected");o(this,"reconnectAttempt",0);o(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new f(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_message",{content:s})}sendUserEvent(e,s,n,i){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...n&&{value:n},...i&&{source:i}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??A;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const n=(this.config.reconnectInterval??I)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const i=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new f(i),await this.connect()}catch{}},n)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class v{constructor(t,e,s){o(this,"baseUrl");o(this,"apiKey");o(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}},...t.extUid&&{ext_uid:t.extUid}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const n={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(n["X-Api-Key"]=this.apiKey);const i=`${this.baseUrl}${e}`,c={method:t,headers:n};s&&(c.body=JSON.stringify(s));const l=await fetch(i,c);if(!l.ok){const u=await l.text();let g;try{const m=JSON.parse(u);g=m.error||m.message||u}catch{g=u}throw new Error(`API error ${l.status}: ${g}`)}const h=await l.json();if(h&&typeof h=="object"&&"success"in h){if(!h.success)throw new Error(`API error: ${h.message||"Request failed"}`);return h.data}return h}}class y{constructor(){o(this,"_messages",[]);o(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const n={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(n),n}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class w{constructor(t,e=!0){o(this,"_conversationId");o(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(p)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(p)}catch{return null}}saveToStorage(t){try{localStorage.setItem(p,t)}catch{}}}class N extends _{constructor(e){super();o(this,"connection");o(this,"api");o(this,"messageStore");o(this,"conversationManager");o(this,"subscription",null);o(this,"config");this.config=e,this.connection=new S(e),this.api=new v(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new y,this.conversationManager=new w(e.conversationId),this.connection.on("connection:state",s=>{var n,i;this.emit("connection:state",s),(i=(n=this.config).onConnectionStateChange)==null||i.call(n,s)}),this.connection.on("error",s=>{var n,i;this.emit("error",s),(i=(n=this.config).onError)==null||i.call(n,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var i,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const n=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",n),(c=(i=this.config).onMessage)==null||c.call(i,n),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,n){const i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection.sendUserEvent(i,e,s,n)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var n,i,c,l,h,u,g,m;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),(i=(n=this.config).onStatusChange)==null||i.call(n,r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),(l=(c=this.config).onError)==null||l.call(c,r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.content||"",d=e.delta||"";this.messageStore.updateStreaming(r),this.emit("stream:update",{delta:d,content:r}),(u=(h=this.config).onStreamUpdate)==null||u.call(h,d,r);break}case"message_end":{const r=e.usage,d=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),d&&(this.emit("stream:end",{messageId:d.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",d),(m=(g=this.config).onMessage)==null||m.call(g,d));break}case"message_queued":{const r=this.messageStore.messages.findLast(d=>d.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}exports.ActionCableClient=f;exports.AikaaraChatClient=N;exports.ApiClient=v;exports.ChannelSubscription=b;exports.ConnectionManager=S;exports.ConversationManager=w;exports.DEFAULT_BORDER_RADIUS=O;exports.DEFAULT_FONT_FAMILY=U;exports.DEFAULT_OFFSET=R;exports.DEFAULT_PLACEHOLDER=D;exports.DEFAULT_POSITION=F;exports.DEFAULT_PRIMARY_COLOR=M;exports.DEFAULT_THEME=L;exports.DEFAULT_WIDGET_HEIGHT=C;exports.DEFAULT_WIDGET_WIDTH=k;exports.EventEmitter=_;exports.MessageStore=y;
|
|
1
|
+
"use strict";var E=Object.defineProperty;var T=(a,t,e)=>t in a?E(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var o=(a,t,e)=>T(a,typeof t!="symbol"?t+"":t,e);class b{constructor(t,e){o(this,"identifier");o(this,"callbacks",{});o(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class f{constructor(t){o(this,"ws",null);o(this,"url");o(this,"subscriptions",new Map);o(this,"welcomePromise",null);o(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var n;const s=new Error("WebSocket connection error");(n=this.welcomePromise)==null||n.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new b(e,n=>{this.send({command:"message",identifier:e,data:JSON.stringify(n)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((n,i)=>{this.pendingSubscriptions.set(s,{resolve:()=>n(e),reject:i}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),i(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyConnected();const c=this.pendingSubscriptions.get(n);c&&(c.resolve(),this.pendingSubscriptions.delete(n));break}case"reject_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyRejected(),this.subscriptions.delete(n);const c=this.pendingSubscriptions.get(n);c&&(c.reject(new Error(`Subscription rejected: ${n}`)),this.pendingSubscriptions.delete(n));break}case"disconnect":this.subscriptions.forEach(n=>n._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const n=this.subscriptions.get(e.identifier);n==null||n._notifyReceived(e.message)}break}}}}class _{constructor(){o(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(n=>{try{n(e)}catch(i){console.error(`Error in event handler for "${t}":`,i)}})}removeAllListeners(){this.handlers.clear()}}const I=1e3,A=10,k=400,C=600,M="#6366f1",O=12,U="system-ui, -apple-system, sans-serif",D="Type a message...",F="bottom-right",L="light",R={x:20,y:20},p="aikaara_conversation_id";class S extends _{constructor(e){super();o(this,"client");o(this,"config");o(this,"state","disconnected");o(this,"reconnectAttempt",0);o(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new f(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_message",{content:s})}sendUserEvent(e,s,n,i){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...n&&{value:n},...i&&{source:i}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??A;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const n=(this.config.reconnectInterval??I)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const i=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new f(i),await this.connect()}catch{}},n)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class v{constructor(t,e,s){o(this,"baseUrl");o(this,"apiKey");o(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.extUid&&{ext_uid:t.extUid},...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const n={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(n["X-Api-Key"]=this.apiKey);const i=`${this.baseUrl}${e}`,c={method:t,headers:n};s&&(c.body=JSON.stringify(s));const l=await fetch(i,c);if(!l.ok){const u=await l.text();let g;try{const m=JSON.parse(u);g=m.error||m.message||u}catch{g=u}throw new Error(`API error ${l.status}: ${g}`)}const h=await l.json();if(h&&typeof h=="object"&&"success"in h){if(!h.success)throw new Error(`API error: ${h.message||"Request failed"}`);return h.data}return h}}class y{constructor(){o(this,"_messages",[]);o(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const n={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(n),n}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class w{constructor(t,e=!0){o(this,"_conversationId");o(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(p)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(p)}catch{return null}}saveToStorage(t){try{localStorage.setItem(p,t)}catch{}}}class N extends _{constructor(e){super();o(this,"connection");o(this,"api");o(this,"messageStore");o(this,"conversationManager");o(this,"subscription",null);o(this,"config");this.config=e,this.connection=new S(e),this.api=new v(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new y,this.conversationManager=new w(e.conversationId),this.connection.on("connection:state",s=>{var n,i;this.emit("connection:state",s),(i=(n=this.config).onConnectionStateChange)==null||i.call(n,s)}),this.connection.on("error",s=>{var n,i;this.emit("error",s),(i=(n=this.config).onError)==null||i.call(n,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var i,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const n=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",n),(c=(i=this.config).onMessage)==null||c.call(i,n),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,n){const i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection.sendUserEvent(i,e,s,n)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var n,i,c,l,h,u,g,m;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),(i=(n=this.config).onStatusChange)==null||i.call(n,r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),(l=(c=this.config).onError)==null||l.call(c,r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.content||"",d=e.delta||"";this.messageStore.updateStreaming(r),this.emit("stream:update",{delta:d,content:r}),(u=(h=this.config).onStreamUpdate)==null||u.call(h,d,r);break}case"message_end":{const r=e.usage,d=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),d&&(this.emit("stream:end",{messageId:d.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",d),(m=(g=this.config).onMessage)==null||m.call(g,d));break}case"message_queued":{const r=this.messageStore.messages.findLast(d=>d.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}exports.ActionCableClient=f;exports.AikaaraChatClient=N;exports.ApiClient=v;exports.ChannelSubscription=b;exports.ConnectionManager=S;exports.ConversationManager=w;exports.DEFAULT_BORDER_RADIUS=O;exports.DEFAULT_FONT_FAMILY=U;exports.DEFAULT_OFFSET=R;exports.DEFAULT_PLACEHOLDER=D;exports.DEFAULT_POSITION=F;exports.DEFAULT_PRIMARY_COLOR=M;exports.DEFAULT_THEME=L;exports.DEFAULT_WIDGET_HEIGHT=C;exports.DEFAULT_WIDGET_WIDTH=k;exports.EventEmitter=_;exports.MessageStore=y;
|
package/dist/headless.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./headless-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./headless-DDmLD-ag.cjs");exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;
|
package/dist/headless.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as n, a as t, b as s, C as i, c as o, d as r, E as C, M as l } from "./headless-
|
|
1
|
+
import { A as n, a as t, b as s, C as i, c as o, d as r, E as C, M as l } from "./headless-CXRux2Q-.mjs";
|
|
2
2
|
export {
|
|
3
3
|
n as ActionCableClient,
|
|
4
4
|
t as AikaaraChatClient,
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./headless-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./headless-DDmLD-ag.cjs"),a=require("./ui.cjs");function l(t){a.registerComponents();const r=document.createElement("aikaara-chat-widget"),n={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[o,s]of Object.entries(n)){const i=t[o];i!=null&&r.setAttribute(s,String(i))}return r.configure(t),document.body.appendChild(r),r}function u(){const t=document.querySelector("aikaara-chat-widget");t&&t.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;exports.mount=l;exports.unmount=u;
|
package/dist/index.d.ts
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as p, a as d, b as g, C as h, c as k, d as C, E as b, M as A } from "./headless-
|
|
1
|
+
import { A as p, a as d, b as g, C as h, c as k, d as C, E as b, M as A } from "./headless-CXRux2Q-.mjs";
|
|
2
2
|
import { registerComponents as n } from "./ui.mjs";
|
|
3
3
|
import { AikaaraChatBubble as M, AikaaraChatHeader as w, AikaaraChatInput as y, AikaaraChatWidget as v, AikaaraErrorBanner as E, AikaaraMessageBubble as S, AikaaraMessageList as x, AikaaraStreamingMessage as B, AikaaraTypingIndicator as I } from "./ui.mjs";
|
|
4
4
|
function l(a) {
|
package/dist/ui.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var T=Object.defineProperty;var
|
|
1
|
+
"use strict";var T=Object.defineProperty;var C=(s,t,e)=>t in s?T(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var i=(s,t,e)=>C(s,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./headless-DDmLD-ag.cjs");class L{constructor(t,e){i(this,"client");i(this,"panel");i(this,"bubble");i(this,"header");i(this,"messageList");i(this,"input");i(this,"errorBanner");i(this,"isOpen",!1);this.client=new o.AikaaraChatClient(t),this.bubble=e.querySelector("aikaara-chat-bubble"),this.panel=e.querySelector(".aikaara-panel"),this.header=e.querySelector("aikaara-chat-header"),this.messageList=e.querySelector("aikaara-message-list"),this.input=e.querySelector("aikaara-chat-input"),this.errorBanner=e.querySelector("aikaara-error-banner"),t.welcomeMessage&&this.messageList.setWelcomeMessage(t.welcomeMessage),t.showTimestamps!==void 0&&this.messageList.setShowTimestamps(t.showTimestamps),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble.addEventListener("toggle",()=>{this.togglePanel()}),this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(t=>{this.handleSend(t.detail.content)})),this.client.on("message:sent",t=>{this.messageList.addMessage(t)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const t=this.client.messages[this.client.messages.length-1];t&&this.messageList.addMessage(t)}),this.client.on("stream:update",({content:t})=>{this.messageList.updateStreamingContent(t)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const t=this.client.messages,e=t[t.length-1];(!e||e.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",t=>{this.header.setStatus(t),t==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):t==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):t==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",t=>{this.errorBanner.show(t.message,5e3)})}async handleSend(t){try{await this.client.sendMessage(t)}catch{this.errorBanner.show("Failed to send message",3e3)}}togglePanel(t){this.isOpen=t!==void 0?t:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200))}}class b extends HTMLElement{constructor(){super();i(this,"shadow");i(this,"controller",null);i(this,"_config",{});this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["base-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url"]}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){var e;(e=this.controller)==null||e.disconnect()}attributeChangedCallback(e,a,r){a!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||o.DEFAULT_THEME,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||o.DEFAULT_PRIMARY_COLOR,position:this.getAttribute("position")||this._config.position||o.DEFAULT_POSITION,width:Number(this.getAttribute("width"))||this._config.width||o.DEFAULT_WIDGET_WIDTH,height:Number(this.getAttribute("height"))||this._config.height||o.DEFAULT_WIDGET_HEIGHT,fontFamily:this._config.fontFamily||o.DEFAULT_FONT_FAMILY,borderRadius:this._config.borderRadius??o.DEFAULT_BORDER_RADIUS,placeholder:this.getAttribute("placeholder")||this._config.placeholder||o.DEFAULT_PLACEHOLDER,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showBubble:this._config.showBubble??!0,offset:this._config.offset||o.DEFAULT_OFFSET,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange}}render(){var a,r;const e=this.getConfig();this.shadow.innerHTML=`
|
|
2
2
|
<style>
|
|
3
3
|
:host {
|
|
4
4
|
--aikaara-primary: ${e.primaryColor};
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
<aikaara-chat-input placeholder="${e.placeholder||o.DEFAULT_PLACEHOLDER}"></aikaara-chat-input>
|
|
67
67
|
<aikaara-error-banner></aikaara-error-banner>
|
|
68
68
|
</div>
|
|
69
|
-
`}async initController(){var a;const e=this.getConfig();!e.baseUrl||!e.userToken||((a=this.controller)==null||a.disconnect(),this.controller=new
|
|
69
|
+
`}async initController(){var a;const e=this.getConfig();!e.baseUrl||!e.userToken||((a=this.controller)==null||a.disconnect(),this.controller=new L(e,this.shadow),await this.controller.connect())}darkenColor(e){try{const a=parseInt(e.replace("#",""),16),r=Math.max(0,(a>>16)-20),n=Math.max(0,(a>>8&255)-20),d=Math.max(0,(a&255)-20);return`#${(r<<16|n<<8|d).toString(16).padStart(6,"0")}`}catch{return e}}}class p extends HTMLElement{constructor(){super();i(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){var e;this.render(),(e=this.shadow.querySelector(".bubble"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
|
|
70
70
|
<style>
|
|
71
71
|
.bubble {
|
|
72
72
|
width: var(--aikaara-bubble-size, 60px);
|
|
@@ -101,7 +101,7 @@
|
|
|
101
101
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
|
102
102
|
</svg>
|
|
103
103
|
</button>
|
|
104
|
-
`}setIcon(e){const a=this.shadow.querySelector(".bubble");a&&(a.innerHTML=e)}}class u extends HTMLElement{constructor(){super();i(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["title","subtitle","avatar-url","status"]}connectedCallback(){
|
|
104
|
+
`}setIcon(e){const a=this.shadow.querySelector(".bubble");a&&(a.innerHTML=e)}}class u extends HTMLElement{constructor(){super();i(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["title","subtitle","avatar-url","status"]}connectedCallback(){this.render(),this.bindClose()}attributeChangedCallback(){this.render(),this.bindClose()}bindClose(){var e;(e=this.shadow.querySelector(".close-btn"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))})}render(){const e=this.getAttribute("title")||"Chat",a=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),n=this.getAttribute("status")||"connected",d=n==="connected"?"#10b981":n==="connecting"||n==="reconnecting"?"#f59e0b":"#ef4444";this.shadow.innerHTML=`
|
|
105
105
|
<style>
|
|
106
106
|
.header {
|
|
107
107
|
display: flex;
|
package/dist/ui.d.ts
CHANGED
package/dist/ui.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var u = Object.defineProperty;
|
|
2
2
|
var g = (s, t, e) => t in s ? u(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
|
|
3
3
|
var i = (s, t, e) => g(s, typeof t != "symbol" ? t + "" : t, e);
|
|
4
|
-
import { a as m, D as f, e as h, f as x, g as k, h as y, i as v, j as w, k as b, l as T } from "./headless-
|
|
4
|
+
import { a as m, D as f, e as h, f as x, g as k, h as y, i as v, j as w, k as b, l as T } from "./headless-CXRux2Q-.mjs";
|
|
5
5
|
class L {
|
|
6
6
|
constructor(t, e) {
|
|
7
7
|
i(this, "client");
|
|
@@ -27,7 +27,7 @@ class L {
|
|
|
27
27
|
wireEvents() {
|
|
28
28
|
this.bubble.addEventListener("toggle", () => {
|
|
29
29
|
this.togglePanel();
|
|
30
|
-
}), this.header.addEventListener("close", () => {
|
|
30
|
+
}), this.header.addEventListener("header-close", () => {
|
|
31
31
|
this.togglePanel(!1);
|
|
32
32
|
}), this.input.addEventListener("send", ((t) => {
|
|
33
33
|
this.handleSend(t.detail.content);
|
|
@@ -288,13 +288,16 @@ class S extends HTMLElement {
|
|
|
288
288
|
return ["title", "subtitle", "avatar-url", "status"];
|
|
289
289
|
}
|
|
290
290
|
connectedCallback() {
|
|
291
|
-
|
|
292
|
-
this.render(), (e = this.shadow.querySelector(".close-btn")) == null || e.addEventListener("click", () => {
|
|
293
|
-
this.dispatchEvent(new CustomEvent("close", { bubbles: !0, composed: !0 }));
|
|
294
|
-
});
|
|
291
|
+
this.render(), this.bindClose();
|
|
295
292
|
}
|
|
296
293
|
attributeChangedCallback() {
|
|
297
|
-
this.render();
|
|
294
|
+
this.render(), this.bindClose();
|
|
295
|
+
}
|
|
296
|
+
bindClose() {
|
|
297
|
+
var e;
|
|
298
|
+
(e = this.shadow.querySelector(".close-btn")) == null || e.addEventListener("click", () => {
|
|
299
|
+
this.dispatchEvent(new CustomEvent("header-close", { bubbles: !0, composed: !0 }));
|
|
300
|
+
});
|
|
298
301
|
}
|
|
299
302
|
render() {
|
|
300
303
|
const e = this.getAttribute("title") || "Chat", a = this.getAttribute("subtitle") || "", r = this.getAttribute("avatar-url"), n = this.getAttribute("status") || "connected", l = n === "connected" ? "#10b981" : n === "connecting" || n === "reconnecting" ? "#f59e0b" : "#ef4444";
|