@idevconn/ai-chat-client 0.1.2

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,636 @@
1
+ // src/standalone/index.ts
2
+ import React4 from "react";
3
+ import { createRoot } from "react-dom/client";
4
+
5
+ // src/react/AiChat.tsx
6
+ import { useSyncExternalStore, useCallback as useCallback4 } from "react";
7
+
8
+ // src/hooks/use-chat.ts
9
+ import { useCallback as useCallback2, useRef as useRef2, useState as useState2 } from "react";
10
+
11
+ // src/hooks/use-sse-stream.ts
12
+ import { useCallback, useRef, useState } from "react";
13
+ function useSseStream(options) {
14
+ const [isStreaming, setIsStreaming] = useState(false);
15
+ const abortRef = useRef(null);
16
+ const abort = useCallback(() => {
17
+ abortRef.current?.abort();
18
+ abortRef.current = null;
19
+ setIsStreaming(false);
20
+ }, []);
21
+ const streamMessage = useCallback(
22
+ async (sessionId, message, onToken, onDone, onError) => {
23
+ abort();
24
+ const controller = new AbortController();
25
+ abortRef.current = controller;
26
+ setIsStreaming(true);
27
+ try {
28
+ const response = await fetch(options.endpoint, {
29
+ method: "POST",
30
+ headers: {
31
+ "Content-Type": "application/json",
32
+ ...options.headers
33
+ },
34
+ body: JSON.stringify({ sessionId, message }),
35
+ signal: controller.signal
36
+ });
37
+ if (!response.ok) {
38
+ onError(`Server error: ${response.status}`);
39
+ setIsStreaming(false);
40
+ return;
41
+ }
42
+ const reader = response.body?.getReader();
43
+ if (!reader) {
44
+ onError("No response body");
45
+ setIsStreaming(false);
46
+ return;
47
+ }
48
+ const decoder = new TextDecoder();
49
+ let buffer = "";
50
+ while (true) {
51
+ const { done, value } = await reader.read();
52
+ if (done) break;
53
+ buffer += decoder.decode(value, { stream: true });
54
+ const lines = buffer.split("\n");
55
+ buffer = lines.pop() || "";
56
+ for (const line of lines) {
57
+ if (!line.startsWith("data: ")) continue;
58
+ const data = line.slice(6).trim();
59
+ if (!data || data === "[DONE]") continue;
60
+ try {
61
+ const event = JSON.parse(data);
62
+ switch (event.type) {
63
+ case "token":
64
+ if (event.content) onToken(event.content);
65
+ break;
66
+ case "done":
67
+ onDone();
68
+ setIsStreaming(false);
69
+ return;
70
+ case "error":
71
+ onError(event.error || "Unknown error");
72
+ setIsStreaming(false);
73
+ return;
74
+ }
75
+ } catch {
76
+ }
77
+ }
78
+ }
79
+ onDone();
80
+ } catch (error) {
81
+ if (error.name !== "AbortError") {
82
+ onError(error.message || "Connection failed");
83
+ }
84
+ }
85
+ setIsStreaming(false);
86
+ },
87
+ [options.endpoint, options.headers, abort]
88
+ );
89
+ return { isStreaming, streamMessage, abort };
90
+ }
91
+
92
+ // src/lib/utils.ts
93
+ function generateId() {
94
+ return crypto.randomUUID?.() || Math.random().toString(36).slice(2);
95
+ }
96
+
97
+ // src/hooks/use-chat.ts
98
+ function useChat(config) {
99
+ const [messages, setMessages] = useState2([]);
100
+ const sessionIdRef = useRef2(generateId());
101
+ const headers = {};
102
+ if (config.apiKey) headers["x-api-key"] = config.apiKey;
103
+ if (config.token) headers["Authorization"] = `Bearer ${config.token}`;
104
+ const { isStreaming, streamMessage } = useSseStream({
105
+ endpoint: config.endpoint,
106
+ headers
107
+ });
108
+ const sendMessage = useCallback2(
109
+ (text) => {
110
+ if (!text.trim() || isStreaming) return;
111
+ const userMsg = {
112
+ id: generateId(),
113
+ role: "user",
114
+ content: text,
115
+ timestamp: Date.now()
116
+ };
117
+ const assistantMsg = {
118
+ id: generateId(),
119
+ role: "assistant",
120
+ content: "",
121
+ timestamp: Date.now(),
122
+ streaming: true
123
+ };
124
+ setMessages((prev) => [...prev, userMsg, assistantMsg]);
125
+ streamMessage(
126
+ sessionIdRef.current,
127
+ text,
128
+ (token) => {
129
+ setMessages((prev) => {
130
+ const updated = [...prev];
131
+ const last = updated[updated.length - 1];
132
+ if (last && last.role === "assistant") {
133
+ updated[updated.length - 1] = {
134
+ ...last,
135
+ content: last.content + token
136
+ };
137
+ }
138
+ return updated;
139
+ });
140
+ },
141
+ () => {
142
+ setMessages((prev) => {
143
+ const updated = [...prev];
144
+ const last = updated[updated.length - 1];
145
+ if (last && last.role === "assistant") {
146
+ updated[updated.length - 1] = {
147
+ ...last,
148
+ streaming: false
149
+ };
150
+ }
151
+ return updated;
152
+ });
153
+ },
154
+ (error) => {
155
+ setMessages((prev) => {
156
+ const updated = [...prev];
157
+ const last = updated[updated.length - 1];
158
+ if (last && last.role === "assistant") {
159
+ updated[updated.length - 1] = {
160
+ ...last,
161
+ content: `Error: ${error}`,
162
+ streaming: false
163
+ };
164
+ }
165
+ return updated;
166
+ });
167
+ }
168
+ );
169
+ },
170
+ [isStreaming, streamMessage]
171
+ );
172
+ const clearMessages = useCallback2(() => {
173
+ setMessages([]);
174
+ sessionIdRef.current = generateId();
175
+ }, []);
176
+ return { messages, isStreaming, sendMessage, clearMessages };
177
+ }
178
+
179
+ // src/react/ChatFab.tsx
180
+ import { jsx } from "react/jsx-runtime";
181
+ function ChatFab({
182
+ isOpen,
183
+ onClick,
184
+ primaryColor,
185
+ position = "bottom-right"
186
+ }) {
187
+ return /* @__PURE__ */ jsx(
188
+ "button",
189
+ {
190
+ onClick,
191
+ style: {
192
+ position: "fixed",
193
+ zIndex: 9999,
194
+ bottom: "16px",
195
+ right: position === "bottom-right" ? "16px" : "auto",
196
+ left: position === "bottom-left" ? "16px" : "auto",
197
+ display: "flex",
198
+ alignItems: "center",
199
+ justifyContent: "center",
200
+ width: "56px",
201
+ height: "56px",
202
+ borderRadius: "50%",
203
+ border: "none",
204
+ cursor: "pointer",
205
+ boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
206
+ backgroundColor: primaryColor || "#6366f1",
207
+ transition: "transform 0.2s"
208
+ },
209
+ "aria-label": isOpen ? "Close chat" : "Open chat",
210
+ children: /* @__PURE__ */ jsx(
211
+ "svg",
212
+ {
213
+ style: { width: "24px", height: "24px", color: "white" },
214
+ fill: "none",
215
+ viewBox: "0 0 24 24",
216
+ stroke: "currentColor",
217
+ strokeWidth: 2,
218
+ children: isOpen ? /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18L18 6M6 6l12 12" }) : /* @__PURE__ */ jsx(
219
+ "path",
220
+ {
221
+ strokeLinecap: "round",
222
+ strokeLinejoin: "round",
223
+ d: "M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
224
+ }
225
+ )
226
+ }
227
+ )
228
+ }
229
+ );
230
+ }
231
+
232
+ // src/react/ChatHeader.tsx
233
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
234
+ function ChatHeader({ botName, botAvatar, primaryColor, onClose }) {
235
+ return /* @__PURE__ */ jsxs(
236
+ "div",
237
+ {
238
+ style: {
239
+ display: "flex",
240
+ alignItems: "center",
241
+ justifyContent: "space-between",
242
+ padding: "12px 16px",
243
+ borderBottom: "1px solid #e5e7eb",
244
+ backgroundColor: primaryColor || "#6366f1"
245
+ },
246
+ children: [
247
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", alignItems: "center", gap: "8px" }, children: [
248
+ botAvatar && /* @__PURE__ */ jsx2("span", { style: { fontSize: "18px" }, children: botAvatar }),
249
+ /* @__PURE__ */ jsx2("span", { style: { color: "white", fontWeight: 500, fontSize: "14px" }, children: botName || "AI Assistant" })
250
+ ] }),
251
+ /* @__PURE__ */ jsx2(
252
+ "button",
253
+ {
254
+ onClick: onClose,
255
+ style: {
256
+ background: "transparent",
257
+ border: "none",
258
+ cursor: "pointer",
259
+ padding: "4px",
260
+ borderRadius: "4px",
261
+ color: "rgba(255,255,255,0.8)"
262
+ },
263
+ "aria-label": "Close chat",
264
+ children: /* @__PURE__ */ jsx2(
265
+ "svg",
266
+ {
267
+ style: { width: "20px", height: "20px" },
268
+ fill: "none",
269
+ viewBox: "0 0 24 24",
270
+ stroke: "currentColor",
271
+ strokeWidth: 2,
272
+ children: /* @__PURE__ */ jsx2("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18L18 6M6 6l12 12" })
273
+ }
274
+ )
275
+ }
276
+ )
277
+ ]
278
+ }
279
+ );
280
+ }
281
+
282
+ // src/react/MessageList.tsx
283
+ import { useEffect, useRef as useRef3 } from "react";
284
+
285
+ // src/react/UserMessage.tsx
286
+ import { jsx as jsx3 } from "react/jsx-runtime";
287
+ function UserMessage({ content }) {
288
+ return /* @__PURE__ */ jsx3("div", { style: { display: "flex", justifyContent: "flex-end", marginBottom: "12px" }, children: /* @__PURE__ */ jsx3(
289
+ "div",
290
+ {
291
+ style: {
292
+ maxWidth: "80%",
293
+ borderRadius: "8px",
294
+ padding: "8px 16px",
295
+ backgroundColor: "#6366f1",
296
+ color: "white",
297
+ fontSize: "14px"
298
+ },
299
+ children: content
300
+ }
301
+ ) });
302
+ }
303
+
304
+ // src/react/BotMessage.tsx
305
+ import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
306
+ function BotMessage({ content, streaming }) {
307
+ return /* @__PURE__ */ jsx4("div", { style: { display: "flex", justifyContent: "flex-start", marginBottom: "12px" }, children: /* @__PURE__ */ jsxs2(
308
+ "div",
309
+ {
310
+ style: {
311
+ maxWidth: "80%",
312
+ borderRadius: "8px",
313
+ padding: "8px 16px",
314
+ backgroundColor: "#f3f4f6",
315
+ color: "#1f2937",
316
+ fontSize: "14px"
317
+ },
318
+ children: [
319
+ content || streaming && "...",
320
+ streaming && content && /* @__PURE__ */ jsx4(
321
+ "span",
322
+ {
323
+ style: {
324
+ display: "inline-block",
325
+ width: "6px",
326
+ height: "16px",
327
+ marginLeft: "2px",
328
+ backgroundColor: "#9ca3af",
329
+ animation: "pulse 1s infinite"
330
+ }
331
+ }
332
+ )
333
+ ]
334
+ }
335
+ ) });
336
+ }
337
+
338
+ // src/react/MessageList.tsx
339
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
340
+ function MessageList({ messages }) {
341
+ const bottomRef = useRef3(null);
342
+ useEffect(() => {
343
+ bottomRef.current?.scrollIntoView({ behavior: "smooth" });
344
+ }, [messages]);
345
+ return /* @__PURE__ */ jsxs3("div", { style: { flex: 1, overflowY: "auto", padding: "16px" }, children: [
346
+ messages.map(
347
+ (msg) => msg.role === "user" ? /* @__PURE__ */ jsx5(UserMessage, { content: msg.content }, msg.id) : /* @__PURE__ */ jsx5(BotMessage, { content: msg.content, streaming: msg.streaming }, msg.id)
348
+ ),
349
+ /* @__PURE__ */ jsx5("div", { ref: bottomRef })
350
+ ] });
351
+ }
352
+
353
+ // src/react/EmptyState.tsx
354
+ import { jsx as jsx6, jsxs as jsxs4 } from "react/jsx-runtime";
355
+ function EmptyState({ welcomeMessage, starterTopics, onTopicClick }) {
356
+ return /* @__PURE__ */ jsxs4(
357
+ "div",
358
+ {
359
+ style: {
360
+ display: "flex",
361
+ flexDirection: "column",
362
+ alignItems: "center",
363
+ justifyContent: "center",
364
+ height: "100%",
365
+ padding: "24px",
366
+ textAlign: "center"
367
+ },
368
+ children: [
369
+ /* @__PURE__ */ jsx6("p", { style: { color: "#6b7280", fontSize: "14px", marginBottom: "24px" }, children: welcomeMessage || "Hi! How can I help you today?" }),
370
+ starterTopics && starterTopics.length > 0 && /* @__PURE__ */ jsx6(
371
+ "div",
372
+ {
373
+ style: {
374
+ display: "flex",
375
+ flexDirection: "column",
376
+ gap: "8px",
377
+ width: "100%",
378
+ maxWidth: "280px"
379
+ },
380
+ children: starterTopics.map((topic, i) => /* @__PURE__ */ jsxs4(
381
+ "button",
382
+ {
383
+ onClick: () => onTopicClick(topic.message),
384
+ style: {
385
+ display: "flex",
386
+ alignItems: "center",
387
+ gap: "8px",
388
+ padding: "12px 16px",
389
+ textAlign: "left",
390
+ fontSize: "14px",
391
+ borderRadius: "8px",
392
+ border: "1px solid #e5e7eb",
393
+ backgroundColor: "white",
394
+ cursor: "pointer"
395
+ },
396
+ children: [
397
+ topic.icon && /* @__PURE__ */ jsx6("span", { children: topic.icon }),
398
+ /* @__PURE__ */ jsxs4("div", { children: [
399
+ /* @__PURE__ */ jsx6("span", { style: { color: "#1f2937", fontWeight: 500 }, children: topic.label }),
400
+ topic.description && /* @__PURE__ */ jsx6(
401
+ "span",
402
+ {
403
+ style: {
404
+ display: "block",
405
+ fontSize: "12px",
406
+ color: "#6b7280",
407
+ marginTop: "2px"
408
+ },
409
+ children: topic.description
410
+ }
411
+ )
412
+ ] })
413
+ ]
414
+ },
415
+ i
416
+ ))
417
+ }
418
+ )
419
+ ]
420
+ }
421
+ );
422
+ }
423
+
424
+ // src/react/ChatInput.tsx
425
+ import { useState as useState3, useCallback as useCallback3 } from "react";
426
+ import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
427
+ function ChatInput({ onSend, disabled, placeholder }) {
428
+ const [value, setValue] = useState3("");
429
+ const handleSend = useCallback3(() => {
430
+ if (!value.trim() || disabled) return;
431
+ onSend(value.trim());
432
+ setValue("");
433
+ }, [value, disabled, onSend]);
434
+ const handleKeyDown = useCallback3(
435
+ (e) => {
436
+ if (e.key === "Enter" && !e.shiftKey) {
437
+ e.preventDefault();
438
+ handleSend();
439
+ }
440
+ },
441
+ [handleSend]
442
+ );
443
+ return /* @__PURE__ */ jsxs5(
444
+ "div",
445
+ {
446
+ style: {
447
+ display: "flex",
448
+ alignItems: "center",
449
+ gap: "8px",
450
+ padding: "12px",
451
+ borderTop: "1px solid #e5e7eb"
452
+ },
453
+ children: [
454
+ /* @__PURE__ */ jsx7(
455
+ "input",
456
+ {
457
+ type: "text",
458
+ value,
459
+ onChange: (e) => setValue(e.target.value),
460
+ onKeyDown: handleKeyDown,
461
+ disabled,
462
+ placeholder: placeholder || "Type your message...",
463
+ style: {
464
+ flex: 1,
465
+ padding: "8px 12px",
466
+ fontSize: "14px",
467
+ border: "1px solid #e5e7eb",
468
+ borderRadius: "8px",
469
+ outline: "none",
470
+ opacity: disabled ? 0.5 : 1
471
+ }
472
+ }
473
+ ),
474
+ /* @__PURE__ */ jsx7(
475
+ "button",
476
+ {
477
+ onClick: handleSend,
478
+ disabled: disabled || !value.trim(),
479
+ style: {
480
+ display: "flex",
481
+ alignItems: "center",
482
+ justifyContent: "center",
483
+ width: "36px",
484
+ height: "36px",
485
+ borderRadius: "8px",
486
+ border: "none",
487
+ cursor: disabled || !value.trim() ? "not-allowed" : "pointer",
488
+ backgroundColor: "#6366f1",
489
+ opacity: disabled || !value.trim() ? 0.5 : 1
490
+ },
491
+ "aria-label": "Send message",
492
+ children: /* @__PURE__ */ jsx7(
493
+ "svg",
494
+ {
495
+ style: { width: "16px", height: "16px", color: "white" },
496
+ fill: "none",
497
+ viewBox: "0 0 24 24",
498
+ stroke: "currentColor",
499
+ strokeWidth: 2,
500
+ children: /* @__PURE__ */ jsx7("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 19l9 2-9-18-9 18 9-2zm0 0v-8" })
501
+ }
502
+ )
503
+ }
504
+ )
505
+ ]
506
+ }
507
+ );
508
+ }
509
+
510
+ // src/react/ChatPanel.tsx
511
+ import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
512
+ function ChatPanel({ config, messages, isStreaming, onSend, onClose }) {
513
+ const position = config.theme?.position || "bottom-right";
514
+ return /* @__PURE__ */ jsxs6(
515
+ "div",
516
+ {
517
+ style: {
518
+ position: "fixed",
519
+ zIndex: 9999,
520
+ bottom: "80px",
521
+ right: position === "bottom-right" ? "16px" : "auto",
522
+ left: position === "bottom-left" ? "16px" : "auto",
523
+ width: config.theme?.width || "380px",
524
+ height: config.theme?.height || "560px",
525
+ borderRadius: config.theme?.borderRadius || "12px",
526
+ backgroundColor: "#ffffff",
527
+ boxShadow: "0 25px 50px -12px rgba(0,0,0,0.25)",
528
+ border: "1px solid #e5e7eb",
529
+ display: "flex",
530
+ flexDirection: "column",
531
+ overflow: "hidden"
532
+ },
533
+ children: [
534
+ /* @__PURE__ */ jsx8(
535
+ ChatHeader,
536
+ {
537
+ botName: config.botName,
538
+ botAvatar: config.botAvatar,
539
+ primaryColor: config.theme?.primaryColor,
540
+ onClose
541
+ }
542
+ ),
543
+ messages.length === 0 ? /* @__PURE__ */ jsx8(
544
+ EmptyState,
545
+ {
546
+ welcomeMessage: config.welcomeMessage,
547
+ starterTopics: config.starterTopics,
548
+ onTopicClick: onSend
549
+ }
550
+ ) : /* @__PURE__ */ jsx8(MessageList, { messages }),
551
+ /* @__PURE__ */ jsx8(ChatInput, { onSend, disabled: isStreaming, placeholder: config.placeholder })
552
+ ]
553
+ }
554
+ );
555
+ }
556
+
557
+ // src/react/AiChat.tsx
558
+ import { Fragment, jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
559
+ var _isOpen = false;
560
+ var listeners = /* @__PURE__ */ new Set();
561
+ function setOpen(value) {
562
+ _isOpen = value;
563
+ listeners.forEach((l) => l());
564
+ }
565
+ function subscribe(listener) {
566
+ listeners.add(listener);
567
+ return () => listeners.delete(listener);
568
+ }
569
+ function getSnapshot() {
570
+ return _isOpen;
571
+ }
572
+ function AiChat(props) {
573
+ const isOpen = useSyncExternalStore(subscribe, getSnapshot);
574
+ const { messages, isStreaming, sendMessage } = useChat(props);
575
+ const toggle = useCallback4((e) => {
576
+ e.preventDefault();
577
+ e.stopPropagation();
578
+ setOpen(!_isOpen);
579
+ }, []);
580
+ return /* @__PURE__ */ jsxs7(Fragment, { children: [
581
+ isOpen && /* @__PURE__ */ jsx9(
582
+ ChatPanel,
583
+ {
584
+ config: props,
585
+ messages,
586
+ isStreaming,
587
+ onSend: sendMessage,
588
+ onClose: () => setOpen(false)
589
+ }
590
+ ),
591
+ /* @__PURE__ */ jsx9(
592
+ ChatFab,
593
+ {
594
+ isOpen,
595
+ onClick: toggle,
596
+ primaryColor: props.theme?.primaryColor,
597
+ position: props.theme?.position
598
+ }
599
+ )
600
+ ] });
601
+ }
602
+
603
+ // src/standalone/index.ts
604
+ var root = null;
605
+ var container = null;
606
+ var AiChatStandalone = {
607
+ init(config) {
608
+ if (container) {
609
+ this.destroy();
610
+ }
611
+ container = document.createElement("div");
612
+ container.id = "ai-chat-widget-root";
613
+ document.body.appendChild(container);
614
+ root = createRoot(container);
615
+ root.render(React4.createElement(AiChat, config));
616
+ return {
617
+ destroy: () => this.destroy()
618
+ };
619
+ },
620
+ destroy() {
621
+ if (root) {
622
+ root.unmount();
623
+ root = null;
624
+ }
625
+ if (container) {
626
+ container.remove();
627
+ container = null;
628
+ }
629
+ }
630
+ };
631
+ if (typeof window !== "undefined") {
632
+ window.AiChat = AiChatStandalone;
633
+ }
634
+ export {
635
+ AiChatStandalone
636
+ };
@@ -0,0 +1,49 @@
1
+ interface ChatStreamEvent {
2
+ type: 'token' | 'tool_call' | 'tool_result' | 'done' | 'error';
3
+ content?: string;
4
+ usage?: {
5
+ promptTokens: number;
6
+ completionTokens: number;
7
+ totalTokens: number;
8
+ };
9
+ error?: string;
10
+ }
11
+ interface StarterTopic {
12
+ label: string;
13
+ message: string;
14
+ icon?: string;
15
+ description?: string;
16
+ }
17
+ interface ThemeConfig {
18
+ primaryColor?: string;
19
+ borderRadius?: string;
20
+ fontFamily?: string;
21
+ darkMode?: boolean;
22
+ position?: 'bottom-right' | 'bottom-left';
23
+ zIndex?: number;
24
+ width?: string;
25
+ height?: string;
26
+ }
27
+ interface AiChatConfig {
28
+ endpoint: string;
29
+ apiKey?: string;
30
+ token?: string;
31
+ getToken?: () => Promise<string>;
32
+ theme?: ThemeConfig;
33
+ welcomeMessage?: string;
34
+ placeholder?: string;
35
+ starterTopics?: StarterTopic[];
36
+ botName?: string;
37
+ botAvatar?: string;
38
+ persistSession?: boolean;
39
+ showTimestamps?: boolean;
40
+ }
41
+ interface ChatMessageUI {
42
+ id: string;
43
+ role: 'user' | 'assistant';
44
+ content: string;
45
+ timestamp: number;
46
+ streaming?: boolean;
47
+ }
48
+
49
+ export type { AiChatConfig as A, ChatMessageUI as C, StarterTopic as S, ThemeConfig as T, ChatStreamEvent as a };