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