@botzki/react 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,409 @@
1
+ import * as React from 'react';
2
+ import React__default from 'react';
3
+ import { Citation, ChatResponse, Botzki, BotzkiUser, WidgetOptions } from '@botzki/js';
4
+ export { BotzkiConfig, BotzkiUser, ChatOptions, ChatResponse, Citation, WidgetOptions } from '@botzki/js';
5
+
6
+ /**
7
+ * Message representation inside React chat interfaces.
8
+ */
9
+ interface BotzkiMessage {
10
+ id: string;
11
+ role: "user" | "assistant" | "system";
12
+ content: string;
13
+ createdAt: Date;
14
+ citations?: Citation[];
15
+ isStreaming?: boolean;
16
+ error?: string;
17
+ }
18
+ /**
19
+ * Configuration options for the `useChat` hook.
20
+ */
21
+ interface UseChatOptions {
22
+ /**
23
+ * Target bot identifier. Inherited from `<BotzkiProvider>` if omitted.
24
+ */
25
+ botId?: string;
26
+ /**
27
+ * Publishable API key. Inherited from `<BotzkiProvider>` if omitted.
28
+ */
29
+ publishableKey?: string;
30
+ /**
31
+ * Custom backend API base URL (e.g. for local development or custom proxy).
32
+ */
33
+ baseUrl?: string;
34
+ /**
35
+ * Alias for `baseUrl`.
36
+ */
37
+ apiHost?: string;
38
+ /**
39
+ * Unique session identifier. Auto-generated and persisted if omitted.
40
+ */
41
+ sessionId?: string;
42
+ /**
43
+ * Initial messages to preload into the conversation.
44
+ */
45
+ initialMessages?: BotzkiMessage[];
46
+ /**
47
+ * Whether to persist the conversation and session in browser localStorage.
48
+ * @default true
49
+ */
50
+ persistSession?: boolean;
51
+ /**
52
+ * Custom localStorage key prefix for session and message caching.
53
+ */
54
+ storageKey?: string;
55
+ /**
56
+ * Preferred ISO 639-1 language code (e.g. 'en', 'es', 'de').
57
+ */
58
+ language?: string;
59
+ /**
60
+ * Whether to stream answers in real-time token-by-token.
61
+ * @default true
62
+ */
63
+ stream?: boolean;
64
+ /**
65
+ * Callback fired whenever a full response is received from the bot.
66
+ */
67
+ onResponse?: (response: ChatResponse) => void;
68
+ /**
69
+ * Callback fired when a message turn finishes (streaming completed).
70
+ */
71
+ onFinish?: (message: BotzkiMessage) => void;
72
+ /**
73
+ * Callback fired when an error occurs during message transmission.
74
+ */
75
+ onError?: (error: Error) => void;
76
+ }
77
+ /**
78
+ * Return type and state of the `useChat` hook.
79
+ */
80
+ interface UseChatReturn {
81
+ /**
82
+ * Array of conversation messages in chronological order.
83
+ */
84
+ messages: BotzkiMessage[];
85
+ /**
86
+ * Current text in the input box.
87
+ */
88
+ input: string;
89
+ /**
90
+ * Sets input box value manually.
91
+ */
92
+ setInput: (value: string) => void;
93
+ /**
94
+ * Standard React onChange handler for input and textarea elements.
95
+ */
96
+ handleInputChange: (e: React__default.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
97
+ /**
98
+ * Form submission handler. Submits current `input` and clears the input box.
99
+ */
100
+ handleSubmit: (e?: React__default.FormEvent, options?: {
101
+ imageBase64?: string;
102
+ imageMimeType?: string;
103
+ }) => Promise<void>;
104
+ /**
105
+ * Programmatically sends a message with optional image attachment.
106
+ */
107
+ sendMessage: (content: string, options?: {
108
+ imageBase64?: string;
109
+ imageMimeType?: string;
110
+ }) => Promise<void>;
111
+ /**
112
+ * Appends a message to the conversation history without triggering an API call.
113
+ */
114
+ append: (message: Partial<BotzkiMessage> & {
115
+ content: string;
116
+ }) => void;
117
+ /**
118
+ * Re-sends the last user message to regenerate the assistant response.
119
+ */
120
+ reload: () => Promise<void>;
121
+ /**
122
+ * Aborts the active streaming generation immediately.
123
+ */
124
+ stop: () => void;
125
+ /**
126
+ * Clears the current conversation history.
127
+ */
128
+ clearMessages: () => void;
129
+ /**
130
+ * Direct state setter for messages array.
131
+ */
132
+ setMessages: React__default.Dispatch<React__default.SetStateAction<BotzkiMessage[]>>;
133
+ /**
134
+ * True if waiting for a response or streaming tokens.
135
+ */
136
+ isLoading: boolean;
137
+ /**
138
+ * True specifically when tokens are actively streaming in.
139
+ */
140
+ isStreaming: boolean;
141
+ /**
142
+ * Error object if the last operation failed, or null.
143
+ */
144
+ error: Error | null;
145
+ /**
146
+ * Active conversation session identifier.
147
+ */
148
+ sessionId: string;
149
+ /**
150
+ * Sets or updates active conversation session identifier.
151
+ */
152
+ setSessionId: (id: string) => void;
153
+ }
154
+ /**
155
+ * Properties for `<BotzkiProvider>`.
156
+ */
157
+ interface BotzkiProviderProps {
158
+ /**
159
+ * Target bot identifier.
160
+ */
161
+ botId: string;
162
+ /**
163
+ * Publishable API key (`botz_pk_live_...`). Safe to expose in frontend bundles.
164
+ */
165
+ publishableKey: string;
166
+ /**
167
+ * Optional custom backend API base URL (defaults to https://api.botzki.com).
168
+ */
169
+ baseUrl?: string;
170
+ /**
171
+ * Alias for `baseUrl`.
172
+ */
173
+ apiHost?: string;
174
+ /**
175
+ * Optional visitor user details to identify customer sessions.
176
+ */
177
+ user?: BotzkiUser;
178
+ /**
179
+ * Optional persistent session ID. Auto-generated if omitted.
180
+ */
181
+ defaultSessionId?: string;
182
+ /**
183
+ * Optional pre-instantiated Botzki client instance.
184
+ */
185
+ client?: Botzki;
186
+ /**
187
+ * React tree to wrap with Botzki context.
188
+ */
189
+ children: React__default.ReactNode;
190
+ }
191
+ /**
192
+ * Value exposed by the Botzki React Context.
193
+ */
194
+ interface BotzkiContextValue {
195
+ client: Botzki;
196
+ botId: string;
197
+ publishableKey: string;
198
+ baseUrl: string;
199
+ apiHost: string;
200
+ user?: BotzkiUser;
201
+ sessionId: string;
202
+ setSessionId: (id: string) => void;
203
+ }
204
+ /**
205
+ * Imperative handle exposed via React ref for `<BotzkiWidget />`.
206
+ */
207
+ interface BotzkiWidgetRef {
208
+ /** Opens the floating chat popup */
209
+ open: () => void;
210
+ /** Closes the floating chat popup */
211
+ close: () => void;
212
+ /** Toggles open / close state */
213
+ toggle: () => void;
214
+ /** Returns true if the chat popup is currently open */
215
+ isOpen: () => boolean;
216
+ /** Shows the floating launcher bubble */
217
+ show: () => void;
218
+ /** Hides the floating launcher bubble */
219
+ hide: () => void;
220
+ /** Sends a message programmatically through the widget */
221
+ sendMessage: (message: string, imageBase64?: string) => Promise<void>;
222
+ /** Clears widget chat history */
223
+ clearMessages: () => void;
224
+ /** Dynamically updates widget theme */
225
+ setTheme: (theme: "light" | "dark" | "auto") => void;
226
+ /** Dynamically updates widget primary accent color */
227
+ setPrimaryColor: (color: string) => void;
228
+ /** Updates identified visitor details */
229
+ setUser: (user: BotzkiUser) => void;
230
+ }
231
+ /**
232
+ * Props for `<BotzkiWidget />`.
233
+ */
234
+ interface BotzkiWidgetProps extends WidgetOptions {
235
+ /**
236
+ * Optional bot ID. If omitted, uses value from `<BotzkiProvider>`.
237
+ */
238
+ botId?: string;
239
+ /**
240
+ * Optional publishable key. If omitted, uses value from `<BotzkiProvider>`.
241
+ */
242
+ publishableKey?: string;
243
+ /**
244
+ * Optional custom base URL.
245
+ */
246
+ baseUrl?: string;
247
+ /**
248
+ * Optional visitor details.
249
+ */
250
+ user?: BotzkiUser;
251
+ /**
252
+ * Callback fired when the widget chat window opens.
253
+ */
254
+ onOpen?: () => void;
255
+ /**
256
+ * Callback fired when the widget chat window closes.
257
+ */
258
+ onClose?: () => void;
259
+ }
260
+
261
+ /**
262
+ * Root context provider for Botzki AI. Wraps your React component tree and shares
263
+ * client instances and configuration with all child hooks and components.
264
+ */
265
+ declare function BotzkiProvider({ botId, publishableKey, baseUrl, apiHost, user, defaultSessionId, client: customClient, children, }: BotzkiProviderProps): React.JSX.Element;
266
+ /**
267
+ * Hook to access the current Botzki context value (client instance, botId, sessionId).
268
+ * Throws a helpful error if used outside a `<BotzkiProvider>`.
269
+ */
270
+ declare function useBotzki(): BotzkiContextValue;
271
+ /**
272
+ * Optional hook to access the Botzki context, returning null instead of throwing
273
+ * if called outside `<BotzkiProvider>`. Useful for components that can be used standalone.
274
+ */
275
+ declare function useOptionalBotzki(): BotzkiContextValue | null;
276
+
277
+ /**
278
+ * Drop-in floating chat widget component for React.
279
+ * Handles automatic lifecycle management, React StrictMode safety, dynamic theme/color updates,
280
+ * and imperative control via forwarded ref.
281
+ */
282
+ declare const BotzkiWidget: React.ForwardRefExoticComponent<BotzkiWidgetProps & React.RefAttributes<BotzkiWidgetRef>>;
283
+
284
+ interface BotzkiChatProps extends UseChatOptions {
285
+ /**
286
+ * Title shown in the chat window header. Defaults to bot name or "AI Assistant".
287
+ */
288
+ title?: string;
289
+ /**
290
+ * Subtitle shown in the chat window header. Defaults to "Online".
291
+ */
292
+ subtitle?: string;
293
+ /**
294
+ * Welcome greeting when conversation starts.
295
+ */
296
+ greeting?: string;
297
+ /**
298
+ * List of clickable starter prompt questions.
299
+ */
300
+ starterQuestions?: string[];
301
+ /**
302
+ * Visual theme ("light" | "dark" | "auto"). Defaults to "auto".
303
+ */
304
+ theme?: "light" | "dark" | "auto";
305
+ /**
306
+ * Primary accent color (hex or rgb). Defaults to "#0ea5e9".
307
+ */
308
+ primaryColor?: string;
309
+ /**
310
+ * Custom CSS class name for the outer container.
311
+ */
312
+ className?: string;
313
+ /**
314
+ * Custom style object for the outer container.
315
+ */
316
+ style?: React__default.CSSProperties;
317
+ /**
318
+ * Placeholder text for the message input.
319
+ */
320
+ placeholder?: string;
321
+ }
322
+ /**
323
+ * Embedded, full-featured AI chat container for dashboards, sidebars, and dedicated support pages.
324
+ * Fully responsive and self-contained with no external CSS dependencies.
325
+ */
326
+ declare function BotzkiChat({ title, subtitle, greeting, starterQuestions, theme, primaryColor, className, style, placeholder, ...chatOptions }: BotzkiChatProps): React__default.JSX.Element;
327
+
328
+ /**
329
+ * Headless React hook for building rich, interactive AI chat interfaces with real-time streaming,
330
+ * session persistence, optimistic UI updates, error recovery, and multimodal support.
331
+ */
332
+ declare function useChat(options?: UseChatOptions): UseChatReturn;
333
+
334
+ interface BotInfoData {
335
+ id?: string;
336
+ name?: string;
337
+ description?: string;
338
+ primaryColor?: string;
339
+ theme?: string;
340
+ avatarUrl?: string;
341
+ greeting?: string;
342
+ starterQuestions?: string[];
343
+ capabilities?: string[];
344
+ [key: string]: unknown;
345
+ }
346
+ interface UseBotInfoReturn {
347
+ data: BotInfoData | null;
348
+ isLoading: boolean;
349
+ error: Error | null;
350
+ refetch: () => Promise<void>;
351
+ }
352
+ /**
353
+ * Hook to retrieve public bot configuration, branding, avatar, and starter questions.
354
+ */
355
+ declare function useBotInfo(): UseBotInfoReturn;
356
+
357
+ interface FeedbackPayload {
358
+ messageId?: string;
359
+ query?: string;
360
+ rating: number;
361
+ comment?: string;
362
+ category?: string;
363
+ }
364
+ interface UseFeedbackReturn {
365
+ submitFeedback: (payload: FeedbackPayload) => Promise<boolean>;
366
+ isSubmitting: boolean;
367
+ isSuccess: boolean;
368
+ error: Error | null;
369
+ reset: () => void;
370
+ }
371
+ /**
372
+ * Hook to submit visitor ratings and feedback on bot answers.
373
+ */
374
+ declare function useFeedback(): UseFeedbackReturn;
375
+
376
+ interface LeadCapturePayload {
377
+ email: string;
378
+ name?: string;
379
+ phone?: string;
380
+ company?: string;
381
+ notes?: string;
382
+ metadata?: Record<string, unknown>;
383
+ customData?: Record<string, unknown>;
384
+ }
385
+ interface UseLeadCaptureReturn {
386
+ captureLead: (payload: LeadCapturePayload) => Promise<boolean>;
387
+ isSubmitting: boolean;
388
+ isSuccess: boolean;
389
+ error: Error | null;
390
+ reset: () => void;
391
+ }
392
+ /**
393
+ * Hook to capture customer lead contact details directly from custom React forms or chat widgets.
394
+ */
395
+ declare function useLeadCapture(): UseLeadCaptureReturn;
396
+
397
+ interface UseVoiceTranscriptionReturn {
398
+ transcribe: (audio: Blob | File) => Promise<string | null>;
399
+ isTranscribing: boolean;
400
+ transcript: string | null;
401
+ error: Error | null;
402
+ reset: () => void;
403
+ }
404
+ /**
405
+ * Hook to transcribe audio recordings directly to text using the Botzki AI audio transcription endpoint.
406
+ */
407
+ declare function useVoiceTranscription(): UseVoiceTranscriptionReturn;
408
+
409
+ export { type BotInfoData, BotzkiChat, type BotzkiChatProps, type BotzkiContextValue, type BotzkiMessage, BotzkiProvider, type BotzkiProviderProps, BotzkiWidget, type BotzkiWidgetProps, type BotzkiWidgetRef, type FeedbackPayload, type LeadCapturePayload, type UseBotInfoReturn, type UseChatOptions, type UseChatReturn, type UseFeedbackReturn, type UseLeadCaptureReturn, type UseVoiceTranscriptionReturn, useBotInfo, useBotzki, useChat, useFeedback, useLeadCapture, useOptionalBotzki, useVoiceTranscription };
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import {createContext,forwardRef,useMemo,useRef,useEffect,useImperativeHandle,useContext,useState,useCallback}from'react';import {Botzki}from'@botzki/js';import {jsx,jsxs}from'react/jsx-runtime';var G=createContext(null);function Q(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"sess_"+Math.random().toString(36).substring(2,11)+"_"+Date.now()}function ge({botId:e,publishableKey:r,baseUrl:f,apiHost:s,user:d,defaultSessionId:n,client:l,children:t}){let i=s||f||"https://api.botzki.com",[a,c]=useState(()=>{if(n)return n;if(typeof window<"u")try{let S=localStorage.getItem(`botzki_session_${e}`);if(S)return S;let U=Q();return localStorage.setItem(`botzki_session_${e}`,U),U}catch{return Q()}return n||Q()}),o=useMemo(()=>l||new Botzki({botId:e,publishableKey:r,apiHost:i}),[l,e,r,i]);useEffect(()=>{d&&o&&o.setUser(d);},[o,d]);let C=useMemo(()=>({client:o,botId:e,publishableKey:r,baseUrl:i,apiHost:i,user:d,sessionId:a,setSessionId:c}),[o,e,r,i,d,a]);return jsx(G.Provider,{value:C,children:t})}function R(){let e=useContext(G);if(!e)throw new Error("useBotzki must be used within a <BotzkiProvider>. Wrap your application or component with <BotzkiProvider botId='...' publishableKey='...'>.");return e}function V(){return useContext(G)}var Be=forwardRef(function(r,f){let s=V(),d=r.botId||s?.botId,n=r.publishableKey||s?.publishableKey,l=r.baseUrl||s?.baseUrl||"https://api.botzki.com",t=useMemo(()=>s?.client&&(!r.botId||r.botId===s.botId)?s.client:d&&n?new Botzki({botId:d,publishableKey:n,apiHost:l}):null,[s?.client,s?.botId,r.botId,d,n,l]),i=useRef(false);return useEffect(()=>{if(!t||typeof window>"u")return;let{botId:a,publishableKey:c,baseUrl:o,user:C,onOpen:S,onClose:U,...v}=r;return t.mount({...v,onOpen:S,onClose:U}),r.user&&t.setUser(r.user),i.current=true,()=>{i.current=false;try{t.unmount();}catch{}}},[t]),useEffect(()=>{t&&i.current&&r.theme&&t.setTheme(r.theme);},[t,r.theme]),useEffect(()=>{t&&i.current&&r.primaryColor&&t.setPrimaryColor(r.primaryColor);},[t,r.primaryColor]),useEffect(()=>{t&&i.current&&r.user&&t.setUser(r.user);},[t,r.user]),useImperativeHandle(f,()=>({open:()=>t?.open(),close:()=>t?.close(),toggle:()=>t?.toggle(),isOpen:()=>t?.isOpen()??false,show:()=>t?.show(),hide:()=>t?.hide(),sendMessage:(a,c)=>t?t.sendWidgetMessage(a,c):Promise.resolve(),clearMessages:()=>t?.clearMessages(),setTheme:a=>t?.setTheme(a),setPrimaryColor:a=>t?.setPrimaryColor(a),setUser:a=>t?.setUser(a)}),[t]),null});function J(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"msg_"+Math.random().toString(36).substring(2,11)+"_"+Date.now()}function q(e={}){let r=V(),f=e.botId||r?.botId,s=e.publishableKey||r?.publishableKey,d=e.baseUrl||r?.baseUrl||"https://api.botzki.com",n=useMemo(()=>r?.client&&(!e.botId||e.botId===r.botId)?r.client:f&&s?new Botzki({botId:f,publishableKey:s,apiHost:d}):null,[r?.client,r?.botId,e.botId,f,s,d]),l=e.storageKey||(f?`botzki_chat_history_${f}`:"botzki_chat_history"),t=e.persistSession??true,[i,a]=useState(()=>e.sessionId?e.sessionId:r?.sessionId?r.sessionId:"sess_"+Math.random().toString(36).substring(2,9)),[c,o]=useState(e.initialMessages||[]),[C,S]=useState(""),[U,v]=useState(false),[T,M]=useState(false),[$,D]=useState(null),I=useRef(null),F=useRef(c);F.current=c,useEffect(()=>{if(!(!t||typeof window>"u"||e.initialMessages?.length))try{let u=localStorage.getItem(l);if(u){let p=JSON.parse(u);Array.isArray(p)&&o(p.map(g=>({...g,createdAt:new Date(g.createdAt)})));}}catch{}},[t,l,e.initialMessages?.length]),useEffect(()=>{if(!(!t||typeof window>"u"))try{c.length>0&&localStorage.setItem(l,JSON.stringify(c));}catch{}},[c,t,l]);let W=useCallback(()=>{I.current&&(I.current.abort(),I.current=null),v(false),M(false);},[]),B=useCallback(async(u,p)=>{let g=u.trim();if(!g&&!p?.imageBase64)return;if(!n){let b=new Error("Botzki client is not initialized. Provide botId & publishableKey or wrap in <BotzkiProvider>.");D(b),e.onError?.(b);return}D(null),v(true),M(e.stream!==false);let k={id:J(),role:"user",content:g,createdAt:new Date},m=J(),H={id:m,role:"assistant",content:"",createdAt:new Date,isStreaming:e.stream!==false};o(b=>[...b,k,H]);let P=new AbortController;I.current=P;try{if(e.stream!==!1){let b="";await n.chatStream({message:g,sessionId:i,language:e.language,imageBase64:p?.imageBase64,imageMimeType:p?.imageMimeType,onDelta:y=>{P.signal.aborted||(b+=y,o(w=>w.map(x=>x.id===m?{...x,content:b}:x)));},onDone:y=>{if(P.signal.aborted)return;let w={id:m,role:"assistant",content:y.reply||b,createdAt:new Date,citations:y.citations,isStreaming:!1};o(x=>x.map(re=>re.id===m?w:re)),v(!1),M(!1),e.onResponse?.(y),e.onFinish?.(w);},onError:y=>{P.signal.aborted||(D(y),v(!1),M(!1),o(w=>w.map(x=>x.id===m?{...x,isStreaming:!1,error:y.message}:x)),e.onError?.(y));}});}else {let b=await n.chat({message:g,sessionId:i,language:e.language,imageBase64:p?.imageBase64,imageMimeType:p?.imageMimeType}),y={id:m,role:"assistant",content:b.reply,createdAt:new Date,citations:b.citations,isStreaming:!1};o(w=>w.map(x=>x.id===m?y:x)),v(!1),M(!1),e.onResponse?.(b),e.onFinish?.(y);}}catch(b){if(!P.signal.aborted){let y=b instanceof Error?b:new Error(String(b));D(y),v(false),M(false),o(w=>w.map(x=>x.id===m?{...x,isStreaming:false,error:y.message}:x)),e.onError?.(y);}}finally{I.current===P&&(I.current=null);}},[n,e,i]),K=useCallback(u=>{S(u.target.value);},[]),j=useCallback(async(u,p)=>{u&&typeof u.preventDefault=="function"&&u.preventDefault();let g=C;S(""),await B(g,p);},[C,B]),O=useCallback(u=>{let p={id:u.id||J(),role:u.role||"user",content:u.content,createdAt:u.createdAt||new Date,citations:u.citations,isStreaming:u.isStreaming,error:u.error};o(g=>[...g,p]);},[]),_=useCallback(async()=>{let u=F.current;if(u.length===0)return;let p=u.map(k=>k.role).lastIndexOf("user");if(p===-1)return;let g=u[p];o(u.slice(0,p)),await B(g.content);},[B]),E=useCallback(()=>{if(W(),o([]),t&&typeof window<"u")try{localStorage.removeItem(l);}catch{}},[W,t,l]);return {messages:c,input:C,setInput:S,handleInputChange:K,handleSubmit:j,sendMessage:B,append:O,reload:_,stop:W,clearMessages:E,setMessages:o,isLoading:U,isStreaming:T,error:$,sessionId:i,setSessionId:a}}function X(){let{client:e,botId:r}=R(),[f,s]=useState(null),[d,n]=useState(true),[l,t]=useState(null),i=useCallback(async()=>{n(true),t(null);try{let a=await e.getBotInfo();s(a);}catch(a){t(a instanceof Error?a:new Error(String(a)));}finally{n(false);}},[e]);return useEffect(()=>{i();},[i,r]),{data:f,isLoading:d,error:l,refetch:i}}function Me({title:e,subtitle:r="Online",greeting:f="Hello! How can I help you today?",starterQuestions:s,theme:d="auto",primaryColor:n="#0ea5e9",className:l="",style:t,placeholder:i="Ask a question...",...a}){let{messages:c,input:o,handleInputChange:C,handleSubmit:S,sendMessage:U,clearMessages:v,isLoading:T,isStreaming:M,error:$}=q(a),{data:D}=X(),I=useRef(null);useEffect(()=>{I.current&&(I.current.scrollTop=I.current.scrollHeight);},[c,M]);let F=e||D?.name||"AI Assistant",W=s||D?.starterQuestions||[],B=d==="dark"||d==="auto"&&typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches,K=B?"#0f172a":"#ffffff",j=B?"#1e293b":"#f8fafc",O=B?"#f8fafc":"#0f172a",_=B?"#94a3b8":"#64748b",E=B?"#334155":"#e2e8f0",u=n,p=B?"#1e293b":"#f1f5f9",g=B?"#f1f5f9":"#1e293b";return jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:"450px",backgroundColor:K,color:O,borderRadius:"16px",border:`1px solid ${E}`,overflow:"hidden",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',boxSizing:"border-box",...t},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 18px",backgroundColor:j,borderBottom:`1px solid ${E}`},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[jsx("div",{style:{width:"36px",height:"36px",borderRadius:"50%",backgroundColor:n,display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",fontWeight:"bold",fontSize:"15px"},children:F.charAt(0).toUpperCase()}),jsxs("div",{children:[jsx("div",{style:{fontWeight:600,fontSize:"14px",lineHeight:1.2},children:F}),jsxs("div",{style:{fontSize:"12px",color:_,display:"flex",alignItems:"center",gap:"5px",marginTop:"2px"},children:[jsx("span",{style:{width:"7px",height:"7px",borderRadius:"50%",backgroundColor:"#22c55e",display:"inline-block"}}),r]})]})]}),c.length>0&&jsx("button",{onClick:v,title:"Clear Chat",style:{background:"transparent",border:"none",color:_,cursor:"pointer",fontSize:"12px",padding:"4px 8px",borderRadius:"6px"},children:"Clear"})]}),jsxs("div",{ref:I,style:{flex:1,overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px"},children:[f&&jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:jsx("div",{style:{maxWidth:"80%",padding:"10px 14px",borderRadius:"14px",backgroundColor:p,color:g,fontSize:"14px",lineHeight:1.45},children:f})}),c.length===0&&W.length>0&&jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px",marginTop:"8px"},children:[jsx("span",{style:{fontSize:"11px",color:_,fontWeight:500},children:"SUGGESTED QUESTIONS"}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:W.map((k,m)=>jsx("button",{onClick:()=>U(k),style:{backgroundColor:B?"#1e293b":"#f1f5f9",color:O,border:`1px solid ${E}`,padding:"6px 12px",borderRadius:"20px",fontSize:"12px",cursor:"pointer",textAlign:"left",transition:"all 0.15s ease"},children:k},m))})]}),c.map(k=>{let m=k.role==="user";return jsx("div",{style:{display:"flex",justifyContent:m?"flex-end":"flex-start"},children:jsxs("div",{style:{maxWidth:"85%",padding:"10px 14px",borderRadius:"14px",backgroundColor:m?u:p,color:m?"#ffffff":g,fontSize:"14px",lineHeight:1.45,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[k.content,k.citations&&k.citations.length>0&&jsxs("div",{style:{marginTop:"8px",paddingTop:"6px",borderTop:`1px solid ${m?"rgba(255,255,255,0.2)":E}`,fontSize:"11px",display:"flex",flexWrap:"wrap",gap:"4px"},children:[jsx("span",{style:{opacity:.8},children:"Sources:"}),k.citations.map((H,P)=>jsxs("span",{style:{backgroundColor:m?"rgba(255,255,255,0.2)":"rgba(0,0,0,0.06)",padding:"2px 6px",borderRadius:"4px",fontWeight:500},children:[H.source," ",H.page_number?`p.${H.page_number}`:""]},P))]}),k.error&&jsxs("div",{style:{marginTop:"6px",fontSize:"12px",color:"#ef4444"},children:["Error: ",k.error]})]})},k.id)}),T&&!M&&jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:jsx("div",{style:{padding:"8px 14px",borderRadius:"14px",backgroundColor:p,color:_,fontSize:"13px"},children:"Thinking..."})}),$&&jsx("div",{style:{padding:"8px 12px",borderRadius:"8px",backgroundColor:"rgba(239, 68, 68, 0.1)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#ef4444",fontSize:"12px"},children:$.message})]}),jsxs("form",{onSubmit:S,style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",borderTop:`1px solid ${E}`,backgroundColor:j},children:[jsx("input",{type:"text",value:o,onChange:C,placeholder:i,disabled:T,style:{flex:1,padding:"10px 14px",borderRadius:"22px",border:`1px solid ${E}`,backgroundColor:K,color:O,fontSize:"14px",outline:"none"}}),jsx("button",{type:"submit",disabled:T||!o.trim(),style:{backgroundColor:n,color:"#ffffff",border:"none",borderRadius:"20px",padding:"10px 18px",fontWeight:600,fontSize:"13px",cursor:T||!o.trim()?"not-allowed":"pointer",opacity:T||!o.trim()?.5:1,transition:"opacity 0.2s ease"},children:"Send"})]})]})}function Re(){let{client:e,sessionId:r}=R(),[f,s]=useState(false),[d,n]=useState(false),[l,t]=useState(null),i=useCallback(async c=>{s(true),t(null),n(false);try{return await e.submitFeedback({...c,sessionId:r}),n(!0),!0}catch(o){let C=o instanceof Error?o:new Error(String(o));return t(C),false}finally{s(false);}},[e,r]),a=useCallback(()=>{s(false),n(false),t(null);},[]);return {submitFeedback:i,isSubmitting:f,isSuccess:d,error:l,reset:a}}function Ue(){let{client:e,sessionId:r}=R(),[f,s]=useState(false),[d,n]=useState(false),[l,t]=useState(null),i=useCallback(async c=>{s(true),t(null),n(false);try{return await e.captureLead({...c,sessionId:r}),n(!0),!0}catch(o){let C=o instanceof Error?o:new Error(String(o));return t(C),false}finally{s(false);}},[e,r]),a=useCallback(()=>{s(false),n(false),t(null);},[]);return {captureLead:i,isSubmitting:f,isSuccess:d,error:l,reset:a}}function Ee(){let{client:e}=R(),[r,f]=useState(false),[s,d]=useState(null),[n,l]=useState(null),t=useCallback(async a=>{f(true),l(null);try{let o=(await e.transcribeAudio(a)).text||"";return d(o),o}catch(c){let o=c instanceof Error?c:new Error(String(c));return l(o),null}finally{f(false);}},[e]),i=useCallback(()=>{f(false),d(null),l(null);},[]);return {transcribe:t,isTranscribing:r,transcript:s,error:n,reset:i}}
2
+ export{Me as BotzkiChat,ge as BotzkiProvider,Be as BotzkiWidget,X as useBotInfo,R as useBotzki,q as useChat,Re as useFeedback,Ue as useLeadCapture,V as useOptionalBotzki,Ee as useVoiceTranscription};//# sourceMappingURL=index.mjs.map
3
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context.tsx","../src/components/BotzkiWidget.tsx","../src/hooks/useChat.ts","../src/hooks/useBotInfo.ts","../src/components/BotzkiChat.tsx","../src/hooks/useFeedback.ts","../src/hooks/useLeadCapture.ts","../src/hooks/useVoiceTranscription.ts"],"names":["BotzkiContext","createContext","generateId","BotzkiProvider","botId","publishableKey","baseUrl","apiHost","user","defaultSessionId","customClient","children","resolvedHost","sessionId","setSessionId","useState","stored","newId","client","useMemo","Botzki","useEffect","value","jsx","useBotzki","context","useContext","useOptionalBotzki","BotzkiWidget","forwardRef","props","ref","isMountedRef","useRef","_b","_p","_u","_usr","onOpen","onClose","widgetOptions","useImperativeHandle","msg","img","theme","color","generateMessageId","useChat","options","storageKey","persist","messages","setMessages","input","setInput","isLoading","setIsLoading","isStreaming","setIsStreaming","error","setError","abortControllerRef","messagesRef","parsed","m","stop","useCallback","sendMessage","content","sendOpts","trimmed","err","userMsg","assistantMsgId","assistantMsg","prev","controller","accumulatedContent","delta","res","completedMsg","finalErr","handleInputChange","e","handleSubmit","currentText","append","newMsg","reload","list","lastUserIdx","userMsgToResend","clearMessages","useBotInfo","data","setData","fetchBotInfo","BotzkiChat","title","subtitle","greeting","starterQuestions","primaryColor","className","style","placeholder","chatOptions","botInfo","scrollRef","displayTitle","displayStarters","isDark","bgMain","bgHeader","textMain","textMuted","borderColor","userBubbleBg","assistantBubbleBg","assistantText","jsxs","q","idx","isUser","c","i","useFeedback","isSubmitting","setIsSubmitting","isSuccess","setIsSuccess","submitFeedback","payload","errorObj","reset","useLeadCapture","captureLead","useVoiceTranscription","isTranscribing","setIsTranscribing","transcript","setTranscript","transcribe","audio","transcriptText"],"mappings":"mMAeA,IAAMA,CAAAA,CAAgBC,aAAAA,CAAyC,IAAI,CAAA,CAEnE,SAASC,CAAAA,EAAqB,CAC5B,OAAI,OAAO,MAAA,CAAW,GAAA,E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MAAM,MAAA,CAAOA,CAAG,CAAC,CAAA,CACnE,OAAAX,EAASyE,CAAQ,CAAA,CACV,IACT,CAAA,OAAE,CACAM,CAAAA,CAAkB,KAAK,EACzB,CACF,EACA,CAACzH,CAAM,CACT,CAAA,CAEMoH,EAAQpE,WAAAA,CAAY,IAAM,CAC9ByE,CAAAA,CAAkB,KAAK,EACvBE,CAAAA,CAAc,IAAI,CAAA,CAClBjF,CAAAA,CAAS,IAAI,EACf,CAAA,CAAG,EAAE,CAAA,CAEL,OAAO,CACL,UAAA,CAAAkF,CAAAA,CACA,cAAA,CAAAJ,EACA,UAAA,CAAAE,CAAAA,CACA,MAAAjF,CAAAA,CACA,KAAA,CAAA2E,CACF,CACF","file":"index.mjs","sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useMemo,\n useState,\n useEffect,\n} from \"react\";\nimport { Botzki } from \"@botzki/js\";\nimport type {\n BotzkiProviderProps,\n BotzkiContextValue,\n} from \"./types\";\n\nconst BotzkiContext = createContext<BotzkiContextValue | null>(null);\n\nfunction generateId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return \"sess_\" + Math.random().toString(36).substring(2, 11) + \"_\" + Date.now();\n}\n\n/**\n * Root context provider for Botzki AI. Wraps your React component tree and shares\n * client instances and configuration with all child hooks and components.\n */\nexport function BotzkiProvider({\n botId,\n publishableKey,\n baseUrl,\n apiHost,\n user,\n defaultSessionId,\n client: customClient,\n children,\n}: BotzkiProviderProps) {\n const resolvedHost = apiHost || baseUrl || \"https://api.botzki.com\";\n\n // Session ID management (SSR-safe)\n const [sessionId, setSessionId] = useState<string>(() => {\n if (defaultSessionId) return defaultSessionId;\n if (typeof window !== \"undefined\") {\n try {\n const stored = localStorage.getItem(`botzki_session_${botId}`);\n if (stored) return stored;\n const newId = generateId();\n localStorage.setItem(`botzki_session_${botId}`, newId);\n return newId;\n } catch {\n return generateId();\n }\n }\n return defaultSessionId || generateId();\n });\n\n // Client memoization: instantiate once per unique botId + publishableKey + apiHost\n const client = useMemo(() => {\n if (customClient) return customClient;\n return new Botzki({\n botId,\n publishableKey,\n apiHost: resolvedHost,\n });\n }, [customClient, botId, publishableKey, resolvedHost]);\n\n // Sync visitor details if provided\n useEffect(() => {\n if (user && client) {\n client.setUser(user);\n }\n }, [client, user]);\n\n const value = useMemo<BotzkiContextValue>(\n () => ({\n client,\n botId,\n publishableKey,\n baseUrl: resolvedHost,\n apiHost: resolvedHost,\n user,\n sessionId,\n setSessionId,\n }),\n [client, botId, publishableKey, resolvedHost, user, sessionId]\n );\n\n return (\n <BotzkiContext.Provider value={value}>\n {children}\n </BotzkiContext.Provider>\n );\n}\n\n/**\n * Hook to access the current Botzki context value (client instance, botId, sessionId).\n * Throws a helpful error if used outside a `<BotzkiProvider>`.\n */\nexport function useBotzki(): BotzkiContextValue {\n const context = useContext(BotzkiContext);\n if (!context) {\n throw new Error(\n \"useBotzki must be used within a <BotzkiProvider>. Wrap your application or component with <BotzkiProvider botId='...' publishableKey='...'>.\"\n );\n }\n return context;\n}\n\n/**\n * Optional hook to access the Botzki context, returning null instead of throwing\n * if called outside `<BotzkiProvider>`. Useful for components that can be used standalone.\n */\nexport function useOptionalBotzki(): BotzkiContextValue | null {\n return useContext(BotzkiContext);\n}\n","\"use client\";\n\nimport {\n useEffect,\n useRef,\n useImperativeHandle,\n forwardRef,\n useMemo,\n} from \"react\";\nimport { Botzki } from \"@botzki/js\";\nimport { useOptionalBotzki } from \"../context\";\nimport type {\n BotzkiWidgetProps,\n BotzkiWidgetRef,\n} from \"../types\";\n\n/**\n * Drop-in floating chat widget component for React.\n * Handles automatic lifecycle management, React StrictMode safety, dynamic theme/color updates,\n * and imperative control via forwarded ref.\n */\nexport const BotzkiWidget = forwardRef<BotzkiWidgetRef, BotzkiWidgetProps>(\n function BotzkiWidget(props, ref) {\n const context = useOptionalBotzki();\n\n const botId = props.botId || context?.botId;\n const publishableKey = props.publishableKey || context?.publishableKey;\n const baseUrl = props.baseUrl || context?.baseUrl || \"https://api.botzki.com\";\n\n // Dedicated or inherited Botzki client\n const client = useMemo(() => {\n if (context?.client && (!props.botId || props.botId === context.botId)) {\n return context.client;\n }\n if (botId && publishableKey) {\n return new Botzki({ botId, publishableKey, apiHost: baseUrl });\n }\n return null;\n }, [context?.client, context?.botId, props.botId, botId, publishableKey, baseUrl]);\n\n const isMountedRef = useRef<boolean>(false);\n\n // Lifecycle: Mount and Unmount with React StrictMode resilience\n useEffect(() => {\n if (!client || typeof window === \"undefined\") return;\n\n // Extract widget mount options\n const {\n botId: _b,\n publishableKey: _p,\n baseUrl: _u,\n user: _usr,\n onOpen,\n onClose,\n ...widgetOptions\n } = props;\n\n // Mount the widget\n client.mount({\n ...widgetOptions,\n onOpen,\n onClose,\n });\n\n if (props.user) {\n client.setUser(props.user);\n }\n\n isMountedRef.current = true;\n\n // Cleanup on unmount (Strict Mode safe)\n return () => {\n isMountedRef.current = false;\n try {\n client.unmount();\n } catch {\n // Ignore unmount error if already detached\n }\n };\n }, [client]);\n\n // Dynamic reactive updates: Theme\n useEffect(() => {\n if (client && isMountedRef.current && props.theme) {\n client.setTheme(props.theme);\n }\n }, [client, props.theme]);\n\n // Dynamic reactive updates: Primary Color\n useEffect(() => {\n if (client && isMountedRef.current && props.primaryColor) {\n client.setPrimaryColor(props.primaryColor);\n }\n }, [client, props.primaryColor]);\n\n // Dynamic reactive updates: Identified User\n useEffect(() => {\n if (client && isMountedRef.current && props.user) {\n client.setUser(props.user);\n }\n }, [client, props.user]);\n\n // Imperative ref handle\n useImperativeHandle(\n ref,\n () => ({\n open: () => client?.open(),\n close: () => client?.close(),\n toggle: () => client?.toggle(),\n isOpen: () => client?.isOpen() ?? false,\n show: () => client?.show(),\n hide: () => client?.hide(),\n sendMessage: (msg: string, img?: string) =>\n client ? client.sendWidgetMessage(msg, img) : Promise.resolve(),\n clearMessages: () => client?.clearMessages(),\n setTheme: (theme: \"light\" | \"dark\" | \"auto\") => client?.setTheme(theme),\n setPrimaryColor: (color: string) => client?.setPrimaryColor(color),\n setUser: (user) => client?.setUser(user),\n }),\n [client]\n );\n\n // Widget mounts into the DOM body using Shadow DOM isolation\n return null;\n }\n);\n","\"use client\";\n\nimport { useState, useCallback, useRef, useEffect, useMemo } from \"react\";\nimport { Botzki, type ChatResponse } from \"@botzki/js\";\nimport { useOptionalBotzki } from \"../context\";\nimport type {\n BotzkiMessage,\n UseChatOptions,\n UseChatReturn,\n} from \"../types\";\n\nfunction generateMessageId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return \"msg_\" + Math.random().toString(36).substring(2, 11) + \"_\" + Date.now();\n}\n\n/**\n * Headless React hook for building rich, interactive AI chat interfaces with real-time streaming,\n * session persistence, optimistic UI updates, error recovery, and multimodal support.\n */\nexport function useChat(options: UseChatOptions = {}): UseChatReturn {\n const context = useOptionalBotzki();\n\n const botId = options.botId || context?.botId;\n const publishableKey = options.publishableKey || context?.publishableKey;\n const baseUrl = options.baseUrl || context?.baseUrl || \"https://api.botzki.com\";\n\n // Dedicated or shared Botzki client\n const client = useMemo(() => {\n if (context?.client && (!options.botId || options.botId === context.botId)) {\n return context.client;\n }\n if (botId && publishableKey) {\n return new Botzki({ botId, publishableKey, apiHost: baseUrl });\n }\n return null;\n }, [context?.client, context?.botId, options.botId, botId, publishableKey, baseUrl]);\n\n // Session ID resolution\n const storageKey =\n options.storageKey || (botId ? `botzki_chat_history_${botId}` : \"botzki_chat_history\");\n const persist = options.persistSession ?? true;\n\n const [sessionId, setSessionId] = useState<string>(() => {\n if (options.sessionId) return options.sessionId;\n if (context?.sessionId) return context.sessionId;\n return \"sess_\" + Math.random().toString(36).substring(2, 9);\n });\n\n const [messages, setMessages] = useState<BotzkiMessage[]>(\n options.initialMessages || []\n );\n const [input, setInput] = useState<string>(\"\");\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isStreaming, setIsStreaming] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n\n const abortControllerRef = useRef<AbortController | null>(null);\n const messagesRef = useRef<BotzkiMessage[]>(messages);\n messagesRef.current = messages;\n\n // Hydrate stored messages from localStorage on mount (SSR safe)\n useEffect(() => {\n if (!persist || typeof window === \"undefined\" || options.initialMessages?.length) return;\n try {\n const stored = localStorage.getItem(storageKey);\n if (stored) {\n const parsed = JSON.parse(stored);\n if (Array.isArray(parsed)) {\n setMessages(\n parsed.map((m: any) => ({\n ...m,\n createdAt: new Date(m.createdAt),\n }))\n );\n }\n }\n } catch {\n // Ignore localStorage parse errors\n }\n }, [persist, storageKey, options.initialMessages?.length]);\n\n // Persist messages to localStorage on change\n useEffect(() => {\n if (!persist || typeof window === \"undefined\") return;\n try {\n if (messages.length > 0) {\n localStorage.setItem(storageKey, JSON.stringify(messages));\n }\n } catch {\n // Ignore quota errors\n }\n }, [messages, persist, storageKey]);\n\n // Stop active streaming\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n setIsLoading(false);\n setIsStreaming(false);\n }, []);\n\n // Send message implementation\n const sendMessage = useCallback(\n async (\n content: string,\n sendOpts?: { imageBase64?: string; imageMimeType?: string }\n ) => {\n const trimmed = content.trim();\n if (!trimmed && !sendOpts?.imageBase64) return;\n\n if (!client) {\n const err = new Error(\n \"Botzki client is not initialized. Provide botId & publishableKey or wrap in <BotzkiProvider>.\"\n );\n setError(err);\n options.onError?.(err);\n return;\n }\n\n setError(null);\n setIsLoading(true);\n setIsStreaming(options.stream !== false);\n\n const userMsg: BotzkiMessage = {\n id: generateMessageId(),\n role: \"user\",\n content: trimmed,\n createdAt: new Date(),\n };\n\n const assistantMsgId = generateMessageId();\n const assistantMsg: BotzkiMessage = {\n id: assistantMsgId,\n role: \"assistant\",\n content: \"\",\n createdAt: new Date(),\n isStreaming: options.stream !== false,\n };\n\n // Optimistically append user message and placeholder assistant message\n setMessages((prev) => [...prev, userMsg, assistantMsg]);\n\n const controller = new AbortController();\n abortControllerRef.current = controller;\n\n try {\n if (options.stream !== false) {\n let accumulatedContent = \"\";\n\n await client.chatStream({\n message: trimmed,\n sessionId,\n language: options.language,\n imageBase64: sendOpts?.imageBase64,\n imageMimeType: sendOpts?.imageMimeType,\n onDelta: (delta: string) => {\n if (controller.signal.aborted) return;\n accumulatedContent += delta;\n\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMsgId\n ? { ...msg, content: accumulatedContent }\n : msg\n )\n );\n },\n onDone: (res: ChatResponse) => {\n if (controller.signal.aborted) return;\n\n const completedMsg: BotzkiMessage = {\n id: assistantMsgId,\n role: \"assistant\",\n content: res.reply || accumulatedContent,\n createdAt: new Date(),\n citations: res.citations,\n isStreaming: false,\n };\n\n setMessages((prev) =>\n prev.map((msg) => (msg.id === assistantMsgId ? completedMsg : msg))\n );\n\n setIsLoading(false);\n setIsStreaming(false);\n options.onResponse?.(res);\n options.onFinish?.(completedMsg);\n },\n onError: (err: Error) => {\n if (controller.signal.aborted) return;\n setError(err);\n setIsLoading(false);\n setIsStreaming(false);\n\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMsgId\n ? { ...msg, isStreaming: false, error: err.message }\n : msg\n )\n );\n options.onError?.(err);\n },\n });\n } else {\n // Non-streaming fallback\n const res = await client.chat({\n message: trimmed,\n sessionId,\n language: options.language,\n imageBase64: sendOpts?.imageBase64,\n imageMimeType: sendOpts?.imageMimeType,\n });\n\n const completedMsg: BotzkiMessage = {\n id: assistantMsgId,\n role: \"assistant\",\n content: res.reply,\n createdAt: new Date(),\n citations: res.citations,\n isStreaming: false,\n };\n\n setMessages((prev) =>\n prev.map((msg) => (msg.id === assistantMsgId ? completedMsg : msg))\n );\n\n setIsLoading(false);\n setIsStreaming(false);\n options.onResponse?.(res);\n options.onFinish?.(completedMsg);\n }\n } catch (err: any) {\n if (!controller.signal.aborted) {\n const finalErr = err instanceof Error ? err : new Error(String(err));\n setError(finalErr);\n setIsLoading(false);\n setIsStreaming(false);\n\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMsgId\n ? { ...msg, isStreaming: false, error: finalErr.message }\n : msg\n )\n );\n options.onError?.(finalErr);\n }\n } finally {\n if (abortControllerRef.current === controller) {\n abortControllerRef.current = null;\n }\n }\n },\n [client, options, sessionId]\n );\n\n const handleInputChange = useCallback(\n (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setInput(e.target.value);\n },\n []\n );\n\n const handleSubmit = useCallback(\n async (\n e?: React.FormEvent,\n sendOpts?: { imageBase64?: string; imageMimeType?: string }\n ) => {\n if (e && typeof e.preventDefault === \"function\") {\n e.preventDefault();\n }\n const currentText = input;\n setInput(\"\");\n await sendMessage(currentText, sendOpts);\n },\n [input, sendMessage]\n );\n\n const append = useCallback(\n (msg: Partial<BotzkiMessage> & { content: string }) => {\n const newMsg: BotzkiMessage = {\n id: msg.id || generateMessageId(),\n role: msg.role || \"user\",\n content: msg.content,\n createdAt: msg.createdAt || new Date(),\n citations: msg.citations,\n isStreaming: msg.isStreaming,\n error: msg.error,\n };\n setMessages((prev) => [...prev, newMsg]);\n },\n []\n );\n\n const reload = useCallback(async () => {\n const list = messagesRef.current;\n if (list.length === 0) return;\n\n // Find the last user message\n const lastUserIdx = list.map((m) => m.role).lastIndexOf(\"user\");\n if (lastUserIdx === -1) return;\n\n const userMsgToResend = list[lastUserIdx];\n\n // Remove everything from the last user message downwards\n setMessages(list.slice(0, lastUserIdx));\n\n await sendMessage(userMsgToResend.content);\n }, [sendMessage]);\n\n const clearMessages = useCallback(() => {\n stop();\n setMessages([]);\n if (persist && typeof window !== \"undefined\") {\n try {\n localStorage.removeItem(storageKey);\n } catch {\n // Ignore\n }\n }\n }, [stop, persist, storageKey]);\n\n return {\n messages,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n sendMessage,\n append,\n reload,\n stop,\n clearMessages,\n setMessages,\n isLoading,\n isStreaming,\n error,\n sessionId,\n setSessionId,\n };\n}\n","\"use client\";\n\nimport { useState, useEffect, useCallback } from \"react\";\nimport { useBotzki } from \"../context\";\n\nexport interface BotInfoData {\n id?: string;\n name?: string;\n description?: string;\n primaryColor?: string;\n theme?: string;\n avatarUrl?: string;\n greeting?: string;\n starterQuestions?: string[];\n capabilities?: string[];\n [key: string]: unknown;\n}\n\nexport interface UseBotInfoReturn {\n data: BotInfoData | null;\n isLoading: boolean;\n error: Error | null;\n refetch: () => Promise<void>;\n}\n\n/**\n * Hook to retrieve public bot configuration, branding, avatar, and starter questions.\n */\nexport function useBotInfo(): UseBotInfoReturn {\n const { client, botId } = useBotzki();\n const [data, setData] = useState<BotInfoData | null>(null);\n const [isLoading, setIsLoading] = useState<boolean>(true);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchBotInfo = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await client.getBotInfo();\n setData(res as BotInfoData);\n } catch (err: any) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [client]);\n\n useEffect(() => {\n fetchBotInfo();\n }, [fetchBotInfo, botId]);\n\n return {\n data,\n isLoading,\n error,\n refetch: fetchBotInfo,\n };\n}\n\n","\"use client\";\n\nimport React, { useRef, useEffect } from \"react\";\nimport { useChat } from \"../hooks/useChat\";\nimport { useBotInfo } from \"../hooks/useBotInfo\";\nimport type { UseChatOptions } from \"../types\";\n\nexport interface BotzkiChatProps extends UseChatOptions {\n /**\n * Title shown in the chat window header. Defaults to bot name or \"AI Assistant\".\n */\n title?: string;\n\n /**\n * Subtitle shown in the chat window header. Defaults to \"Online\".\n */\n subtitle?: string;\n\n /**\n * Welcome greeting when conversation starts.\n */\n greeting?: string;\n\n /**\n * List of clickable starter prompt questions.\n */\n starterQuestions?: string[];\n\n /**\n * Visual theme (\"light\" | \"dark\" | \"auto\"). Defaults to \"auto\".\n */\n theme?: \"light\" | \"dark\" | \"auto\";\n\n /**\n * Primary accent color (hex or rgb). Defaults to \"#0ea5e9\".\n */\n primaryColor?: string;\n\n /**\n * Custom CSS class name for the outer container.\n */\n className?: string;\n\n /**\n * Custom style object for the outer container.\n */\n style?: React.CSSProperties;\n\n /**\n * Placeholder text for the message input.\n */\n placeholder?: string;\n}\n\n/**\n * Embedded, full-featured AI chat container for dashboards, sidebars, and dedicated support pages.\n * Fully responsive and self-contained with no external CSS dependencies.\n */\nexport function BotzkiChat({\n title,\n subtitle = \"Online\",\n greeting = \"Hello! How can I help you today?\",\n starterQuestions,\n theme = \"auto\",\n primaryColor = \"#0ea5e9\",\n className = \"\",\n style,\n placeholder = \"Ask a question...\",\n ...chatOptions\n}: BotzkiChatProps) {\n const {\n messages,\n input,\n handleInputChange,\n handleSubmit,\n sendMessage,\n clearMessages,\n isLoading,\n isStreaming,\n error,\n } = useChat(chatOptions);\n\n const { data: botInfo } = useBotInfo();\n const scrollRef = useRef<HTMLDivElement>(null);\n\n // Auto-scroll to bottom as messages arrive\n useEffect(() => {\n if (scrollRef.current) {\n scrollRef.current.scrollTop = scrollRef.current.scrollHeight;\n }\n }, [messages, isStreaming]);\n\n const displayTitle = title || botInfo?.name || \"AI Assistant\";\n const displayStarters = starterQuestions || botInfo?.starterQuestions || [];\n\n const isDark =\n theme === \"dark\" ||\n (theme === \"auto\" &&\n typeof window !== \"undefined\" &&\n window.matchMedia(\"(prefers-color-scheme: dark)\").matches);\n\n const bgMain = isDark ? \"#0f172a\" : \"#ffffff\";\n const bgHeader = isDark ? \"#1e293b\" : \"#f8fafc\";\n const textMain = isDark ? \"#f8fafc\" : \"#0f172a\";\n const textMuted = isDark ? \"#94a3b8\" : \"#64748b\";\n const borderColor = isDark ? \"#334155\" : \"#e2e8f0\";\n const userBubbleBg = primaryColor;\n const assistantBubbleBg = isDark ? \"#1e293b\" : \"#f1f5f9\";\n const assistantText = isDark ? \"#f1f5f9\" : \"#1e293b\";\n\n return (\n <div\n className={className}\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n width: \"100%\",\n height: \"100%\",\n minHeight: \"450px\",\n backgroundColor: bgMain,\n color: textMain,\n borderRadius: \"16px\",\n border: `1px solid ${borderColor}`,\n overflow: \"hidden\",\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif',\n boxSizing: \"border-box\",\n ...style,\n }}\n >\n {/* Header */}\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n padding: \"14px 18px\",\n backgroundColor: bgHeader,\n borderBottom: `1px solid ${borderColor}`,\n }}\n >\n <div style={{ display: \"flex\", alignItems: \"center\", gap: \"10px\" }}>\n <div\n style={{\n width: \"36px\",\n height: \"36px\",\n borderRadius: \"50%\",\n backgroundColor: primaryColor,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n color: \"#ffffff\",\n fontWeight: \"bold\",\n fontSize: \"15px\",\n }}\n >\n {displayTitle.charAt(0).toUpperCase()}\n </div>\n <div>\n <div style={{ fontWeight: 600, fontSize: \"14px\", lineHeight: 1.2 }}>\n {displayTitle}\n </div>\n <div\n style={{\n fontSize: \"12px\",\n color: textMuted,\n display: \"flex\",\n alignItems: \"center\",\n gap: \"5px\",\n marginTop: \"2px\",\n }}\n >\n <span\n style={{\n width: \"7px\",\n height: \"7px\",\n borderRadius: \"50%\",\n backgroundColor: \"#22c55e\",\n display: \"inline-block\",\n }}\n />\n {subtitle}\n </div>\n </div>\n </div>\n\n {messages.length > 0 && (\n <button\n onClick={clearMessages}\n title=\"Clear Chat\"\n style={{\n background: \"transparent\",\n border: \"none\",\n color: textMuted,\n cursor: \"pointer\",\n fontSize: \"12px\",\n padding: \"4px 8px\",\n borderRadius: \"6px\",\n }}\n >\n Clear\n </button>\n )}\n </div>\n\n {/* Messages Scroll Area */}\n <div\n ref={scrollRef}\n style={{\n flex: 1,\n overflowY: \"auto\",\n padding: \"16px\",\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"12px\",\n }}\n >\n {/* Initial Greeting */}\n {greeting && (\n <div style={{ display: \"flex\", justifyContent: \"flex-start\" }}>\n <div\n style={{\n maxWidth: \"80%\",\n padding: \"10px 14px\",\n borderRadius: \"14px\",\n backgroundColor: assistantBubbleBg,\n color: assistantText,\n fontSize: \"14px\",\n lineHeight: 1.45,\n }}\n >\n {greeting}\n </div>\n </div>\n )}\n\n {/* Starter Prompts */}\n {messages.length === 0 && displayStarters.length > 0 && (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"8px\",\n marginTop: \"8px\",\n }}\n >\n <span style={{ fontSize: \"11px\", color: textMuted, fontWeight: 500 }}>\n SUGGESTED QUESTIONS\n </span>\n <div style={{ display: \"flex\", flexWrap: \"wrap\", gap: \"6px\" }}>\n {displayStarters.map((q, idx) => (\n <button\n key={idx}\n onClick={() => sendMessage(q)}\n style={{\n backgroundColor: isDark ? \"#1e293b\" : \"#f1f5f9\",\n color: textMain,\n border: `1px solid ${borderColor}`,\n padding: \"6px 12px\",\n borderRadius: \"20px\",\n fontSize: \"12px\",\n cursor: \"pointer\",\n textAlign: \"left\",\n transition: \"all 0.15s ease\",\n }}\n >\n {q}\n </button>\n ))}\n </div>\n </div>\n )}\n\n {/* Message Thread */}\n {messages.map((msg) => {\n const isUser = msg.role === \"user\";\n return (\n <div\n key={msg.id}\n style={{\n display: \"flex\",\n justifyContent: isUser ? \"flex-end\" : \"flex-start\",\n }}\n >\n <div\n style={{\n maxWidth: \"85%\",\n padding: \"10px 14px\",\n borderRadius: \"14px\",\n backgroundColor: isUser ? userBubbleBg : assistantBubbleBg,\n color: isUser ? \"#ffffff\" : assistantText,\n fontSize: \"14px\",\n lineHeight: 1.45,\n whiteSpace: \"pre-wrap\",\n wordBreak: \"break-word\",\n }}\n >\n {msg.content}\n\n {/* Citations Badges */}\n {msg.citations && msg.citations.length > 0 && (\n <div\n style={{\n marginTop: \"8px\",\n paddingTop: \"6px\",\n borderTop: `1px solid ${\n isUser ? \"rgba(255,255,255,0.2)\" : borderColor\n }`,\n fontSize: \"11px\",\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: \"4px\",\n }}\n >\n <span style={{ opacity: 0.8 }}>Sources:</span>\n {msg.citations.map((c, i) => (\n <span\n key={i}\n style={{\n backgroundColor: isUser\n ? \"rgba(255,255,255,0.2)\"\n : \"rgba(0,0,0,0.06)\",\n padding: \"2px 6px\",\n borderRadius: \"4px\",\n fontWeight: 500,\n }}\n >\n {c.source} {c.page_number ? `p.${c.page_number}` : \"\"}\n </span>\n ))}\n </div>\n )}\n\n {/* Error Banner */}\n {msg.error && (\n <div\n style={{\n marginTop: \"6px\",\n fontSize: \"12px\",\n color: \"#ef4444\",\n }}\n >\n Error: {msg.error}\n </div>\n )}\n </div>\n </div>\n );\n })}\n\n {/* Loading Indicator */}\n {isLoading && !isStreaming && (\n <div style={{ display: \"flex\", justifyContent: \"flex-start\" }}>\n <div\n style={{\n padding: \"8px 14px\",\n borderRadius: \"14px\",\n backgroundColor: assistantBubbleBg,\n color: textMuted,\n fontSize: \"13px\",\n }}\n >\n Thinking...\n </div>\n </div>\n )}\n\n {/* Global Error Banner */}\n {error && (\n <div\n style={{\n padding: \"8px 12px\",\n borderRadius: \"8px\",\n backgroundColor: \"rgba(239, 68, 68, 0.1)\",\n border: \"1px solid rgba(239, 68, 68, 0.3)\",\n color: \"#ef4444\",\n fontSize: \"12px\",\n }}\n >\n {error.message}\n </div>\n )}\n </div>\n\n {/* Input Bar */}\n <form\n onSubmit={handleSubmit}\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n padding: \"12px 16px\",\n borderTop: `1px solid ${borderColor}`,\n backgroundColor: bgHeader,\n }}\n >\n <input\n type=\"text\"\n value={input}\n onChange={handleInputChange}\n placeholder={placeholder}\n disabled={isLoading}\n style={{\n flex: 1,\n padding: \"10px 14px\",\n borderRadius: \"22px\",\n border: `1px solid ${borderColor}`,\n backgroundColor: bgMain,\n color: textMain,\n fontSize: \"14px\",\n outline: \"none\",\n }}\n />\n <button\n type=\"submit\"\n disabled={isLoading || !input.trim()}\n style={{\n backgroundColor: primaryColor,\n color: \"#ffffff\",\n border: \"none\",\n borderRadius: \"20px\",\n padding: \"10px 18px\",\n fontWeight: 600,\n fontSize: \"13px\",\n cursor: isLoading || !input.trim() ? \"not-allowed\" : \"pointer\",\n opacity: isLoading || !input.trim() ? 0.5 : 1,\n transition: \"opacity 0.2s ease\",\n }}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n\n","\"use client\";\n\nimport { useState, useCallback } from \"react\";\nimport { useBotzki } from \"../context\";\n\nexport interface FeedbackPayload {\n messageId?: string;\n query?: string;\n rating: number; // e.g. 1 for positive (thumbs up), -1 or 0 for negative (thumbs down)\n comment?: string;\n category?: string;\n}\n\nexport interface UseFeedbackReturn {\n submitFeedback: (payload: FeedbackPayload) => Promise<boolean>;\n isSubmitting: boolean;\n isSuccess: boolean;\n error: Error | null;\n reset: () => void;\n}\n\n/**\n * Hook to submit visitor ratings and feedback on bot answers.\n */\nexport function useFeedback(): UseFeedbackReturn {\n const { client, sessionId } = useBotzki();\n const [isSubmitting, setIsSubmitting] = useState<boolean>(false);\n const [isSuccess, setIsSuccess] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n\n const submitFeedback = useCallback(\n async (payload: FeedbackPayload): Promise<boolean> => {\n setIsSubmitting(true);\n setError(null);\n setIsSuccess(false);\n\n try {\n await client.submitFeedback({\n ...payload,\n sessionId,\n });\n setIsSuccess(true);\n return true;\n } catch (err: any) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return false;\n } finally {\n setIsSubmitting(false);\n }\n },\n [client, sessionId]\n );\n\n const reset = useCallback(() => {\n setIsSubmitting(false);\n setIsSuccess(false);\n setError(null);\n }, []);\n\n return {\n submitFeedback,\n isSubmitting,\n isSuccess,\n error,\n reset,\n };\n}\n\n","\"use client\";\n\nimport { useState, useCallback } from \"react\";\nimport { useBotzki } from \"../context\";\n\nexport interface LeadCapturePayload {\n email: string;\n name?: string;\n phone?: string;\n company?: string;\n notes?: string;\n metadata?: Record<string, unknown>;\n customData?: Record<string, unknown>;\n}\n\nexport interface UseLeadCaptureReturn {\n captureLead: (payload: LeadCapturePayload) => Promise<boolean>;\n isSubmitting: boolean;\n isSuccess: boolean;\n error: Error | null;\n reset: () => void;\n}\n\n/**\n * Hook to capture customer lead contact details directly from custom React forms or chat widgets.\n */\nexport function useLeadCapture(): UseLeadCaptureReturn {\n const { client, sessionId } = useBotzki();\n const [isSubmitting, setIsSubmitting] = useState<boolean>(false);\n const [isSuccess, setIsSuccess] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n\n const captureLead = useCallback(\n async (payload: LeadCapturePayload): Promise<boolean> => {\n setIsSubmitting(true);\n setError(null);\n setIsSuccess(false);\n\n try {\n await client.captureLead({\n ...payload,\n sessionId,\n });\n setIsSuccess(true);\n return true;\n } catch (err: any) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return false;\n } finally {\n setIsSubmitting(false);\n }\n },\n [client, sessionId]\n );\n\n const reset = useCallback(() => {\n setIsSubmitting(false);\n setIsSuccess(false);\n setError(null);\n }, []);\n\n return {\n captureLead,\n isSubmitting,\n isSuccess,\n error,\n reset,\n };\n}\n","\"use client\";\n\nimport { useState, useCallback } from \"react\";\nimport { useBotzki } from \"../context\";\n\nexport interface UseVoiceTranscriptionReturn {\n transcribe: (audio: Blob | File) => Promise<string | null>;\n isTranscribing: boolean;\n transcript: string | null;\n error: Error | null;\n reset: () => void;\n}\n\n/**\n * Hook to transcribe audio recordings directly to text using the Botzki AI audio transcription endpoint.\n */\nexport function useVoiceTranscription(): UseVoiceTranscriptionReturn {\n const { client } = useBotzki();\n const [isTranscribing, setIsTranscribing] = useState<boolean>(false);\n const [transcript, setTranscript] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n const transcribe = useCallback(\n async (audio: Blob | File): Promise<string | null> => {\n setIsTranscribing(true);\n setError(null);\n\n try {\n const res = await client.transcribeAudio(audio);\n const transcriptText = res.text || \"\";\n setTranscript(transcriptText);\n return transcriptText;\n } catch (err: any) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return null;\n } finally {\n setIsTranscribing(false);\n }\n },\n [client]\n );\n\n const reset = useCallback(() => {\n setIsTranscribing(false);\n setTranscript(null);\n setError(null);\n }, []);\n\n return {\n transcribe,\n isTranscribing,\n transcript,\n error,\n reset,\n };\n}\n"]}