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