@aikaara/chat-sdk 0.1.2 → 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.
@@ -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.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("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(){var e;this.render(),(e=this.shadow.querySelector(".close-btn"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("close",{bubbles:!0,composed:!0}))})}attributeChangedCallback(){this.render()}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=`
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;
package/dist/index.d.ts CHANGED
@@ -62,6 +62,7 @@ export declare class AikaaraChatHeader extends HTMLElement {
62
62
  constructor();
63
63
  connectedCallback(): void;
64
64
  attributeChangedCallback(): void;
65
+ private bindClose;
65
66
  private render;
66
67
  setStatus(status: string): void;
67
68
  }
package/dist/ui.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var T=Object.defineProperty;var L=(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)=>L(s,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./headless-DDmLD-ag.cjs");class C{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("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=`
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 C(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=`
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(){var e;this.render(),(e=this.shadow.querySelector(".close-btn"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("close",{bubbles:!0,composed:!0}))})}attributeChangedCallback(){this.render()}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=`
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
@@ -12,6 +12,7 @@ export declare class AikaaraChatHeader extends HTMLElement {
12
12
  constructor();
13
13
  connectedCallback(): void;
14
14
  attributeChangedCallback(): void;
15
+ private bindClose;
15
16
  private render;
16
17
  setStatus(status: string): void;
17
18
  }
package/dist/ui.mjs CHANGED
@@ -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
- var e;
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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aikaara/chat-sdk",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "description": "Aikaara Chat SDK — embeddable chat widget and headless client",
6
6
  "license": "MIT",