@brainbase-labs/chat-widget 0.1.6 → 0.1.8

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/index.cjs ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react"),e=require("react/jsx-runtime"),Q="bb-chat-";function te(s){try{const t=sessionStorage.getItem(`${Q}${s}`);return t?JSON.parse(t):null}catch{return null}}function J(s,t){try{sessionStorage.setItem(`${Q}${s}`,JSON.stringify(t))}catch{}}function Y(s){try{sessionStorage.removeItem(`${Q}${s}`)}catch{}}function se(s){const{config:t,apiClient:n,mockMode:r,onSessionStart:d,onSessionEnd:u,onMessage:c,onError:g}=s,[l,o]=i.useState([]),[y,B]=i.useState([]),[P,k]=i.useState(!1),[O,W]=i.useState(null),[m,T]=i.useState(null),$=i.useRef(0),H=i.useRef(!1);i.useEffect(()=>{if(H.current)return;H.current=!0;const _=te(t.embedId);_&&_.status==="active"&&(T(_.sessionId),o(_.messages),B(_.toolCalls),$.current=_.startTime)},[t.embedId]),i.useEffect(()=>{m&&l.length>0&&J(t.embedId,{sessionId:m,deploymentId:t.deploymentId,workerId:t.workerId,flowId:t.flowId,startTime:$.current,messages:l,toolCalls:y,status:"active"})},[m,l,y,t]);const F=i.useCallback(async()=>($.current=Date.now(),T(null),o([]),B([]),Y(t.embedId),""),[t.embedId]),N=i.useCallback((_,x,j)=>{switch(_.type){case"session":{const p=_.data;p.session_id&&(j(p.session_id),p.is_new&&($.current=Date.now(),d==null||d(p.session_id)));break}case"message":{const p=_.data;p.content&&o(h=>h.map(a=>a.id===x?{...a,content:p.content,status:"streaming"}:a));break}case"tool_call":{const p=_.data;B(h=>{const a=h.findIndex(f=>f.name===p.function&&f.status==="pending");return a!==-1&&p.result!==void 0?h.map((f,C)=>C===a?{...f,result:p.result,status:"completed"}:f):a===-1?[...h,{id:`tc-${Date.now()}-${Math.random().toString(36).slice(2)}`,name:p.function,arguments:p.args??{},status:"pending",timestamp:Date.now()}]:h}),p.content&&o(h=>h.map(a=>a.id===x?{...a,content:p.content,status:"streaming"}:a));break}case"waiting":break;case"done":{o(p=>p.map(h=>h.id===x?{...h,status:"sent"}:h));break}case"completed":{o(p=>p.map(h=>h.id===x?{...h,status:"sent"}:h)),m&&J(t.embedId,{sessionId:m,deploymentId:t.deploymentId,workerId:t.workerId,flowId:t.flowId,startTime:$.current,messages:l,toolCalls:y,status:"completed"});break}case"error":{const p=_.data;o(h=>h.map(a=>a.id===x?{...a,status:"error",content:p.error??"An error occurred"}:a));break}}},[t,m,l,y,d]),U=i.useCallback(async(_,x,j)=>{const p=_.getReader(),h=new TextDecoder;let a="";try{for(;;){const{done:f,value:C}=await p.read();if(f)break;for(a+=h.decode(C,{stream:!0});a.includes(`
2
+
3
+ `);){const[L,ge]=a.split(`
4
+
5
+ `,2);a=ge;for(const ee of L.split(`
6
+ `))if(ee.startsWith("data: "))try{const me=JSON.parse(ee.slice(6));N(me,x,j)}catch{}}}}finally{p.releaseLock()}},[N]),q=i.useCallback(async _=>{if(!_.trim())return;const x={id:`user-${Date.now()}`,role:"user",content:_,timestamp:Date.now(),status:"sent"};o(a=>[...a,x]),c==null||c(x);const j=`assistant-${Date.now()}`,p={id:j,role:"assistant",content:"",timestamp:Date.now(),status:"streaming"};o(a=>[...a,p]),k(!0),W(null);const h=a=>{T(a)};try{if(r){const a=n.sendMessage(_);for await(const f of a)N(f,j,h)}else{const a=await n.sendMessage({embedId:t.embedId,message:_,sessionId:m??void 0});await U(a,j,h)}o(a=>a.map(f=>f.id===j&&f.status==="streaming"?{...f,status:"sent"}:f))}catch(a){const f=a instanceof Error?a:new Error("Failed to send message");W(f),g==null||g(f),o(C=>C.map(L=>L.id===j?{...L,status:"error",content:"Failed to get response"}:L))}finally{k(!1)}},[m,n,r,t.embedId,N,U,c,g]),E=i.useCallback(async()=>{if(!m)return;const _={sessionId:m,deploymentId:t.deploymentId,workerId:t.workerId,flowId:t.flowId,startTime:$.current,messages:l,toolCalls:y,status:"completed"};u==null||u(_),Y(t.embedId),T(null),o([]),B([])},[m,t,l,y,u]),V=i.useCallback(()=>{o([]),B([])},[]);return{messages:l,toolCalls:y,isLoading:P,error:O,sessionId:m,sendMessage:q,endSession:E,clearMessages:V,startNewSession:F}}const pe="https://whatsapp-based-server.onrender.com";function oe(s=pe){return{async getDeploymentConfig(t){const n=await fetch(`${s}/chat/config/${t}`);if(!n.ok)throw new Error(`Failed to fetch deployment config: ${n.status}`);const r=await n.json();return{embedId:r.embedId,deploymentId:"",workerId:"",flowId:"",welcomeMessage:r.welcomeMessage,agentName:r.agentName,agentLogoUrl:r.agentLogoUrl,primaryColor:r.primaryColor,styling:r.styling}},async sendMessage(t){const n=await fetch(`${s}/chat/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embed_id:t.embedId,message:t.message,session_id:t.sessionId||void 0,metadata:t.metadata})});if(!n.ok){const r=await n.text();throw new Error(`Failed to send message: ${n.status} - ${r}`)}if(!n.body)throw new Error("No response stream available");return n.body}}}const he={embedId:"mock-embed-id",deploymentId:"mock-deployment-id",workerId:"mock-worker-id",flowId:"mock-flow-id",agentName:"AI Assistant",agentLogoUrl:void 0,primaryColor:"#1a1a2e",styling:{}},_e=[{trigger:/hello|hi|hey/i,response:"Hello! I'm a demo AI assistant. How can I help you today?",delay:500},{trigger:/weather/i,response:"I'd check the weather for you, but I'm in mock mode! In production, I could use a weather API.",delay:800,toolCalls:[{name:"get_weather",arguments:{location:"San Francisco"},result:{temperature:72,condition:"sunny"}}]},{trigger:/help|support/i,response:"I'm here to help! You can ask me questions, and I'll do my best to assist you. In production, I'd be connected to your agent with full capabilities.",delay:600},{trigger:/pricing|cost|price/i,response:"For pricing information, I'd typically check our database or connect you with the sales team. This is a mock response demonstrating how I'd handle pricing questions.",delay:700,toolCalls:[{name:"lookup_pricing",arguments:{plan:"all"},result:{plans:[{name:"Starter",price:"$29/mo"},{name:"Pro",price:"$99/mo"}]}}]},{trigger:/.*/,response:"I'm running in mock mode. This is a simulated response to demonstrate the chat UI. In production, I'd be connected to your agent!",delay:1e3}];function A(s){return new Promise(t=>setTimeout(t,s))}function ne(s,t){const n={...he,...s},r=t??_e,d=`mock-session-${Date.now()}`;return{async getDeploymentConfig(u){return await A(300),n},async*sendMessage(u){yield{type:"session",data:{session_id:d,is_new:!0},timestamp:Date.now()};const c=r.find(o=>typeof o.trigger=="string"?u.toLowerCase().includes(o.trigger.toLowerCase()):o.trigger.test(u))??r[r.length-1];if(await A(c.delay??500),c.toolCalls)for(const o of c.toolCalls)yield{type:"tool_call",data:{function:o.name,args:o.arguments},timestamp:Date.now()},await A(300),yield{type:"tool_call",data:{function:o.name,result:o.result},timestamp:Date.now()},await A(200);const g=c.response.split(" ");let l="";for(const o of g)l+=(l?" ":"")+o,yield{type:"message",data:{content:l,role:"assistant"},timestamp:Date.now()},await A(30+Math.random()*40);yield{type:"done",data:{session_id:d},timestamp:Date.now()}}}}const z=({className:s,color:t="currentColor",cutoutColor:n="var(--bb-primary-color)"})=>e.jsxs("svg",{className:s,viewBox:"0 0 800 800",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H788C794.627 400 800 405.373 800 412V740C800 773.137 773.137 800 740 800H412C405.373 800 400 794.627 400 788V412Z",fill:t}),e.jsx("circle",{cx:"400",cy:"400",r:"400",fill:t}),e.jsx("path",{d:"M0 60C0 26.8629 26.8629 0 60 0H397.614C398.932 0 400 1.06811 400 2.38569V2.38569C400 221.982 221.982 400 2.38569 400V400C1.06811 400 0 398.932 0 397.614V60Z",fill:t}),e.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H738C744.627 400 750 405.373 750 412V725C750 738.807 738.807 750 725 750H412C405.373 750 400 744.627 400 738V412Z",fill:t}),e.jsx("circle",{cx:"400",cy:"400",r:"350",fill:t}),e.jsx("path",{d:"M50 75C50 61.1929 61.1929 50 75 50H388C394.627 50 400 55.3726 400 62V388C400 394.627 394.627 400 388 400H62C55.3726 400 50 394.627 50 388V75Z",fill:t}),e.jsx("rect",{x:"399.919",y:"209",width:"270",height:"270",rx:"12",transform:"rotate(45 399.919 209)",fill:n})]}),fe="_header_1p6z5_1",xe="_compact_1p6z5_9",be="_headerBackground_1p6z5_20",we="_headerContent_1p6z5_59",ye="_topRow_1p6z5_64",je="_agentInfo_1p6z5_79",Ce="_agentLogo_1p6z5_85",ke="_agentLogoPlaceholder_1p6z5_102",ve="_brainbaseLogo_1p6z5_123",Ie="_agentName_1p6z5_137",Ne="_actions_1p6z5_144",Le="_actionButton_1p6z5_149",Be="_welcomeText_1p6z5_183",$e="_title_1p6z5_202",Se="_subtitle_1p6z5_210",b={header:fe,compact:xe,headerBackground:be,headerContent:we,topRow:ye,agentInfo:je,agentLogo:Ce,agentLogoPlaceholder:ke,brainbaseLogo:ve,agentName:Ie,actions:Ne,actionButton:Le,welcomeText:Be,title:$e,subtitle:Se},re=({agentName:s="AI Assistant",agentLogoUrl:t,welcomeTitle:n,welcomeSubtitle:r,onClose:d,onNewChatRequest:u,showNewChatButton:c=!1,compact:g=!1})=>{const l=n||"Hello there.",o=r!==void 0?r:n?void 0:"How can we help?";return e.jsxs("div",{className:`${b.header} ${g?b.compact:""}`,children:[e.jsx("div",{className:b.headerBackground}),e.jsxs("div",{className:b.headerContent,children:[e.jsxs("div",{className:b.topRow,children:[e.jsxs("div",{className:b.agentInfo,children:[t?e.jsx("img",{src:t,alt:s,className:b.agentLogo}):e.jsx("div",{className:b.agentLogoPlaceholder,children:e.jsx(z,{className:b.brainbaseLogo,color:"white",cutoutColor:"var(--bb-primary-color)"})}),e.jsx("span",{className:b.agentName,children:s})]}),e.jsxs("div",{className:b.actions,children:[c&&u&&e.jsx("button",{className:b.actionButton,onClick:u,"aria-label":"Start new chat",type:"button",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:e.jsx("path",{d:"M12 5V19M5 12H19",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),d&&e.jsx("button",{className:b.actionButton,onClick:d,"aria-label":"Close chat",type:"button",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:e.jsx("path",{d:"M6 18L18 6M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]}),!g&&e.jsxs("div",{className:b.welcomeText,children:[e.jsx("h1",{className:b.title,children:l}),o&&e.jsx("p",{className:b.subtitle,children:o})]})]})]})},Me="_messageWrapper_c86gj_1",Te="_user_c86gj_19",We="_assistant_c86gj_24",De="_avatar_c86gj_28",Pe="_avatarPlaceholder_c86gj_43",He="_brainbaseLogo_c86gj_53",Ee="_messageBubble_c86gj_58",Ve="_error_c86gj_76",Ae="_content_c86gj_81",Re="_cursor_c86gj_88",ze="_errorIndicator_c86gj_107",v={messageWrapper:Me,user:Te,assistant:We,avatar:De,avatarPlaceholder:Pe,brainbaseLogo:He,messageBubble:Ee,error:Ve,content:Ae,cursor:Re,errorIndicator:ze},ae=({message:s,agentName:t,agentLogoUrl:n})=>{const r=s.role==="user",d=s.status==="streaming",u=s.status==="error";return e.jsxs("div",{className:`${v.messageWrapper} ${r?v.user:v.assistant}`,children:[!r&&e.jsx("div",{className:v.avatar,children:n?e.jsx("img",{src:n,alt:t||"AI"}):e.jsx("div",{className:v.avatarPlaceholder,children:e.jsx(z,{className:v.brainbaseLogo,color:"white",cutoutColor:"var(--bb-primary-color)"})})}),e.jsxs("div",{className:`${v.messageBubble} ${u?v.error:""}`,role:"article","aria-label":`${r?"Your message":`${t||"AI"} says`}`,children:[e.jsxs("div",{className:v.content,children:[s.content,d&&e.jsx("span",{className:v.cursor})]}),u&&e.jsxs("div",{className:v.errorIndicator,children:[e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2"}),e.jsx("path",{d:"M12 8V12M12 16H12.01",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),e.jsx("span",{children:"Failed to send"})]})]})]})},Oe="_toolCall_1wby1_1",Fe="_iconWrapper_1wby1_24",Ue="_spinner_1wby1_33",qe="_checkIcon_1wby1_48",Ze="_errorIcon_1wby1_54",Ke="_content_1wby1_60",Ge="_label_1wby1_66",Je="_name_1wby1_73",Ye="_pending_1wby1_78",Xe="_completed_1wby1_82",Qe="_error_1wby1_54",I={toolCall:Oe,iconWrapper:Fe,spinner:Ue,checkIcon:qe,errorIcon:Ze,content:Ke,label:Ge,name:Je,pending:Ye,completed:Xe,error:Qe},ce=({toolCall:s})=>{const t=s.status==="pending"||s.status==="executing",n=s.status==="completed",r=s.status==="error",d=u=>u.replace(/_/g," ").replace(/([A-Z])/g," $1").trim().toLowerCase().replace(/^./,c=>c.toUpperCase());return e.jsxs("div",{className:`${I.toolCall} ${t?I.pending:""} ${n?I.completed:""} ${r?I.error:""}`,children:[e.jsx("div",{className:I.iconWrapper,children:t?e.jsx("div",{className:I.spinner}):n?e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:I.checkIcon,children:e.jsx("path",{d:"M20 6L9 17L4 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:I.errorIcon,children:e.jsx("path",{d:"M6 18L18 6M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),e.jsxs("div",{className:I.content,children:[e.jsx("span",{className:I.label,children:t?"Running":n?"Completed":"Failed"}),e.jsx("span",{className:I.name,children:d(s.name)})]})]})},et="_wrapper_10rss_2",tt="_avatar_10rss_22",st="_avatarPlaceholder_10rss_37",ot="_brainbaseLogo_10rss_47",nt="_bubble_10rss_52",rt="_dot_10rss_63",S={wrapper:et,avatar:tt,avatarPlaceholder:st,brainbaseLogo:ot,bubble:nt,dot:rt},ie=({agentName:s="AI",agentLogoUrl:t})=>e.jsxs("div",{className:S.wrapper,role:"status","aria-label":`${s} is typing`,children:[e.jsx("div",{className:S.avatar,children:t?e.jsx("img",{src:t,alt:s}):e.jsx("div",{className:S.avatarPlaceholder,children:e.jsx(z,{className:S.brainbaseLogo,color:"white",cutoutColor:"var(--bb-primary-color)"})})}),e.jsxs("div",{className:S.bubble,children:[e.jsx("span",{className:S.dot}),e.jsx("span",{className:S.dot}),e.jsx("span",{className:S.dot})]})]}),at="_messageList_241kk_1",ct="_emptyState_241kk_29",it="_emptyIcon_241kk_40",lt="_emptyText_241kk_52",Z={messageList:at,emptyState:ct,emptyIcon:it,emptyText:lt},le=({messages:s,toolCalls:t,isLoading:n,agentName:r,agentLogoUrl:d})=>{var l;const u=i.useRef(null),c=i.useRef(null);i.useEffect(()=>{var o;(o=c.current)==null||o.scrollIntoView({behavior:"smooth"})},[s,t,n]);const g=t.filter(o=>o.status==="pending"||o.status==="executing");return e.jsxs("div",{className:Z.messageList,ref:u,role:"log","aria-live":"polite",children:[s.length===0&&!n&&e.jsxs("div",{className:Z.emptyState,children:[e.jsx("div",{className:Z.emptyIcon,children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:e.jsx("path",{d:"M8 12H8.01M12 12H12.01M16 12H16.01M21 12C21 16.4183 16.9706 20 12 20C10.4607 20 9.01172 19.6565 7.74467 19.0511L3 20L4.39499 16.28C3.51156 15.0423 3 13.5743 3 12C3 7.58172 7.02944 4 12 4C16.9706 4 21 7.58172 21 12Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),e.jsx("p",{className:Z.emptyText,children:"Start a conversation"})]}),s.map(o=>e.jsx(ae,{message:o,agentName:r,agentLogoUrl:d},o.id)),g.map(o=>e.jsx(ce,{toolCall:o},o.id)),n&&((l=s[s.length-1])==null?void 0:l.role)==="user"&&e.jsx(ie,{agentName:r,agentLogoUrl:d}),e.jsx("div",{ref:c})]})},dt="_inputWrapper_5lgg7_1",ut="_inputContainer_5lgg7_7",gt="_textarea_5lgg7_23",mt="_sendButton_5lgg7_50",pt="_hint_5lgg7_89",R={inputWrapper:dt,inputContainer:ut,textarea:gt,sendButton:mt,hint:pt},de=({onSend:s,disabled:t=!1,placeholder:n="Send a message..."})=>{const[r,d]=i.useState(""),u=i.useRef(null),c=i.useCallback(()=>{const o=u.current;o&&(o.style.height="auto",o.style.height=`${Math.min(o.scrollHeight,150)}px`)},[]);i.useEffect(()=>{c()},[r,c]);const g=i.useCallback(o=>{o==null||o.preventDefault();const y=r.trim();y&&!t&&(s(y),d(""),u.current&&(u.current.style.height="auto"))},[r,t,s]),l=i.useCallback(o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),g())},[g]);return e.jsxs("form",{className:R.inputWrapper,onSubmit:g,children:[e.jsxs("div",{className:R.inputContainer,children:[e.jsx("textarea",{ref:u,className:R.textarea,value:r,onChange:o=>d(o.target.value),onKeyDown:l,placeholder:n,disabled:t,rows:1,"aria-label":"Message input"}),e.jsx("button",{type:"submit",className:R.sendButton,disabled:t||!r.trim(),"aria-label":"Send message",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:e.jsx("path",{d:"M22 2L11 13M22 2L15 22L11 13M22 2L2 9L11 13",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),e.jsxs("div",{className:R.hint,children:["Press ",e.jsx("kbd",{children:"Enter"})," to send, ",e.jsx("kbd",{children:"Shift + Enter"})," for new line"]})]})},ht="_poweredBy_9jh5q_1",_t="_logo_9jh5q_20",ft="_poweredText_9jh5q_24",xt="_text_9jh5q_36",K={poweredBy:ht,logo:_t,poweredText:ft,text:xt},bt=({className:s})=>e.jsxs("svg",{className:s,viewBox:"0 0 800 800",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H788C794.627 400 800 405.373 800 412V740C800 773.137 773.137 800 740 800H412C405.373 800 400 794.627 400 788V412Z",fill:"currentColor"}),e.jsx("circle",{cx:"400",cy:"400",r:"400",fill:"currentColor"}),e.jsx("path",{d:"M0 60C0 26.8629 26.8629 0 60 0H397.614C398.932 0 400 1.06811 400 2.38569V2.38569C400 221.982 221.982 400 2.38569 400V400C1.06811 400 0 398.932 0 397.614V60Z",fill:"currentColor"}),e.jsx("path",{d:"M400 412C400 405.373 405.373 400 412 400H738C744.627 400 750 405.373 750 412V725C750 738.807 738.807 750 725 750H412C405.373 750 400 744.627 400 738V412Z",fill:"currentColor"}),e.jsx("circle",{cx:"400",cy:"400",r:"350",fill:"currentColor"}),e.jsx("path",{d:"M50 75C50 61.1929 61.1929 50 75 50H388C394.627 50 400 55.3726 400 62V388C400 394.627 394.627 400 388 400H62C55.3726 400 50 394.627 50 388V75Z",fill:"currentColor"}),e.jsx("rect",{x:"399.919",y:"209",width:"270",height:"270",rx:"12",transform:"rotate(45 399.919 209)",fill:"var(--bb-surface-bg, #ffffff)"})]}),wt=({showBranding:s=!0})=>s?e.jsxs("a",{href:"https://brainbaselabs.com/",target:"_blank",rel:"noopener noreferrer",className:K.poweredBy,"aria-label":"Powered by Brainbase Labs",children:[e.jsx("span",{className:K.poweredText,children:"Powered by"}),e.jsx(bt,{className:K.logo}),e.jsx("span",{className:K.text,children:"Brainbase Labs"})]}):null,yt="_container_m2o9l_1",jt="_body_m2o9l_26",Ct="_confirmationOverlay_m2o9l_35",kt="_confirmationDialog_m2o9l_56",vt="_confirmationText_m2o9l_78",It="_confirmationButtons_m2o9l_86",Nt="_cancelButton_m2o9l_91",Lt="_confirmButton_m2o9l_92",M={container:yt,body:jt,confirmationOverlay:Ct,confirmationDialog:kt,confirmationText:vt,confirmationButtons:It,cancelButton:Nt,confirmButton:Lt},ue=({config:s,messages:t,toolCalls:n,isLoading:r,onSendMessage:d,onClose:u,onNewChat:c})=>{var k;const[g,l]=i.useState(!1),o=t.length>0,y=()=>{l(!0)},B=()=>{l(!1),c==null||c()},P=()=>{l(!1)};return e.jsxs("div",{className:M.container,role:"dialog","aria-label":"Chat window",children:[e.jsx(re,{agentName:s.agentName,agentLogoUrl:s.agentLogoUrl,welcomeTitle:s.welcomeMessage||"Hello there.",welcomeSubtitle:s.welcomeMessage?void 0:"How can we help?",onClose:u,onNewChatRequest:y,showNewChatButton:o,compact:o}),e.jsxs("div",{className:M.body,children:[e.jsx(le,{messages:t,toolCalls:n,isLoading:r,agentName:s.agentName,agentLogoUrl:s.agentLogoUrl}),e.jsx(de,{onSend:d,disabled:r,placeholder:"Ask a question..."})]}),e.jsx(wt,{showBranding:((k=s.styling)==null?void 0:k.showBranding)??!0}),g&&e.jsx("div",{className:M.confirmationOverlay,children:e.jsxs("div",{className:M.confirmationDialog,children:[e.jsx("p",{className:M.confirmationText,children:"End current chat and start a new conversation?"}),e.jsxs("div",{className:M.confirmationButtons,children:[e.jsx("button",{className:M.cancelButton,onClick:P,type:"button",children:"Cancel"}),e.jsx("button",{className:M.confirmButton,onClick:B,type:"button",children:"End Chat"})]})]})})]})},Bt="_toggleButton_11dqz_1",$t="_icon_11dqz_31",St="_agentLogo_11dqz_36",Mt="_unreadBadge_11dqz_43",G={toggleButton:Bt,icon:$t,agentLogo:St,unreadBadge:Mt},X=({onClick:s,agentLogoUrl:t,unreadCount:n=0})=>e.jsxs("button",{className:G.toggleButton,onClick:s,"aria-label":"Open chat",type:"button",children:[t?e.jsx("img",{src:t,alt:"",className:G.agentLogo}):e.jsx("svg",{className:G.icon,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M8 12H8.01M12 12H12.01M16 12H16.01M21 12C21 16.4183 16.9706 20 12 20C10.4607 20 9.01172 19.6565 7.74467 19.0511L3 20L4.39499 16.28C3.51156 15.0423 3 13.5743 3 12C3 7.58172 7.02944 4 12 4C16.9706 4 21 7.58172 21 12Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),n>0&&e.jsx("span",{className:G.unreadBadge,children:n>9?"9+":n})]}),Tt="_container_kgfgt_1",Wt="_header_kgfgt_25",Dt="_logoWrapper_kgfgt_38",Pt="_logo_kgfgt_38",Ht="_closeButton_kgfgt_51",Et="_content_kgfgt_74",Vt="_iconWrapper_kgfgt_84",At="_errorIcon_kgfgt_95",Rt="_title_kgfgt_101",zt="_description_kgfgt_109",Ot="_retryButton_kgfgt_117",Ft="_footer_kgfgt_139",Ut="_poweredBy_kgfgt_146",qt="_footerLogo_kgfgt_160",w={container:Tt,header:Wt,logoWrapper:Dt,logo:Pt,closeButton:Ht,content:Et,iconWrapper:Vt,errorIcon:At,title:Rt,description:zt,retryButton:Ot,footer:Ft,poweredBy:Ut,footerLogo:qt},Zt=({errorType:s,message:t,onRetry:n,onClose:r})=>{const d=()=>{switch(s){case"not_found":return{title:"Chat Not Found",description:t||"This chat widget is not configured correctly. Please check the embed ID.",icon:e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:w.errorIcon,children:[e.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("path",{d:"M12 7V13M12 16V16.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})};case"network":return{title:"Connection Error",description:t||"Unable to connect to the chat service. Please check your internet connection.",icon:e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",className:w.errorIcon,children:[e.jsx("path",{d:"M12 21C16.9706 21 21 16.9706 21 12C21 7.02944 16.9706 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21Z",stroke:"currentColor",strokeWidth:"1.5"}),e.jsx("path",{d:"M8 15L16 9M8 9L16 15",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})};default:return{title:"Something Went Wrong",description:t||"An unexpected error occurred. Please try again later.",icon:e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",className:w.errorIcon,children:e.jsx("path",{d:"M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}}},{title:u,description:c,icon:g}=d();return e.jsxs("div",{className:w.container,children:[e.jsxs("div",{className:w.header,children:[e.jsx("div",{className:w.logoWrapper,children:e.jsx(z,{className:w.logo,color:"white",cutoutColor:"var(--bb-primary-color)"})}),r&&e.jsx("button",{className:w.closeButton,onClick:r,"aria-label":"Close",type:"button",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:e.jsx("path",{d:"M6 18L18 6M6 6L18 18",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),e.jsxs("div",{className:w.content,children:[e.jsx("div",{className:w.iconWrapper,children:g}),e.jsx("h2",{className:w.title,children:u}),e.jsx("p",{className:w.description,children:c}),n&&e.jsx("button",{className:w.retryButton,onClick:n,type:"button",children:"Try Again"})]}),e.jsx("div",{className:w.footer,children:e.jsxs("a",{href:"https://brainbaselabs.com",target:"_blank",rel:"noopener noreferrer",className:w.poweredBy,children:["Powered by"," ",e.jsx(z,{className:w.footerLogo,color:"var(--bb-text-tertiary)",cutoutColor:"var(--bb-surface-bg)"}),e.jsx("span",{children:"Brainbase Labs"})]})})]})},Kt="_widget_1ehud_1",Gt="_inline_1ehud_25",D={widget:Kt,"bottom-right":"_bottom-right_1ehud_10","bottom-left":"_bottom-left_1ehud_17",inline:Gt},Jt="https://whatsapp-based-server.onrender.com",Yt=({embedId:s,apiBaseUrl:t=Jt,mockMode:n=!1,mockResponses:r,position:d="bottom-right",defaultOpen:u=!1,primaryColor:c,agentName:g,welcomeMessage:l,className:o,onSessionStart:y,onSessionEnd:B,onMessage:P,onError:k})=>{const[O,W]=i.useState(u),[m,T]=i.useState(null),[$,H]=i.useState(!0),[F,N]=i.useState(null),[U,q]=i.useState(),E=i.useMemo(()=>n?ne({primaryColor:c,agentName:g,welcomeMessage:l},r):oe(t),[n,c,g,l,r,t]),V=i.useCallback(async()=>{H(!0),N(null),q(void 0);try{const C=await E.getDeploymentConfig(s);T({...C,primaryColor:c??C.primaryColor,agentName:g??C.agentName,welcomeMessage:l??C.welcomeMessage})}catch(C){const L=C instanceof Error?C:new Error("Failed to load config");L.message.includes("404")?(N("not_found"),q("The chat widget with this embed ID was not found.")):L.message.includes("Failed to fetch")||L.message.includes("network")?N("network"):N("unknown"),n&&(T({embedId:s,deploymentId:"mock-deployment",workerId:"mock-worker",flowId:"mock-flow",primaryColor:c??"#1a1a2e",agentName:g??"AI Assistant"}),N(null)),k==null||k(L)}finally{H(!1)}},[s,n,E,c,g,l,k]);i.useEffect(()=>{V()},[V]);const _=i.useMemo(()=>m||{embedId:s,deploymentId:"",workerId:"",flowId:"",primaryColor:c,agentName:g,welcomeMessage:l},[m,s,c,g,l]),x=se({config:_,apiClient:E,mockMode:n,onSessionStart:y,onSessionEnd:B,onMessage:P,onError:k}),j=i.useMemo(()=>({"--bb-primary-color":(m==null?void 0:m.primaryColor)??c??"#1a1a2e"}),[m==null?void 0:m.primaryColor,c]),p=()=>{x.endSession(),x.startNewSession()},h=()=>{W(!1)},a=()=>{V()},f=d==="inline";return $?null:F&&!n?!f&&!O?e.jsx("div",{className:`${D.widget} ${D[d]} ${o??""}`,style:j,children:e.jsx(X,{onClick:()=>W(!0),agentName:g})}):e.jsx("div",{className:`${D.widget} ${D[d]} ${o??""}`,style:j,children:e.jsx(Zt,{errorType:F,message:U,onRetry:a,onClose:f?void 0:h})}):e.jsx("div",{className:`${D.widget} ${D[d]} ${o??""}`,style:j,children:O||f?e.jsx(ue,{config:_,messages:x.messages,toolCalls:x.toolCalls,isLoading:x.isLoading,onSendMessage:x.sendMessage,onClose:f?void 0:h,onNewChat:p}):e.jsx(X,{onClick:()=>W(!0),agentName:m==null?void 0:m.agentName,agentLogoUrl:m==null?void 0:m.agentLogoUrl})})};function Xt(){if(typeof crypto<"u"&&crypto.randomUUID)return`bb-${crypto.randomUUID()}`;const s=Date.now().toString(36),t=Math.random().toString(36).substring(2,15),n=Math.random().toString(36).substring(2,15);return`bb-${s}-${t}${n}`}exports.ChatContainer=ue;exports.ChatHeader=re;exports.ChatToggleButton=X;exports.ChatWidget=Yt;exports.Message=ae;exports.MessageInput=de;exports.MessageList=le;exports.ToolCallDisplay=ce;exports.TypingIndicator=ie;exports.clearSession=Y;exports.createAPIClient=oe;exports.createMockAPIClient=ne;exports.generateSessionId=Xt;exports.getStoredSession=te;exports.storeSession=J;exports.useChat=se;
@@ -0,0 +1,230 @@
1
+ import { default as default_2 } from 'react';
2
+
3
+ export declare interface BrainbaseAPIClient {
4
+ getDeploymentConfig(embedId: string): Promise<DeploymentConfig>;
5
+ sendMessage(params: SendMessageParams): Promise<ReadableStream<Uint8Array>>;
6
+ }
7
+
8
+ export declare const ChatContainer: default_2.FC<ChatContainerProps>;
9
+
10
+ declare interface ChatContainerProps {
11
+ config: DeploymentConfig;
12
+ messages: MessageType[];
13
+ toolCalls: ToolCall[];
14
+ isLoading: boolean;
15
+ onSendMessage: (message: string) => void;
16
+ onClose?: () => void;
17
+ onNewChat?: () => void;
18
+ }
19
+
20
+ export declare const ChatHeader: default_2.FC<ChatHeaderProps>;
21
+
22
+ declare interface ChatHeaderProps {
23
+ agentName?: string;
24
+ agentLogoUrl?: string;
25
+ welcomeTitle?: string;
26
+ welcomeSubtitle?: string;
27
+ onClose?: () => void;
28
+ onNewChatRequest?: () => void;
29
+ showNewChatButton?: boolean;
30
+ /** When true, shows a compact header without welcome text */
31
+ compact?: boolean;
32
+ }
33
+
34
+ export declare const ChatToggleButton: default_2.FC<ChatToggleButtonProps>;
35
+
36
+ declare interface ChatToggleButtonProps {
37
+ onClick: () => void;
38
+ agentName?: string;
39
+ agentLogoUrl?: string;
40
+ unreadCount?: number;
41
+ }
42
+
43
+ export declare const ChatWidget: default_2.FC<ChatWidgetProps>;
44
+
45
+ export declare interface ChatWidgetProps {
46
+ /** The embed ID from your Brainbase deployment */
47
+ embedId: string;
48
+ /** API base URL (defaults to production) */
49
+ apiBaseUrl?: string;
50
+ /** Enable mock mode for UI development */
51
+ mockMode?: boolean;
52
+ /** Custom mock responses for mock mode */
53
+ mockResponses?: MockResponse[];
54
+ /** Position of the widget */
55
+ position?: 'bottom-right' | 'bottom-left' | 'inline';
56
+ /** Whether widget starts open */
57
+ defaultOpen?: boolean;
58
+ /** Override primary color */
59
+ primaryColor?: string;
60
+ /** Override agent name */
61
+ agentName?: string;
62
+ /** Override welcome message */
63
+ welcomeMessage?: string;
64
+ /** Custom CSS class */
65
+ className?: string;
66
+ /** Callback when session starts */
67
+ onSessionStart?: (sessionId: string) => void;
68
+ /** Callback when session ends */
69
+ onSessionEnd?: (session: Session) => void;
70
+ /** Callback on message received */
71
+ onMessage?: (message: MessageType) => void;
72
+ /** Callback on error */
73
+ onError?: (error: Error) => void;
74
+ }
75
+
76
+ export declare function clearSession(embedId: string): void;
77
+
78
+ export declare function createAPIClient(engineBaseUrl?: string): BrainbaseAPIClient;
79
+
80
+ export declare function createMockAPIClient(customConfig?: Partial<DeploymentConfig>, customResponses?: MockResponse[]): MockAPIClient;
81
+
82
+ export declare interface DeploymentConfig {
83
+ embedId: string;
84
+ deploymentId: string;
85
+ workerId: string;
86
+ flowId: string;
87
+ welcomeMessage?: string;
88
+ agentName?: string;
89
+ agentLogoUrl?: string;
90
+ primaryColor?: string;
91
+ styling?: Record<string, unknown>;
92
+ }
93
+
94
+ /**
95
+ * Generates a unique session ID using crypto API when available,
96
+ * with fallback to timestamp + random string
97
+ */
98
+ export declare function generateSessionId(): string;
99
+
100
+ export declare function getStoredSession(embedId: string): Session | null;
101
+
102
+ export declare const Message: default_2.FC<MessageProps>;
103
+
104
+ export declare const MessageInput: default_2.FC<MessageInputProps>;
105
+
106
+ declare interface MessageInputProps {
107
+ onSend: (message: string) => void;
108
+ disabled?: boolean;
109
+ placeholder?: string;
110
+ }
111
+
112
+ export declare const MessageList: default_2.FC<MessageListProps>;
113
+
114
+ declare interface MessageListProps {
115
+ messages: MessageType[];
116
+ toolCalls: ToolCall[];
117
+ isLoading: boolean;
118
+ agentName?: string;
119
+ agentLogoUrl?: string;
120
+ }
121
+
122
+ declare interface MessageProps {
123
+ message: MessageType;
124
+ agentName?: string;
125
+ agentLogoUrl?: string;
126
+ }
127
+
128
+ export declare type MessageRole = 'user' | 'assistant' | 'system';
129
+
130
+ export declare type MessageStatus = 'sending' | 'sent' | 'streaming' | 'error';
131
+
132
+ export declare interface MessageType {
133
+ id: string;
134
+ role: MessageRole;
135
+ content: string;
136
+ timestamp: number;
137
+ status?: MessageStatus;
138
+ }
139
+
140
+ export declare interface MockAPIClient {
141
+ getDeploymentConfig(embedId: string): Promise<DeploymentConfig>;
142
+ sendMessage(message: string): AsyncGenerator<SSEEvent>;
143
+ }
144
+
145
+ export declare interface MockResponse {
146
+ trigger: string | RegExp;
147
+ response: string;
148
+ delay?: number;
149
+ toolCalls?: Array<{
150
+ name: string;
151
+ arguments: Record<string, unknown>;
152
+ result: unknown;
153
+ }>;
154
+ }
155
+
156
+ export declare interface SendMessageParams {
157
+ embedId: string;
158
+ message: string;
159
+ sessionId?: string;
160
+ metadata?: Record<string, unknown>;
161
+ }
162
+
163
+ export declare interface Session {
164
+ sessionId: string;
165
+ deploymentId: string;
166
+ workerId: string;
167
+ flowId: string;
168
+ startTime: number;
169
+ messages: MessageType[];
170
+ toolCalls: ToolCall[];
171
+ status: 'active' | 'completed' | 'error';
172
+ }
173
+
174
+ export declare interface SSEEvent {
175
+ type: SSEEventType;
176
+ data: unknown;
177
+ timestamp?: number;
178
+ }
179
+
180
+ export declare type SSEEventType = 'session' | 'message' | 'tool_call' | 'waiting' | 'done' | 'completed' | 'error';
181
+
182
+ export declare function storeSession(embedId: string, session: Session): void;
183
+
184
+ export declare interface ToolCall {
185
+ id: string;
186
+ name: string;
187
+ arguments: Record<string, unknown>;
188
+ result?: unknown;
189
+ status: 'pending' | 'executing' | 'completed' | 'error';
190
+ timestamp: number;
191
+ }
192
+
193
+ export declare const ToolCallDisplay: default_2.FC<ToolCallDisplayProps>;
194
+
195
+ declare interface ToolCallDisplayProps {
196
+ toolCall: ToolCall;
197
+ }
198
+
199
+ export declare const TypingIndicator: default_2.FC<TypingIndicatorProps>;
200
+
201
+ declare interface TypingIndicatorProps {
202
+ agentName?: string;
203
+ agentLogoUrl?: string;
204
+ }
205
+
206
+ export declare function useChat(options: UseChatOptions): UseChatReturn;
207
+
208
+ declare interface UseChatOptions {
209
+ config: DeploymentConfig;
210
+ apiClient: BrainbaseAPIClient | MockAPIClient;
211
+ mockMode?: boolean;
212
+ onSessionStart?: (sessionId: string) => void;
213
+ onSessionEnd?: (session: Session) => void;
214
+ onMessage?: (message: MessageType) => void;
215
+ onError?: (error: Error) => void;
216
+ }
217
+
218
+ export declare interface UseChatReturn {
219
+ messages: MessageType[];
220
+ toolCalls: ToolCall[];
221
+ isLoading: boolean;
222
+ error: Error | null;
223
+ sessionId: string | null;
224
+ sendMessage: (content: string) => Promise<void>;
225
+ endSession: () => Promise<void>;
226
+ clearMessages: () => void;
227
+ startNewSession: () => Promise<string>;
228
+ }
229
+
230
+ export { }