@elqnt/chat 3.3.0 → 3.5.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.
package/dist/index.mjs CHANGED
@@ -1,1475 +1,3 @@
1
- "use client";
2
-
3
- // hooks/use-chat.ts
4
- import { useCallback, useEffect, useRef, useState } from "react";
5
-
6
- // transport/types.ts
7
- function createLogger(debug = false) {
8
- return {
9
- debug: debug ? console.log.bind(console, "[chat]") : () => {
10
- },
11
- info: console.info.bind(console, "[chat]"),
12
- warn: console.warn.bind(console, "[chat]"),
13
- error: console.error.bind(console, "[chat]")
14
- };
15
- }
16
- var DEFAULT_RETRY_CONFIG = {
17
- maxRetries: 10,
18
- intervals: [1e3, 2e3, 5e3],
19
- backoffMultiplier: 1.5,
20
- maxBackoffTime: 3e4
21
- };
22
- function calculateRetryInterval(retryCount, config = DEFAULT_RETRY_CONFIG) {
23
- const {
24
- intervals = DEFAULT_RETRY_CONFIG.intervals,
25
- backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,
26
- maxBackoffTime = DEFAULT_RETRY_CONFIG.maxBackoffTime
27
- } = config;
28
- if (retryCount < intervals.length) {
29
- return intervals[retryCount];
30
- }
31
- const baseInterval = intervals[intervals.length - 1] || 5e3;
32
- const backoffTime = baseInterval * Math.pow(backoffMultiplier, retryCount - intervals.length + 1);
33
- return Math.min(backoffTime, maxBackoffTime);
34
- }
35
-
36
- // transport/sse.ts
37
- function createSSETransport(options = {}) {
38
- const {
39
- retryConfig = DEFAULT_RETRY_CONFIG,
40
- debug = false,
41
- logger = createLogger(debug)
42
- } = options;
43
- let eventSource;
44
- let config;
45
- let state = "disconnected";
46
- let error;
47
- let retryCount = 0;
48
- let reconnectTimeout;
49
- let intentionalDisconnect = false;
50
- const metrics = {
51
- latency: 0,
52
- messagesSent: 0,
53
- messagesReceived: 0,
54
- messagesQueued: 0,
55
- reconnectCount: 0,
56
- transportType: "sse"
57
- };
58
- const globalHandlers = /* @__PURE__ */ new Set();
59
- const typeHandlers = /* @__PURE__ */ new Map();
60
- function emit(event) {
61
- metrics.messagesReceived++;
62
- metrics.lastMessageAt = Date.now();
63
- globalHandlers.forEach((handler) => {
64
- try {
65
- handler(event);
66
- } catch (err) {
67
- logger.error("Error in message handler:", err);
68
- }
69
- });
70
- const handlers = typeHandlers.get(event.type);
71
- if (handlers) {
72
- handlers.forEach((handler) => {
73
- try {
74
- handler(event);
75
- } catch (err) {
76
- logger.error(`Error in ${event.type} handler:`, err);
77
- }
78
- });
79
- }
80
- }
81
- async function sendRest(endpoint, body) {
82
- if (!config) {
83
- throw new Error("Transport not connected");
84
- }
85
- const url = `${config.baseUrl}/${endpoint}`;
86
- logger.debug(`POST ${endpoint}`, body);
87
- const response = await fetch(url, {
88
- method: "POST",
89
- headers: { "Content-Type": "application/json" },
90
- body: JSON.stringify(body)
91
- });
92
- if (!response.ok) {
93
- const errorText = await response.text();
94
- throw new Error(`API error: ${response.status} - ${errorText}`);
95
- }
96
- const json = await response.json();
97
- if (json && typeof json === "object" && "data" in json) {
98
- return json.data;
99
- }
100
- return json;
101
- }
102
- function handleMessage(event) {
103
- if (!event.data || event.data === "") return;
104
- try {
105
- const data = JSON.parse(event.data);
106
- logger.debug("Received:", data.type);
107
- emit(data);
108
- } catch (err) {
109
- logger.error("Failed to parse SSE message:", err);
110
- }
111
- }
112
- function setupEventListeners(es) {
113
- es.addEventListener("message", handleMessage);
114
- const eventTypes = [
115
- "error",
116
- "reconnected",
117
- "typing",
118
- "stopped_typing",
119
- "waiting",
120
- "waiting_for_agent",
121
- "human_agent_joined",
122
- "human_agent_left",
123
- "chat_ended",
124
- "chat_updated",
125
- "chat_removed",
126
- "load_chat_response",
127
- "new_chat_created",
128
- "show_csat_survey",
129
- "csat_response",
130
- "user_suggested_actions",
131
- "user_suggested_action_selected",
132
- "agent_execution_started",
133
- "agent_execution_ended",
134
- "agent_context_update",
135
- "load_agent_context_response",
136
- "plan_pending_approval",
137
- "plan_approved",
138
- "plan_rejected",
139
- "step_started",
140
- "step_completed",
141
- "step_failed",
142
- "plan_completed",
143
- "skills_changed",
144
- "summary_update",
145
- "message_status_update",
146
- "delivered",
147
- "read",
148
- "sync_metadata_response",
149
- "sync_user_session_response",
150
- "client_action",
151
- "client_action_callback",
152
- "attachment_processing_started",
153
- "attachment_processing_progress",
154
- "attachment_processing_complete",
155
- "attachment_processing_error",
156
- "observer_joined",
157
- "observer_left",
158
- "block_user",
159
- "message_edited",
160
- "message_deleted",
161
- "message_reaction",
162
- "user_presence_changed",
163
- "online_users",
164
- "get_agents_response",
165
- "room_created",
166
- "room_updated",
167
- "room_deleted",
168
- "rooms_response",
169
- "room_user_joined",
170
- "room_user_left",
171
- "user_invited"
172
- ];
173
- eventTypes.forEach((type) => {
174
- es.addEventListener(type, handleMessage);
175
- });
176
- }
177
- function scheduleReconnect() {
178
- if (intentionalDisconnect || !config) return;
179
- const maxRetries = retryConfig.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries;
180
- if (retryCount >= maxRetries) {
181
- logger.error(`Max retries (${maxRetries}) exceeded`);
182
- error = {
183
- code: "CONNECTION_FAILED",
184
- message: `Max retries (${maxRetries}) exceeded`,
185
- retryable: false,
186
- timestamp: Date.now()
187
- };
188
- return;
189
- }
190
- const interval = calculateRetryInterval(retryCount, retryConfig);
191
- retryCount++;
192
- metrics.reconnectCount++;
193
- logger.info(`Reconnecting in ${interval}ms (attempt ${retryCount})`);
194
- state = "reconnecting";
195
- reconnectTimeout = setTimeout(() => {
196
- if (config) {
197
- transport.connect(config).catch((err) => {
198
- logger.error("Reconnect failed:", err);
199
- });
200
- }
201
- }, interval);
202
- }
203
- const transport = {
204
- async connect(cfg) {
205
- config = cfg;
206
- intentionalDisconnect = false;
207
- if (eventSource) {
208
- eventSource.close();
209
- eventSource = void 0;
210
- }
211
- if (reconnectTimeout) {
212
- clearTimeout(reconnectTimeout);
213
- reconnectTimeout = void 0;
214
- }
215
- state = retryCount > 0 ? "reconnecting" : "connecting";
216
- return new Promise((resolve, reject) => {
217
- const connectionStart = Date.now();
218
- const streamParams = new URLSearchParams({
219
- orgId: cfg.orgId,
220
- userId: cfg.userId,
221
- clientType: cfg.clientType
222
- });
223
- if (cfg.chatKey) streamParams.set("chatId", cfg.chatKey);
224
- const url = `${cfg.baseUrl}/stream?${streamParams.toString()}`;
225
- logger.debug("Connecting to:", url);
226
- const es = new EventSource(url);
227
- es.onopen = () => {
228
- const connectionTime = Date.now() - connectionStart;
229
- logger.info(`Connected in ${connectionTime}ms`);
230
- const wasReconnect = retryCount > 0;
231
- state = "connected";
232
- error = void 0;
233
- retryCount = 0;
234
- metrics.connectedAt = Date.now();
235
- metrics.latency = connectionTime;
236
- setupEventListeners(es);
237
- if (wasReconnect) {
238
- emit({
239
- type: "transport_reconnected",
240
- orgId: cfg.orgId,
241
- chatKey: cfg.chatKey || "",
242
- userId: cfg.userId,
243
- timestamp: Date.now()
244
- });
245
- }
246
- resolve();
247
- };
248
- es.onerror = () => {
249
- if (es.readyState === EventSource.CLOSED) {
250
- const sseError = {
251
- code: "CONNECTION_FAILED",
252
- message: "SSE connection failed",
253
- retryable: true,
254
- timestamp: Date.now()
255
- };
256
- error = sseError;
257
- metrics.lastError = sseError;
258
- state = "disconnected";
259
- if (!intentionalDisconnect) {
260
- scheduleReconnect();
261
- }
262
- if (retryCount === 0) {
263
- reject(sseError);
264
- }
265
- }
266
- };
267
- eventSource = es;
268
- });
269
- },
270
- disconnect(intentional = true) {
271
- logger.info("Disconnecting", { intentional });
272
- intentionalDisconnect = intentional;
273
- if (reconnectTimeout) {
274
- clearTimeout(reconnectTimeout);
275
- reconnectTimeout = void 0;
276
- }
277
- if (eventSource) {
278
- eventSource.close();
279
- eventSource = void 0;
280
- }
281
- state = "disconnected";
282
- retryCount = 0;
283
- },
284
- async send(event) {
285
- if (!config) {
286
- throw new Error("Transport not connected");
287
- }
288
- switch (event.type) {
289
- case "message":
290
- await sendRest("send", {
291
- orgId: event.orgId,
292
- chatKey: event.chatKey,
293
- userId: event.userId,
294
- message: event.message,
295
- ...event.data ? { data: event.data } : {}
296
- });
297
- break;
298
- case "typing":
299
- await sendRest("typing", {
300
- orgId: event.orgId,
301
- chatKey: event.chatKey,
302
- userId: event.userId,
303
- typing: true
304
- });
305
- break;
306
- case "stopped_typing":
307
- await sendRest("typing", {
308
- orgId: event.orgId,
309
- chatKey: event.chatKey,
310
- userId: event.userId,
311
- typing: false
312
- });
313
- break;
314
- case "load_chat":
315
- await sendRest("load", {
316
- orgId: event.orgId,
317
- chatKey: event.chatKey,
318
- userId: event.userId
319
- });
320
- break;
321
- case "new_chat":
322
- await sendRest("create", {
323
- orgId: event.orgId,
324
- userId: event.userId,
325
- metadata: event.data
326
- });
327
- break;
328
- case "end_chat":
329
- await sendRest("end", {
330
- orgId: event.orgId,
331
- chatKey: event.chatKey,
332
- userId: event.userId,
333
- data: event.data
334
- });
335
- break;
336
- default:
337
- await sendRest("event", {
338
- type: event.type,
339
- orgId: event.orgId,
340
- chatKey: event.chatKey,
341
- userId: event.userId,
342
- data: event.data
343
- });
344
- }
345
- metrics.messagesSent++;
346
- },
347
- async sendMessage(message) {
348
- if (!config) {
349
- throw new Error("Transport not connected");
350
- }
351
- await sendRest("send", {
352
- orgId: config.orgId,
353
- chatKey: config.chatKey,
354
- userId: config.userId,
355
- message
356
- });
357
- metrics.messagesSent++;
358
- },
359
- async createChat(options2) {
360
- if (!config) {
361
- throw new Error("Transport not connected");
362
- }
363
- const response = await sendRest("create", {
364
- orgId: options2.orgId,
365
- userId: options2.userId,
366
- metadata: options2.metadata
367
- });
368
- if (!response?.chatKey) {
369
- throw new Error("Failed to create chat: no chatKey returned");
370
- }
371
- return { chatKey: response.chatKey };
372
- },
373
- async loadChatData(options2) {
374
- if (!config) {
375
- throw new Error("Transport not connected");
376
- }
377
- const response = await sendRest("load", {
378
- orgId: options2.orgId,
379
- chatKey: options2.chatKey,
380
- userId: options2.userId
381
- });
382
- if (!response?.chat) {
383
- throw new Error("Failed to load chat: no chat data returned");
384
- }
385
- return {
386
- chat: response.chat,
387
- agentId: response.agentId
388
- };
389
- },
390
- onMessage(handler) {
391
- globalHandlers.add(handler);
392
- return () => globalHandlers.delete(handler);
393
- },
394
- on(eventType, handler) {
395
- if (!typeHandlers.has(eventType)) {
396
- typeHandlers.set(eventType, /* @__PURE__ */ new Set());
397
- }
398
- typeHandlers.get(eventType).add(handler);
399
- return () => {
400
- const handlers = typeHandlers.get(eventType);
401
- if (handlers) {
402
- handlers.delete(handler);
403
- if (handlers.size === 0) {
404
- typeHandlers.delete(eventType);
405
- }
406
- }
407
- };
408
- },
409
- getState() {
410
- return state;
411
- },
412
- getMetrics() {
413
- return { ...metrics };
414
- },
415
- getError() {
416
- return error;
417
- },
418
- clearError() {
419
- error = void 0;
420
- }
421
- };
422
- return transport;
423
- }
424
-
425
- // transport/sse-fetch.ts
426
- function createFetchSSETransport(options = {}) {
427
- const {
428
- retryConfig = DEFAULT_RETRY_CONFIG,
429
- debug = false,
430
- logger = createLogger(debug),
431
- customFetch = fetch
432
- } = options;
433
- let abortController;
434
- let config;
435
- let state = "disconnected";
436
- let error;
437
- let retryCount = 0;
438
- let reconnectTimeout;
439
- let intentionalDisconnect = false;
440
- const metrics = {
441
- latency: 0,
442
- messagesSent: 0,
443
- messagesReceived: 0,
444
- messagesQueued: 0,
445
- reconnectCount: 0,
446
- transportType: "sse-fetch"
447
- };
448
- const globalHandlers = /* @__PURE__ */ new Set();
449
- const typeHandlers = /* @__PURE__ */ new Map();
450
- function emit(event) {
451
- metrics.messagesReceived++;
452
- metrics.lastMessageAt = Date.now();
453
- globalHandlers.forEach((handler) => {
454
- try {
455
- handler(event);
456
- } catch (err) {
457
- logger.error("Error in message handler:", err);
458
- }
459
- });
460
- const handlers = typeHandlers.get(event.type);
461
- if (handlers) {
462
- handlers.forEach((handler) => {
463
- try {
464
- handler(event);
465
- } catch (err) {
466
- logger.error(`Error in ${event.type} handler:`, err);
467
- }
468
- });
469
- }
470
- }
471
- async function sendRest(endpoint, body) {
472
- if (!config) {
473
- throw new Error("Transport not connected");
474
- }
475
- const url = `${config.baseUrl}/${endpoint}`;
476
- logger.debug(`POST ${endpoint}`, body);
477
- const response = await customFetch(url, {
478
- method: "POST",
479
- headers: { "Content-Type": "application/json" },
480
- body: JSON.stringify(body)
481
- });
482
- if (!response.ok) {
483
- const errorText = await response.text();
484
- throw new Error(`API error: ${response.status} - ${errorText}`);
485
- }
486
- const json = await response.json();
487
- if (json && typeof json === "object" && "data" in json) {
488
- return json.data;
489
- }
490
- return json;
491
- }
492
- function parseSSEChunk(chunk) {
493
- const events = [];
494
- const lines = chunk.split("\n");
495
- let eventType = "message";
496
- let data = "";
497
- for (const line of lines) {
498
- if (line.startsWith("event:")) {
499
- eventType = line.slice(6).trim();
500
- } else if (line.startsWith("data:")) {
501
- data = line.slice(5).trim();
502
- } else if (line === "" && data) {
503
- try {
504
- const parsed = JSON.parse(data);
505
- events.push(parsed);
506
- } catch {
507
- logger.warn("Failed to parse SSE data:", data);
508
- }
509
- eventType = "message";
510
- data = "";
511
- }
512
- }
513
- return events;
514
- }
515
- async function startStream(cfg) {
516
- const streamParams = new URLSearchParams({
517
- orgId: cfg.orgId,
518
- userId: cfg.userId,
519
- clientType: cfg.clientType
520
- });
521
- if (cfg.chatKey) streamParams.set("chatId", cfg.chatKey);
522
- const url = `${cfg.baseUrl}/stream?${streamParams.toString()}`;
523
- logger.debug("Connecting to:", url);
524
- abortController = new AbortController();
525
- const response = await customFetch(url, {
526
- method: "GET",
527
- headers: {
528
- Accept: "text/event-stream",
529
- "Cache-Control": "no-cache"
530
- },
531
- signal: abortController.signal
532
- });
533
- if (!response.ok) {
534
- throw new Error(`Stream connection failed: ${response.status}`);
535
- }
536
- if (!response.body) {
537
- throw new Error("Response body is null - ReadableStream not supported");
538
- }
539
- const reader = response.body.getReader();
540
- const decoder = new TextDecoder();
541
- let buffer = "";
542
- const readStream = async () => {
543
- try {
544
- while (true) {
545
- const { done, value } = await reader.read();
546
- if (done) {
547
- logger.info("Stream ended");
548
- break;
549
- }
550
- buffer += decoder.decode(value, { stream: true });
551
- const lastNewline = buffer.lastIndexOf("\n\n");
552
- if (lastNewline !== -1) {
553
- const complete = buffer.slice(0, lastNewline + 2);
554
- buffer = buffer.slice(lastNewline + 2);
555
- const events = parseSSEChunk(complete);
556
- events.forEach(emit);
557
- }
558
- }
559
- } catch (err) {
560
- if (err.name === "AbortError") {
561
- logger.debug("Stream aborted");
562
- return;
563
- }
564
- logger.error("Stream error:", err);
565
- throw err;
566
- }
567
- if (!intentionalDisconnect) {
568
- state = "disconnected";
569
- scheduleReconnect();
570
- }
571
- };
572
- readStream().catch((err) => {
573
- if (!intentionalDisconnect) {
574
- error = {
575
- code: "CONNECTION_FAILED",
576
- message: err.message,
577
- retryable: true,
578
- timestamp: Date.now(),
579
- originalError: err
580
- };
581
- metrics.lastError = error;
582
- state = "disconnected";
583
- scheduleReconnect();
584
- }
585
- });
586
- }
587
- function scheduleReconnect() {
588
- if (intentionalDisconnect || !config) return;
589
- const maxRetries = retryConfig.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries;
590
- if (retryCount >= maxRetries) {
591
- logger.error(`Max retries (${maxRetries}) exceeded`);
592
- error = {
593
- code: "CONNECTION_FAILED",
594
- message: `Max retries (${maxRetries}) exceeded`,
595
- retryable: false,
596
- timestamp: Date.now()
597
- };
598
- return;
599
- }
600
- const interval = calculateRetryInterval(retryCount, retryConfig);
601
- retryCount++;
602
- metrics.reconnectCount++;
603
- logger.info(`Reconnecting in ${interval}ms (attempt ${retryCount})`);
604
- state = "reconnecting";
605
- reconnectTimeout = setTimeout(() => {
606
- if (config) {
607
- transport.connect(config).catch((err) => {
608
- logger.error("Reconnect failed:", err);
609
- });
610
- }
611
- }, interval);
612
- }
613
- const transport = {
614
- async connect(cfg) {
615
- config = cfg;
616
- intentionalDisconnect = false;
617
- if (abortController) {
618
- abortController.abort();
619
- abortController = void 0;
620
- }
621
- if (reconnectTimeout) {
622
- clearTimeout(reconnectTimeout);
623
- reconnectTimeout = void 0;
624
- }
625
- state = retryCount > 0 ? "reconnecting" : "connecting";
626
- const connectionStart = Date.now();
627
- try {
628
- const wasReconnect = retryCount > 0;
629
- await startStream(cfg);
630
- const connectionTime = Date.now() - connectionStart;
631
- logger.info(`Connected in ${connectionTime}ms`);
632
- state = "connected";
633
- error = void 0;
634
- retryCount = 0;
635
- metrics.connectedAt = Date.now();
636
- metrics.latency = connectionTime;
637
- if (wasReconnect) {
638
- emit({
639
- type: "transport_reconnected",
640
- orgId: cfg.orgId,
641
- chatKey: cfg.chatKey || "",
642
- userId: cfg.userId,
643
- timestamp: Date.now()
644
- });
645
- }
646
- } catch (err) {
647
- const connectError = {
648
- code: "CONNECTION_FAILED",
649
- message: err.message,
650
- retryable: true,
651
- timestamp: Date.now(),
652
- originalError: err
653
- };
654
- error = connectError;
655
- metrics.lastError = connectError;
656
- state = "disconnected";
657
- if (!intentionalDisconnect) {
658
- scheduleReconnect();
659
- }
660
- throw connectError;
661
- }
662
- },
663
- disconnect(intentional = true) {
664
- logger.info("Disconnecting", { intentional });
665
- intentionalDisconnect = intentional;
666
- if (reconnectTimeout) {
667
- clearTimeout(reconnectTimeout);
668
- reconnectTimeout = void 0;
669
- }
670
- if (abortController) {
671
- abortController.abort();
672
- abortController = void 0;
673
- }
674
- state = "disconnected";
675
- retryCount = 0;
676
- },
677
- async send(event) {
678
- if (!config) {
679
- throw new Error("Transport not connected");
680
- }
681
- switch (event.type) {
682
- case "message":
683
- await sendRest("send", {
684
- orgId: event.orgId,
685
- chatKey: event.chatKey,
686
- userId: event.userId,
687
- message: event.message,
688
- ...event.data ? { data: event.data } : {}
689
- });
690
- break;
691
- case "typing":
692
- await sendRest("typing", {
693
- orgId: event.orgId,
694
- chatKey: event.chatKey,
695
- userId: event.userId,
696
- typing: true
697
- });
698
- break;
699
- case "stopped_typing":
700
- await sendRest("typing", {
701
- orgId: event.orgId,
702
- chatKey: event.chatKey,
703
- userId: event.userId,
704
- typing: false
705
- });
706
- break;
707
- case "load_chat":
708
- await sendRest("load", {
709
- orgId: event.orgId,
710
- chatKey: event.chatKey,
711
- userId: event.userId
712
- });
713
- break;
714
- case "new_chat":
715
- await sendRest("create", {
716
- orgId: event.orgId,
717
- userId: event.userId,
718
- metadata: event.data
719
- });
720
- break;
721
- case "end_chat":
722
- await sendRest("end", {
723
- orgId: event.orgId,
724
- chatKey: event.chatKey,
725
- userId: event.userId,
726
- data: event.data
727
- });
728
- break;
729
- default:
730
- await sendRest("event", {
731
- type: event.type,
732
- orgId: event.orgId,
733
- chatKey: event.chatKey,
734
- userId: event.userId,
735
- data: event.data
736
- });
737
- }
738
- metrics.messagesSent++;
739
- },
740
- async sendMessage(message) {
741
- if (!config) {
742
- throw new Error("Transport not connected");
743
- }
744
- await sendRest("send", {
745
- orgId: config.orgId,
746
- chatKey: config.chatKey,
747
- userId: config.userId,
748
- message
749
- });
750
- metrics.messagesSent++;
751
- },
752
- async createChat(options2) {
753
- if (!config) {
754
- throw new Error("Transport not connected");
755
- }
756
- const response = await sendRest("create", {
757
- orgId: options2.orgId,
758
- userId: options2.userId,
759
- metadata: options2.metadata
760
- });
761
- if (!response?.chatKey) {
762
- throw new Error("Failed to create chat: no chatKey returned");
763
- }
764
- return { chatKey: response.chatKey };
765
- },
766
- async loadChatData(options2) {
767
- if (!config) {
768
- throw new Error("Transport not connected");
769
- }
770
- const response = await sendRest("load", {
771
- orgId: options2.orgId,
772
- chatKey: options2.chatKey,
773
- userId: options2.userId
774
- });
775
- if (!response?.chat) {
776
- throw new Error("Failed to load chat: no chat data returned");
777
- }
778
- return {
779
- chat: response.chat,
780
- agentId: response.agentId
781
- };
782
- },
783
- onMessage(handler) {
784
- globalHandlers.add(handler);
785
- return () => globalHandlers.delete(handler);
786
- },
787
- on(eventType, handler) {
788
- if (!typeHandlers.has(eventType)) {
789
- typeHandlers.set(eventType, /* @__PURE__ */ new Set());
790
- }
791
- typeHandlers.get(eventType).add(handler);
792
- return () => {
793
- const handlers = typeHandlers.get(eventType);
794
- if (handlers) {
795
- handlers.delete(handler);
796
- if (handlers.size === 0) {
797
- typeHandlers.delete(eventType);
798
- }
799
- }
800
- };
801
- },
802
- getState() {
803
- return state;
804
- },
805
- getMetrics() {
806
- return { ...metrics };
807
- },
808
- getError() {
809
- return error;
810
- },
811
- clearError() {
812
- error = void 0;
813
- }
814
- };
815
- return transport;
816
- }
817
-
818
- // hooks/use-chat.ts
819
- function getDefaultTransport(type, debug) {
820
- if (type === "sse-fetch") {
821
- return createFetchSSETransport({ debug });
822
- }
823
- if (type === "sse") {
824
- return createSSETransport({ debug });
825
- }
826
- const isReactNative = typeof navigator !== "undefined" && navigator.product === "ReactNative";
827
- if (isReactNative || typeof EventSource === "undefined") {
828
- return createFetchSSETransport({ debug });
829
- }
830
- return createSSETransport({ debug });
831
- }
832
- function useChat(options) {
833
- const {
834
- baseUrl,
835
- orgId,
836
- userId,
837
- clientType = "customer",
838
- transport: transportOption,
839
- onMessage,
840
- onError,
841
- onConnectionChange,
842
- autoConnect = false,
843
- retryConfig,
844
- debug = false
845
- } = options;
846
- const [connectionState, setConnectionState] = useState("disconnected");
847
- const [currentChat, setCurrentChat] = useState(null);
848
- const [chatKey, setChatKey] = useState(null);
849
- const [messages, setMessages] = useState([]);
850
- const [error, setError] = useState(null);
851
- const [metrics, setMetrics] = useState({
852
- latency: 0,
853
- messagesSent: 0,
854
- messagesReceived: 0,
855
- messagesQueued: 0,
856
- reconnectCount: 0
857
- });
858
- const transportRef = useRef(null);
859
- const mountedRef = useRef(false);
860
- const onMessageRef = useRef(onMessage);
861
- const onErrorRef = useRef(onError);
862
- const typingTimeoutRef = useRef(null);
863
- useEffect(() => {
864
- onMessageRef.current = onMessage;
865
- onErrorRef.current = onError;
866
- }, [onMessage, onError]);
867
- useEffect(() => {
868
- if (typeof transportOption === "object") {
869
- transportRef.current = transportOption;
870
- } else {
871
- transportRef.current = getDefaultTransport(
872
- transportOption,
873
- debug
874
- );
875
- }
876
- }, [transportOption, debug]);
877
- const handleEvent = useCallback((event) => {
878
- if (!mountedRef.current) return;
879
- setMetrics((prev) => ({
880
- ...prev,
881
- messagesReceived: prev.messagesReceived + 1,
882
- lastMessageAt: Date.now()
883
- }));
884
- switch (event.type) {
885
- case "new_chat_created":
886
- const newChatKey = event.data?.chatKey;
887
- if (newChatKey) {
888
- setChatKey(newChatKey);
889
- }
890
- break;
891
- case "load_chat_response":
892
- const chat = event.data?.chat;
893
- if (chat) {
894
- setCurrentChat(chat);
895
- setChatKey(chat.key);
896
- setMessages(chat.messages || []);
897
- }
898
- break;
899
- case "message":
900
- if (event.message) {
901
- setMessages((prev) => [...prev, event.message]);
902
- }
903
- break;
904
- case "chat_ended":
905
- setCurrentChat(null);
906
- setChatKey(null);
907
- break;
908
- case "error":
909
- const errorMsg = event.data?.message;
910
- if (errorMsg) {
911
- const transportError = {
912
- code: "NETWORK_ERROR",
913
- message: errorMsg,
914
- retryable: true,
915
- timestamp: Date.now()
916
- };
917
- setError(transportError);
918
- onErrorRef.current?.(transportError);
919
- }
920
- break;
921
- }
922
- onMessageRef.current?.(event);
923
- }, []);
924
- const connect = useCallback(async () => {
925
- const transport = transportRef.current;
926
- if (!transport) {
927
- throw new Error("Transport not initialized");
928
- }
929
- if (!orgId) {
930
- const err = {
931
- code: "CONNECTION_FAILED",
932
- message: "orgId is required",
933
- retryable: false,
934
- timestamp: Date.now()
935
- };
936
- setError(err);
937
- throw err;
938
- }
939
- setConnectionState("connecting");
940
- onConnectionChange?.("connecting");
941
- try {
942
- const unsubscribe = transport.onMessage(handleEvent);
943
- await transport.connect({
944
- baseUrl,
945
- orgId,
946
- userId,
947
- clientType,
948
- chatKey: chatKey || void 0,
949
- debug
950
- });
951
- setConnectionState("connected");
952
- setError(null);
953
- setMetrics(transport.getMetrics());
954
- onConnectionChange?.("connected");
955
- return;
956
- } catch (err) {
957
- const transportError = err;
958
- setConnectionState("disconnected");
959
- onConnectionChange?.("disconnected");
960
- setError(transportError);
961
- onErrorRef.current?.(transportError);
962
- throw err;
963
- }
964
- }, [baseUrl, orgId, userId, clientType, chatKey, debug, handleEvent, onConnectionChange]);
965
- const disconnect = useCallback(() => {
966
- const transport = transportRef.current;
967
- if (transport) {
968
- transport.disconnect(true);
969
- }
970
- setConnectionState("disconnected");
971
- onConnectionChange?.("disconnected");
972
- }, [onConnectionChange]);
973
- const startChat = useCallback(
974
- async (metadata) => {
975
- const transport = transportRef.current;
976
- if (!transport) {
977
- throw new Error("Transport not initialized");
978
- }
979
- const response = await transport.createChat({
980
- orgId,
981
- userId,
982
- metadata
983
- });
984
- setChatKey(response.chatKey);
985
- return response.chatKey;
986
- },
987
- [orgId, userId]
988
- );
989
- const loadChat2 = useCallback(
990
- async (key) => {
991
- const transport = transportRef.current;
992
- if (!transport) {
993
- throw new Error("Transport not initialized");
994
- }
995
- const response = await transport.loadChatData({
996
- orgId,
997
- chatKey: key,
998
- userId
999
- });
1000
- setCurrentChat(response.chat);
1001
- setChatKey(response.chat.key);
1002
- setMessages(response.chat.messages || []);
1003
- return response.chat;
1004
- },
1005
- [orgId, userId]
1006
- );
1007
- const sendMessage = useCallback(
1008
- async (content, attachments, data) => {
1009
- const transport = transportRef.current;
1010
- if (!transport) {
1011
- throw new Error("Transport not initialized");
1012
- }
1013
- if (!chatKey) {
1014
- throw new Error("No active chat");
1015
- }
1016
- const message = {
1017
- id: `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`,
1018
- role: "user",
1019
- content,
1020
- time: Date.now(),
1021
- status: "sending",
1022
- senderId: userId,
1023
- createdAt: Date.now(),
1024
- attachments
1025
- };
1026
- setMessages((prev) => [...prev, message]);
1027
- await transport.send({
1028
- type: "message",
1029
- orgId,
1030
- chatKey,
1031
- userId,
1032
- timestamp: Date.now(),
1033
- message,
1034
- ...data ? { data } : {}
1035
- });
1036
- setMetrics((prev) => ({
1037
- ...prev,
1038
- messagesSent: prev.messagesSent + 1
1039
- }));
1040
- },
1041
- [orgId, chatKey, userId]
1042
- );
1043
- const endChat2 = useCallback(
1044
- async (reason) => {
1045
- const transport = transportRef.current;
1046
- if (!transport) {
1047
- throw new Error("Transport not initialized");
1048
- }
1049
- if (!chatKey) {
1050
- return;
1051
- }
1052
- await transport.send({
1053
- type: "end_chat",
1054
- orgId,
1055
- chatKey,
1056
- userId,
1057
- timestamp: Date.now(),
1058
- data: reason ? { reason } : void 0
1059
- });
1060
- setCurrentChat(null);
1061
- setChatKey(null);
1062
- },
1063
- [orgId, chatKey, userId]
1064
- );
1065
- const sendEvent2 = useCallback(
1066
- async (event) => {
1067
- const transport = transportRef.current;
1068
- if (!transport) {
1069
- throw new Error("Transport not initialized");
1070
- }
1071
- await transport.send({
1072
- ...event,
1073
- timestamp: Date.now()
1074
- });
1075
- },
1076
- []
1077
- );
1078
- const startTyping = useCallback(() => {
1079
- const transport = transportRef.current;
1080
- if (!transport || !chatKey) return;
1081
- if (typingTimeoutRef.current) {
1082
- clearTimeout(typingTimeoutRef.current);
1083
- }
1084
- transport.send({
1085
- type: "typing",
1086
- orgId,
1087
- chatKey,
1088
- userId,
1089
- timestamp: Date.now()
1090
- }).catch(() => {
1091
- });
1092
- typingTimeoutRef.current = setTimeout(() => {
1093
- stopTyping();
1094
- }, 3e3);
1095
- }, [orgId, chatKey, userId]);
1096
- const stopTyping = useCallback(() => {
1097
- const transport = transportRef.current;
1098
- if (!transport || !chatKey) return;
1099
- if (typingTimeoutRef.current) {
1100
- clearTimeout(typingTimeoutRef.current);
1101
- typingTimeoutRef.current = null;
1102
- }
1103
- transport.send({
1104
- type: "stopped_typing",
1105
- orgId,
1106
- chatKey,
1107
- userId,
1108
- timestamp: Date.now()
1109
- }).catch(() => {
1110
- });
1111
- }, [orgId, chatKey, userId]);
1112
- const on = useCallback(
1113
- (eventType, handler) => {
1114
- const transport = transportRef.current;
1115
- if (!transport) {
1116
- return () => {
1117
- };
1118
- }
1119
- return transport.on(eventType, handler);
1120
- },
1121
- []
1122
- );
1123
- const clearError = useCallback(() => {
1124
- setError(null);
1125
- transportRef.current?.clearError();
1126
- }, []);
1127
- useEffect(() => {
1128
- mountedRef.current = true;
1129
- if (autoConnect) {
1130
- connect().catch(() => {
1131
- });
1132
- }
1133
- return () => {
1134
- mountedRef.current = false;
1135
- if (typingTimeoutRef.current) {
1136
- clearTimeout(typingTimeoutRef.current);
1137
- }
1138
- disconnect();
1139
- };
1140
- }, []);
1141
- const isConnected = connectionState === "connected";
1142
- return {
1143
- // Connection
1144
- connect,
1145
- disconnect,
1146
- connectionState,
1147
- isConnected,
1148
- // Chat operations
1149
- startChat,
1150
- loadChat: loadChat2,
1151
- sendMessage,
1152
- sendEvent: sendEvent2,
1153
- endChat: endChat2,
1154
- // Typing
1155
- startTyping,
1156
- stopTyping,
1157
- // State
1158
- currentChat,
1159
- chatKey,
1160
- messages,
1161
- error,
1162
- metrics,
1163
- // Events
1164
- on,
1165
- clearError
1166
- };
1167
- }
1168
-
1169
- // hooks/use-chat-history.ts
1170
- import { useMemo } from "react";
1171
-
1172
- // api/index.ts
1173
- import { browserApiRequest as browserApiRequest2 } from "@elqnt/api-client/browser";
1174
-
1175
- // api/memory.ts
1176
- import { browserApiRequest } from "@elqnt/api-client/browser";
1177
- var patchProfileApi = (patch, o) => browserApiRequest("/api/v1/memory/profile", { method: "PATCH", body: patch, ...o });
1178
- var replaceProfileApi = (p, o) => browserApiRequest("/api/v1/memory/profile", { method: "PUT", body: p, ...o });
1179
- var clearProfileApi = (o) => browserApiRequest("/api/v1/memory/profile", { method: "DELETE", ...o });
1180
- var deleteContactApi = (name, o) => browserApiRequest(`/api/v1/memory/profile/contacts/${encodeURIComponent(name)}`, { method: "DELETE", ...o });
1181
- var deleteNoteApi = (index, o) => browserApiRequest(`/api/v1/memory/profile/notes/${index}`, { method: "DELETE", ...o });
1182
- var clearSummaryApi = (chatKey, o) => browserApiRequest(`/api/v1/chats/${chatKey}/summary`, { method: "DELETE", ...o });
1183
- var regenerateSummaryApi = (chatKey, o) => browserApiRequest(`/api/v1/chats/${chatKey}/summary/regenerate`, { method: "POST", ...o });
1184
-
1185
- // api/index.ts
1186
- async function getChatHistoryApi(options) {
1187
- return browserApiRequest2("/api/v1/chats", {
1188
- method: "POST",
1189
- body: {
1190
- limit: options.limit || 15,
1191
- offset: options.offset || 0,
1192
- ...options.skipCache ? { skipCache: true } : {}
1193
- },
1194
- ...options
1195
- });
1196
- }
1197
- async function getChatApi(chatKey, options) {
1198
- return browserApiRequest2(`/api/v1/chats/${chatKey}`, {
1199
- method: "GET",
1200
- ...options
1201
- });
1202
- }
1203
- async function updateChatApi(chatKey, updates, options) {
1204
- return browserApiRequest2(`/api/v1/chats/${chatKey}`, {
1205
- method: "PATCH",
1206
- body: updates,
1207
- ...options
1208
- });
1209
- }
1210
- async function deleteChatApi(chatKey, options) {
1211
- return browserApiRequest2(`/api/v1/chats/${chatKey}`, {
1212
- method: "DELETE",
1213
- ...options
1214
- });
1215
- }
1216
- async function getActiveChatsCountApi(options) {
1217
- return browserApiRequest2("/api/v1/chats/active/count", {
1218
- method: "GET",
1219
- ...options
1220
- });
1221
- }
1222
- async function getActiveChatsApi(options) {
1223
- const params = new URLSearchParams();
1224
- if (options.pastHours) params.set("pastHours", String(options.pastHours));
1225
- const queryString = params.toString();
1226
- return browserApiRequest2(`/api/v1/chats/active${queryString ? `?${queryString}` : ""}`, {
1227
- method: "GET",
1228
- ...options
1229
- });
1230
- }
1231
- async function getWaitingChatsCountApi(options) {
1232
- return browserApiRequest2("/api/v1/chats/waiting/count", {
1233
- method: "GET",
1234
- ...options
1235
- });
1236
- }
1237
- async function getChatsByUserApi(userEmail, options) {
1238
- return browserApiRequest2(`/api/v1/chats/user/${encodeURIComponent(userEmail)}`, {
1239
- method: "GET",
1240
- ...options
1241
- });
1242
- }
1243
- async function listQueuesApi(options) {
1244
- return browserApiRequest2("/api/v1/queues", {
1245
- method: "GET",
1246
- ...options
1247
- });
1248
- }
1249
- async function getOnlineSessionsApi(options) {
1250
- return browserApiRequest2("/api/v1/agents/sessions/online", {
1251
- method: "GET",
1252
- ...options
1253
- });
1254
- }
1255
- async function getAgentSessionApi(agentId, options) {
1256
- return browserApiRequest2(`/api/v1/agents/sessions/${agentId}`, {
1257
- method: "GET",
1258
- ...options
1259
- });
1260
- }
1261
-
1262
- // hooks/use-chat-history.ts
1263
- import { useApiAsync } from "@elqnt/api-client/hooks";
1264
-
1265
- // hooks/use-options-ref.ts
1266
- import { useRef as useRef2, useEffect as useEffect2 } from "react";
1267
- function useOptionsRef(options) {
1268
- const optionsRef = useRef2(options);
1269
- useEffect2(() => {
1270
- optionsRef.current = options;
1271
- }, [options]);
1272
- return optionsRef;
1273
- }
1274
-
1275
- // hooks/use-chat-history.ts
1276
- function useChatHistory(options) {
1277
- const optionsRef = useOptionsRef(options);
1278
- const { execute: getChatHistory, loading: listLoading, error: listError } = useApiAsync(
1279
- (params) => getChatHistoryApi({ ...optionsRef.current, ...params }),
1280
- (data) => ({
1281
- chats: data.chats,
1282
- total: data.total,
1283
- hasMore: data.hasMore
1284
- }),
1285
- { chats: [], total: 0, hasMore: false }
1286
- );
1287
- const { execute: getChat, loading: getLoading, error: getError } = useApiAsync(
1288
- (chatKey) => getChatApi(chatKey, optionsRef.current),
1289
- (data) => data.chat || null,
1290
- null
1291
- );
1292
- const { execute: updateChat, loading: updateLoading, error: updateError } = useApiAsync(
1293
- (chatKey, updates) => updateChatApi(chatKey, updates, optionsRef.current),
1294
- (data) => !!data.chatKey,
1295
- false
1296
- );
1297
- const { execute: deleteChat, loading: deleteLoading, error: deleteError } = useApiAsync(
1298
- (chatKey) => deleteChatApi(chatKey, optionsRef.current),
1299
- (data) => data.success,
1300
- false
1301
- );
1302
- const { execute: getChatsByUser, loading: userChatsLoading, error: userChatsError } = useApiAsync(
1303
- (userEmail) => getChatsByUserApi(userEmail, optionsRef.current),
1304
- (data) => data.chats,
1305
- []
1306
- );
1307
- const loading = listLoading || getLoading || updateLoading || deleteLoading || userChatsLoading;
1308
- const error = listError || getError || updateError || deleteError || userChatsError;
1309
- return useMemo(
1310
- () => ({
1311
- loading,
1312
- error,
1313
- getChatHistory,
1314
- getChat,
1315
- updateChat,
1316
- deleteChat,
1317
- getChatsByUser
1318
- }),
1319
- [loading, error, getChatHistory, getChat, updateChat, deleteChat, getChatsByUser]
1320
- );
1321
- }
1322
-
1323
- // hooks/use-chat-monitoring.ts
1324
- import { useMemo as useMemo2 } from "react";
1325
- import { useApiAsync as useApiAsync2 } from "@elqnt/api-client/hooks";
1326
- function useChatMonitoring(options) {
1327
- const optionsRef = useOptionsRef(options);
1328
- const { execute: getActiveChats, loading: activeLoading, error: activeError } = useApiAsync2(
1329
- (pastHours) => getActiveChatsApi({ ...optionsRef.current, pastHours }),
1330
- (data) => data.chats,
1331
- []
1332
- );
1333
- const { execute: getActiveChatsCount, loading: activeCountLoading, error: activeCountError } = useApiAsync2(
1334
- () => getActiveChatsCountApi(optionsRef.current),
1335
- (data) => data.count,
1336
- 0
1337
- );
1338
- const { execute: getWaitingChatsCount, loading: waitingCountLoading, error: waitingCountError } = useApiAsync2(
1339
- () => getWaitingChatsCountApi(optionsRef.current),
1340
- (data) => data.count,
1341
- 0
1342
- );
1343
- const { execute: listQueues, loading: queuesLoading, error: queuesError } = useApiAsync2(
1344
- () => listQueuesApi(optionsRef.current),
1345
- (data) => data.queues,
1346
- []
1347
- );
1348
- const loading = activeLoading || activeCountLoading || waitingCountLoading || queuesLoading;
1349
- const error = activeError || activeCountError || waitingCountError || queuesError;
1350
- return useMemo2(
1351
- () => ({
1352
- loading,
1353
- error,
1354
- getActiveChats,
1355
- getActiveChatsCount,
1356
- getWaitingChatsCount,
1357
- listQueues
1358
- }),
1359
- [loading, error, getActiveChats, getActiveChatsCount, getWaitingChatsCount, listQueues]
1360
- );
1361
- }
1362
-
1363
- // hooks/use-human-agent-sessions.ts
1364
- import { useMemo as useMemo3 } from "react";
1365
- import { useApiAsync as useApiAsync3 } from "@elqnt/api-client/hooks";
1366
- function useHumanAgentSessions(options) {
1367
- const optionsRef = useOptionsRef(options);
1368
- const { execute: getOnlineSessions, loading: onlineLoading, error: onlineError } = useApiAsync3(
1369
- () => getOnlineSessionsApi(optionsRef.current),
1370
- (data) => data.sessions,
1371
- []
1372
- );
1373
- const { execute: getAgentSession, loading: sessionLoading, error: sessionError } = useApiAsync3(
1374
- (agentId) => getAgentSessionApi(agentId, optionsRef.current),
1375
- (data) => data.session || null,
1376
- null
1377
- );
1378
- const loading = onlineLoading || sessionLoading;
1379
- const error = onlineError || sessionError;
1380
- return useMemo3(
1381
- () => ({
1382
- loading,
1383
- error,
1384
- getOnlineSessions,
1385
- getAgentSession
1386
- }),
1387
- [loading, error, getOnlineSessions, getAgentSession]
1388
- );
1389
- }
1390
-
1391
- // hooks/use-memory.ts
1392
- import { useCallback as useCallback2, useRef as useRef3, useState as useState2 } from "react";
1393
- function useMemory(options, initialProfile = null) {
1394
- const [profile, setProfile] = useState2(initialProfile);
1395
- const [loading, setLoading] = useState2(false);
1396
- const requestCountRef = useRef3(0);
1397
- const runProfileMutation = useCallback2(
1398
- async (fn) => {
1399
- requestCountRef.current += 1;
1400
- setLoading(true);
1401
- try {
1402
- const response = await fn();
1403
- if (!response.error && response.data) {
1404
- setProfile(response.data);
1405
- return response.data;
1406
- }
1407
- return null;
1408
- } catch {
1409
- return null;
1410
- } finally {
1411
- requestCountRef.current -= 1;
1412
- if (requestCountRef.current === 0) {
1413
- setLoading(false);
1414
- }
1415
- }
1416
- },
1417
- []
1418
- );
1419
- const optionsRef = useRef3(options);
1420
- optionsRef.current = options;
1421
- const patchProfile = useCallback2(
1422
- (patch) => runProfileMutation(() => patchProfileApi(patch, optionsRef.current)),
1423
- [runProfileMutation]
1424
- );
1425
- const replaceProfile = useCallback2(
1426
- (p) => runProfileMutation(() => replaceProfileApi(p, optionsRef.current)),
1427
- [runProfileMutation]
1428
- );
1429
- const clearProfile = useCallback2(
1430
- () => runProfileMutation(() => clearProfileApi(optionsRef.current)),
1431
- [runProfileMutation]
1432
- );
1433
- const deleteContact = useCallback2(
1434
- (name) => runProfileMutation(() => deleteContactApi(name, optionsRef.current)),
1435
- [runProfileMutation]
1436
- );
1437
- const deleteNote = useCallback2(
1438
- (index) => runProfileMutation(() => deleteNoteApi(index, optionsRef.current)),
1439
- [runProfileMutation]
1440
- );
1441
- const clearSummary = useCallback2(
1442
- async (chatKey) => {
1443
- await clearSummaryApi(chatKey, optionsRef.current);
1444
- },
1445
- []
1446
- );
1447
- const regenerateSummary = useCallback2(
1448
- async (chatKey) => {
1449
- const response = await regenerateSummaryApi(chatKey, optionsRef.current);
1450
- if (!response.error && response.data) {
1451
- return response.data;
1452
- }
1453
- return null;
1454
- },
1455
- []
1456
- );
1457
- return {
1458
- profile,
1459
- loading,
1460
- patchProfile,
1461
- replaceProfile,
1462
- clearProfile,
1463
- deleteContact,
1464
- deleteNote,
1465
- clearSummary,
1466
- regenerateSummary
1467
- };
1468
- }
1469
-
1470
- // hooks/index.ts
1471
- import { useApiAsync as useApiAsync4 } from "@elqnt/api-client/hooks";
1472
-
1473
1
  // models/chat-models.ts
1474
2
  var ChatStatusActive = "active";
1475
3
  var ChatStatusDisconnected = "disconnected";
@@ -1856,13 +384,6 @@ export {
1856
384
  UserStatusAway,
1857
385
  UserStatusBusy,
1858
386
  UserStatusOffline,
1859
- UserStatusOnline,
1860
- useApiAsync4 as useApiAsync,
1861
- useChat,
1862
- useChatHistory,
1863
- useChatMonitoring,
1864
- useHumanAgentSessions,
1865
- useMemory,
1866
- useOptionsRef
387
+ UserStatusOnline
1867
388
  };
1868
389
  //# sourceMappingURL=index.mjs.map