@elqnt/chat 1.0.2 → 1.0.4

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.
Files changed (42) hide show
  1. package/dist/hooks/use-websocket-chat-admin.d.mts +3 -2
  2. package/dist/hooks/use-websocket-chat-admin.d.ts +3 -2
  3. package/dist/hooks/use-websocket-chat-admin.js +829 -4
  4. package/dist/hooks/use-websocket-chat-admin.js.map +1 -1
  5. package/dist/hooks/use-websocket-chat-admin.mjs +805 -4
  6. package/dist/hooks/use-websocket-chat-admin.mjs.map +1 -1
  7. package/dist/hooks/use-websocket-chat-base.d.mts +68 -2
  8. package/dist/hooks/use-websocket-chat-base.d.ts +68 -2
  9. package/dist/hooks/use-websocket-chat-base.js +661 -6
  10. package/dist/hooks/use-websocket-chat-base.js.map +1 -1
  11. package/dist/hooks/use-websocket-chat-base.mjs +634 -3
  12. package/dist/hooks/use-websocket-chat-base.mjs.map +1 -1
  13. package/dist/hooks/use-websocket-chat-customer.d.mts +3 -2
  14. package/dist/hooks/use-websocket-chat-customer.d.ts +3 -2
  15. package/dist/hooks/use-websocket-chat-customer.js +726 -5
  16. package/dist/hooks/use-websocket-chat-customer.js.map +1 -1
  17. package/dist/hooks/use-websocket-chat-customer.mjs +701 -4
  18. package/dist/hooks/use-websocket-chat-customer.mjs.map +1 -1
  19. package/dist/index.d.mts +3 -2
  20. package/dist/index.d.ts +3 -2
  21. package/dist/index.js +1685 -590
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.mjs +1064 -197
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/{use-websocket-chat-base-CZDONnTz.d.ts → models/index.d.mts} +2 -66
  26. package/dist/{use-websocket-chat-base-CZDONnTz.d.mts → models/index.d.ts} +2 -66
  27. package/dist/models/index.js +555 -0
  28. package/dist/models/index.js.map +1 -0
  29. package/dist/{chunk-AC5J5LX5.mjs → models/index.mjs} +146 -318
  30. package/dist/models/index.mjs.map +1 -0
  31. package/package.json +6 -1
  32. package/dist/chunk-3PXNBY7J.js +0 -73
  33. package/dist/chunk-3PXNBY7J.js.map +0 -1
  34. package/dist/chunk-AC5J5LX5.mjs.map +0 -1
  35. package/dist/chunk-DTFTLFSY.js +0 -637
  36. package/dist/chunk-DTFTLFSY.js.map +0 -1
  37. package/dist/chunk-E2FJX52R.js +0 -529
  38. package/dist/chunk-E2FJX52R.js.map +0 -1
  39. package/dist/chunk-F6OOS4ZM.mjs +0 -637
  40. package/dist/chunk-F6OOS4ZM.mjs.map +0 -1
  41. package/dist/chunk-XVYABY2Z.mjs +0 -73
  42. package/dist/chunk-XVYABY2Z.mjs.map +0 -1
@@ -1,8 +1,705 @@
1
1
  "use client";
2
- import {
3
- useWebSocketChatCustomer
4
- } from "../chunk-XVYABY2Z.mjs";
5
- import "../chunk-F6OOS4ZM.mjs";
2
+ "use client";
3
+
4
+ // hooks/use-websocket-chat-customer.ts
5
+ import { useCallback as useCallback2, useState as useState2 } from "react";
6
+
7
+ // hooks/use-websocket-chat-base.ts
8
+ import { useCallback, useEffect, useRef, useState } from "react";
9
+ var createDefaultLogger = (debug) => ({
10
+ debug: debug ? console.log : () => {
11
+ },
12
+ info: console.info,
13
+ warn: console.warn,
14
+ error: console.error
15
+ });
16
+ var DEFAULT_RETRY_CONFIG = {
17
+ maxRetries: 10,
18
+ intervals: [1e3, 2e3, 5e3],
19
+ backoffMultiplier: 1.5,
20
+ maxBackoffTime: 3e4
21
+ };
22
+ var DEFAULT_QUEUE_CONFIG = {
23
+ maxSize: 100,
24
+ dropStrategy: "oldest"
25
+ };
26
+ var DEFAULT_HEARTBEAT_INTERVAL = 3e4;
27
+ var DEFAULT_HEARTBEAT_TIMEOUT = 5e3;
28
+ function isChatEvent(data) {
29
+ return data && typeof data === "object" && (typeof data.type === "string" || data.message);
30
+ }
31
+ var useWebSocketChatBase = ({
32
+ serverBaseUrl,
33
+ orgId,
34
+ clientType,
35
+ product,
36
+ onMessage,
37
+ retryConfig = DEFAULT_RETRY_CONFIG,
38
+ queueConfig = DEFAULT_QUEUE_CONFIG,
39
+ debug = false,
40
+ logger = createDefaultLogger(debug),
41
+ heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL,
42
+ heartbeatTimeout = DEFAULT_HEARTBEAT_TIMEOUT
43
+ }) => {
44
+ const [connectionState, setConnectionState] = useState("disconnected");
45
+ const [error, setError] = useState(void 0);
46
+ const [startTime, setStartTime] = useState(void 0);
47
+ const [metrics, setMetrics] = useState({
48
+ latency: 0,
49
+ messagesSent: 0,
50
+ messagesReceived: 0,
51
+ messagesQueued: 0,
52
+ reconnectCount: 0
53
+ });
54
+ const wsRef = useRef(void 0);
55
+ const reconnectTimeoutRef = useRef(void 0);
56
+ const retryCountRef = useRef(0);
57
+ const messageQueueRef = useRef([]);
58
+ const mountedRef = useRef(false);
59
+ const currentChatKeyRef = useRef(void 0);
60
+ const currentUserIdRef = useRef(void 0);
61
+ const intentionalDisconnectRef = useRef(false);
62
+ const eventHandlersRef = useRef(
63
+ /* @__PURE__ */ new Map()
64
+ );
65
+ const onMessageRef = useRef(onMessage);
66
+ const pendingMessagesRef = useRef(/* @__PURE__ */ new Map());
67
+ const heartbeatIntervalRef = useRef(void 0);
68
+ const heartbeatTimeoutRef = useRef(void 0);
69
+ const lastPongRef = useRef(Date.now());
70
+ const chatCreationPromiseRef = useRef(null);
71
+ const loadChatRetryMapRef = useRef(/* @__PURE__ */ new Map());
72
+ useEffect(() => {
73
+ onMessageRef.current = onMessage;
74
+ }, [onMessage]);
75
+ const isConnected = connectionState === "connected";
76
+ const on = useCallback((eventType, handler) => {
77
+ if (!eventHandlersRef.current.has(eventType)) {
78
+ eventHandlersRef.current.set(eventType, /* @__PURE__ */ new Set());
79
+ }
80
+ eventHandlersRef.current.get(eventType).add(handler);
81
+ return () => off(eventType, handler);
82
+ }, []);
83
+ const off = useCallback((eventType, handler) => {
84
+ const handlers = eventHandlersRef.current.get(eventType);
85
+ if (handlers) {
86
+ handlers.delete(handler);
87
+ if (handlers.size === 0) {
88
+ eventHandlersRef.current.delete(eventType);
89
+ }
90
+ }
91
+ }, []);
92
+ const emit = useCallback(
93
+ (eventType, data) => {
94
+ const handlers = eventHandlersRef.current.get(eventType);
95
+ if (handlers) {
96
+ handlers.forEach((handler) => {
97
+ try {
98
+ handler(data);
99
+ } catch (error2) {
100
+ logger.error(`Error in event handler for ${eventType}:`, error2);
101
+ }
102
+ });
103
+ }
104
+ },
105
+ [logger]
106
+ );
107
+ const updateMetrics = useCallback((updates) => {
108
+ setMetrics((prev) => ({ ...prev, ...updates }));
109
+ }, []);
110
+ const addToQueue = useCallback(
111
+ (event) => {
112
+ const currentQueueSize = messageQueueRef.current.length;
113
+ const maxSize = queueConfig.maxSize || DEFAULT_QUEUE_CONFIG.maxSize;
114
+ if (currentQueueSize >= maxSize) {
115
+ if (queueConfig.dropStrategy === "newest") {
116
+ logger.warn("Message queue full, dropping new message");
117
+ return false;
118
+ } else {
119
+ const dropped = messageQueueRef.current.shift();
120
+ logger.warn("Message queue full, dropped oldest message", dropped);
121
+ }
122
+ }
123
+ messageQueueRef.current.push(event);
124
+ updateMetrics({ messagesQueued: messageQueueRef.current.length });
125
+ return true;
126
+ },
127
+ [queueConfig, logger, updateMetrics]
128
+ );
129
+ const calculateRetryInterval = useCallback(
130
+ (retryCount) => {
131
+ const config = { ...DEFAULT_RETRY_CONFIG, ...retryConfig };
132
+ const {
133
+ intervals = [],
134
+ backoffMultiplier = 1.5,
135
+ maxBackoffTime = 3e4
136
+ } = config;
137
+ if (retryCount < intervals.length) {
138
+ return intervals[retryCount];
139
+ }
140
+ const baseInterval = intervals[intervals.length - 1] || 5e3;
141
+ const backoffTime = baseInterval * Math.pow(backoffMultiplier, retryCount - intervals.length + 1);
142
+ return Math.min(backoffTime, maxBackoffTime);
143
+ },
144
+ [retryConfig]
145
+ );
146
+ const startHeartbeat = useCallback(() => {
147
+ if (!heartbeatInterval || heartbeatInterval <= 0) return;
148
+ const sendPing = () => {
149
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
150
+ const pingTime = Date.now();
151
+ wsRef.current.send(
152
+ JSON.stringify({ type: "ping", timestamp: pingTime })
153
+ );
154
+ heartbeatTimeoutRef.current = setTimeout(() => {
155
+ logger.warn("Heartbeat timeout - no pong received");
156
+ if (wsRef.current) {
157
+ wsRef.current.close(4e3, "Heartbeat timeout");
158
+ }
159
+ }, heartbeatTimeout);
160
+ }
161
+ };
162
+ if (heartbeatIntervalRef.current) {
163
+ clearInterval(heartbeatIntervalRef.current);
164
+ }
165
+ heartbeatIntervalRef.current = setInterval(sendPing, heartbeatInterval);
166
+ logger.debug("Heartbeat started");
167
+ }, [heartbeatInterval, heartbeatTimeout, logger]);
168
+ const stopHeartbeat = useCallback(() => {
169
+ if (heartbeatIntervalRef.current) {
170
+ clearInterval(heartbeatIntervalRef.current);
171
+ heartbeatIntervalRef.current = void 0;
172
+ }
173
+ if (heartbeatTimeoutRef.current) {
174
+ clearTimeout(heartbeatTimeoutRef.current);
175
+ heartbeatTimeoutRef.current = void 0;
176
+ }
177
+ logger.debug("Heartbeat stopped");
178
+ }, [logger]);
179
+ const cleanup = useCallback(() => {
180
+ if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
181
+ wsRef.current.close(1e3, "Cleanup");
182
+ }
183
+ wsRef.current = void 0;
184
+ if (reconnectTimeoutRef.current) {
185
+ clearTimeout(reconnectTimeoutRef.current);
186
+ reconnectTimeoutRef.current = void 0;
187
+ }
188
+ stopHeartbeat();
189
+ pendingMessagesRef.current.forEach(({ reject, timeout }) => {
190
+ clearTimeout(timeout);
191
+ reject(new Error("Connection closed"));
192
+ });
193
+ pendingMessagesRef.current.clear();
194
+ loadChatRetryMapRef.current.forEach((retryState) => {
195
+ if (retryState.timeoutId) {
196
+ clearTimeout(retryState.timeoutId);
197
+ }
198
+ });
199
+ loadChatRetryMapRef.current.clear();
200
+ }, [stopHeartbeat]);
201
+ const connect = useCallback(
202
+ async (userId) => {
203
+ if (!mountedRef.current) {
204
+ mountedRef.current = true;
205
+ }
206
+ if (!orgId) {
207
+ const error2 = {
208
+ code: "CONNECTION_FAILED",
209
+ message: "Cannot connect: orgId is undefined",
210
+ retryable: false,
211
+ timestamp: Date.now()
212
+ };
213
+ logger.error("Cannot connect: orgId is undefined");
214
+ setError(error2);
215
+ return Promise.reject(error2);
216
+ }
217
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
218
+ logger.debug("Already connected");
219
+ return Promise.resolve();
220
+ }
221
+ if (connectionState === "connecting" || connectionState === "reconnecting") {
222
+ logger.debug("Connection already in progress");
223
+ return Promise.resolve();
224
+ }
225
+ const maxRetries = retryConfig.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries;
226
+ if (retryCountRef.current >= maxRetries && !intentionalDisconnectRef.current) {
227
+ const error2 = {
228
+ code: "CONNECTION_FAILED",
229
+ message: `Max retries (${maxRetries}) exceeded`,
230
+ retryable: false,
231
+ timestamp: Date.now()
232
+ };
233
+ setError(error2);
234
+ updateMetrics({ lastError: error2 });
235
+ return Promise.reject(error2);
236
+ }
237
+ cleanup();
238
+ setConnectionState(
239
+ retryCountRef.current > 0 ? "reconnecting" : "connecting"
240
+ );
241
+ intentionalDisconnectRef.current = false;
242
+ return new Promise((resolve, reject) => {
243
+ try {
244
+ const wsUrl = `${serverBaseUrl}?orgId=${orgId}&userId=${userId}&clientType=${clientType}&product=${product}`;
245
+ const connectionStartTime = Date.now();
246
+ logger.debug("Connecting to WebSocket:", wsUrl);
247
+ console.log(`\u23F3 Initiating WebSocket connection to ${serverBaseUrl}...`);
248
+ const ws = new WebSocket(wsUrl);
249
+ ws.onopen = () => {
250
+ if (!mountedRef.current) {
251
+ ws.close(1e3, "Component unmounted");
252
+ reject(new Error("Component unmounted"));
253
+ return;
254
+ }
255
+ const connectionTimeMs = Date.now() - connectionStartTime;
256
+ const connectionTimeSec = (connectionTimeMs / 1e3).toFixed(2);
257
+ logger.info("\u2705 WebSocket connected", {
258
+ userId,
259
+ retryCount: retryCountRef.current,
260
+ connectionTime: `${connectionTimeSec}s (${connectionTimeMs}ms)`
261
+ });
262
+ console.log(`\u{1F50C} WebSocket connection established in ${connectionTimeSec} seconds`);
263
+ setConnectionState("connected");
264
+ setError(void 0);
265
+ const wasReconnecting = retryCountRef.current > 0;
266
+ retryCountRef.current = 0;
267
+ updateMetrics({
268
+ connectedAt: Date.now(),
269
+ latency: connectionTimeMs,
270
+ reconnectCount: wasReconnecting ? metrics.reconnectCount + 1 : metrics.reconnectCount
271
+ });
272
+ while (messageQueueRef.current.length > 0 && ws.readyState === WebSocket.OPEN) {
273
+ const event = messageQueueRef.current.shift();
274
+ if (event) {
275
+ ws.send(JSON.stringify({ ...event, timestamp: Date.now() }));
276
+ updateMetrics({
277
+ messagesSent: metrics.messagesSent + 1,
278
+ messagesQueued: messageQueueRef.current.length
279
+ });
280
+ }
281
+ }
282
+ currentUserIdRef.current = userId;
283
+ if (currentChatKeyRef.current) {
284
+ if (!orgId) {
285
+ logger.error("Cannot resubscribe to chat: orgId is undefined");
286
+ } else {
287
+ logger.info(
288
+ "Resubscribing to chat after reconnection:",
289
+ currentChatKeyRef.current
290
+ );
291
+ const resubscribeEvent = {
292
+ type: "load_chat",
293
+ orgId,
294
+ chatKey: currentChatKeyRef.current,
295
+ userId,
296
+ timestamp: Date.now(),
297
+ data: {}
298
+ };
299
+ ws.send(JSON.stringify(resubscribeEvent));
300
+ }
301
+ }
302
+ startHeartbeat();
303
+ emit("connected", { userId, wasReconnecting });
304
+ resolve();
305
+ };
306
+ ws.onmessage = (event) => {
307
+ if (!mountedRef.current) return;
308
+ try {
309
+ const data = JSON.parse(event.data);
310
+ if (!isChatEvent(data)) {
311
+ logger.warn("Received invalid message format:", data);
312
+ return;
313
+ }
314
+ const chatEvent = data;
315
+ logger.debug("Message received:", chatEvent.type);
316
+ updateMetrics({
317
+ messagesReceived: metrics.messagesReceived + 1,
318
+ lastMessageAt: Date.now()
319
+ });
320
+ if (chatEvent.type === "pong") {
321
+ if (heartbeatTimeoutRef.current) {
322
+ clearTimeout(heartbeatTimeoutRef.current);
323
+ heartbeatTimeoutRef.current = void 0;
324
+ }
325
+ const latency = Date.now() - (chatEvent.timestamp || Date.now());
326
+ lastPongRef.current = Date.now();
327
+ updateMetrics({ latency });
328
+ return;
329
+ }
330
+ switch (chatEvent.type) {
331
+ case "new_chat_created":
332
+ const newChatKey = chatEvent.data?.chatKey;
333
+ if (newChatKey) {
334
+ logger.info("New chat created with key:", newChatKey);
335
+ currentChatKeyRef.current = newChatKey;
336
+ if (chatCreationPromiseRef.current) {
337
+ chatCreationPromiseRef.current.resolve(newChatKey);
338
+ chatCreationPromiseRef.current = null;
339
+ }
340
+ if (!orgId) {
341
+ logger.error("Cannot send load_chat: orgId is undefined");
342
+ return;
343
+ }
344
+ const loadChatEvent = {
345
+ type: "load_chat",
346
+ orgId,
347
+ chatKey: newChatKey,
348
+ userId: currentUserIdRef.current || userId,
349
+ timestamp: Date.now(),
350
+ data: {}
351
+ };
352
+ ws.send(JSON.stringify(loadChatEvent));
353
+ }
354
+ break;
355
+ case "load_chat_response":
356
+ const chat = chatEvent.data?.chat;
357
+ if (chat && chat.key) {
358
+ logger.info("Chat loaded with key:", chat.key);
359
+ currentChatKeyRef.current = chat.key;
360
+ const retryState = loadChatRetryMapRef.current.get(chat.key);
361
+ if (retryState) {
362
+ if (retryState.timeoutId) {
363
+ clearTimeout(retryState.timeoutId);
364
+ }
365
+ loadChatRetryMapRef.current.delete(chat.key);
366
+ }
367
+ } else if (!chat) {
368
+ logger.warn("Chat load failed, clearing key");
369
+ currentChatKeyRef.current = void 0;
370
+ }
371
+ break;
372
+ case "chat_ended":
373
+ logger.info("Chat ended, clearing key");
374
+ currentChatKeyRef.current = void 0;
375
+ break;
376
+ case "error":
377
+ const errorMessage = chatEvent.data?.message || "Unknown error";
378
+ logger.error("Received error from server:", errorMessage);
379
+ if (errorMessage.includes("nats: key not found") || errorMessage.includes("Failed to load chat")) {
380
+ const chatKeyFromError = currentChatKeyRef.current;
381
+ if (chatKeyFromError) {
382
+ const maxRetries2 = 5;
383
+ let retryState = loadChatRetryMapRef.current.get(chatKeyFromError);
384
+ if (!retryState) {
385
+ retryState = { retryCount: 0, timeoutId: null };
386
+ loadChatRetryMapRef.current.set(chatKeyFromError, retryState);
387
+ }
388
+ if (retryState.retryCount < maxRetries2) {
389
+ const delay = 200 * Math.pow(2, retryState.retryCount);
390
+ retryState.retryCount++;
391
+ logger.info(
392
+ `Chat load failed, retrying (${retryState.retryCount}/${maxRetries2}) in ${delay}ms...`,
393
+ chatKeyFromError
394
+ );
395
+ retryState.timeoutId = setTimeout(() => {
396
+ if (!wsRef.current || !mountedRef.current) return;
397
+ if (!orgId) {
398
+ logger.error("Cannot retry load_chat: orgId is undefined", chatKeyFromError);
399
+ loadChatRetryMapRef.current.delete(chatKeyFromError);
400
+ return;
401
+ }
402
+ logger.debug("Retrying load_chat:", chatKeyFromError);
403
+ const retryLoadEvent = {
404
+ type: "load_chat",
405
+ orgId,
406
+ chatKey: chatKeyFromError,
407
+ userId: currentUserIdRef.current || "",
408
+ timestamp: Date.now(),
409
+ data: {}
410
+ };
411
+ ws.send(JSON.stringify(retryLoadEvent));
412
+ }, delay);
413
+ } else {
414
+ logger.error("Max retries reached for loading chat:", chatKeyFromError);
415
+ loadChatRetryMapRef.current.delete(chatKeyFromError);
416
+ }
417
+ }
418
+ }
419
+ const wsError = {
420
+ code: "NETWORK_ERROR",
421
+ message: errorMessage,
422
+ retryable: true,
423
+ timestamp: Date.now()
424
+ };
425
+ setError(wsError);
426
+ updateMetrics({ lastError: wsError });
427
+ break;
428
+ }
429
+ emit(chatEvent.type || "message", chatEvent);
430
+ if (onMessageRef.current) {
431
+ onMessageRef.current(chatEvent);
432
+ }
433
+ } catch (error2) {
434
+ logger.error("Failed to parse WebSocket message:", error2);
435
+ const parseError = {
436
+ code: "PARSE_ERROR",
437
+ message: "Failed to parse message",
438
+ retryable: false,
439
+ timestamp: Date.now()
440
+ };
441
+ setError(parseError);
442
+ updateMetrics({ lastError: parseError });
443
+ }
444
+ };
445
+ ws.onclose = (event) => {
446
+ if (!mountedRef.current) return;
447
+ logger.info("WebSocket closed", {
448
+ code: event.code,
449
+ reason: event.reason
450
+ });
451
+ setConnectionState("disconnected");
452
+ wsRef.current = void 0;
453
+ stopHeartbeat();
454
+ emit("disconnected", { code: event.code, reason: event.reason });
455
+ if (event.code !== 1e3 && !intentionalDisconnectRef.current && mountedRef.current) {
456
+ const retryInterval = calculateRetryInterval(
457
+ retryCountRef.current
458
+ );
459
+ retryCountRef.current++;
460
+ logger.info(
461
+ `Reconnecting in ${retryInterval}ms (attempt ${retryCountRef.current})`
462
+ );
463
+ if (reconnectTimeoutRef.current) {
464
+ clearTimeout(reconnectTimeoutRef.current);
465
+ }
466
+ reconnectTimeoutRef.current = setTimeout(() => {
467
+ connect(userId);
468
+ }, retryInterval);
469
+ }
470
+ };
471
+ ws.onerror = (error2) => {
472
+ logger.error("WebSocket error:", error2);
473
+ if (!mountedRef.current) return;
474
+ const wsError = {
475
+ code: "CONNECTION_FAILED",
476
+ message: "WebSocket connection failed",
477
+ retryable: true,
478
+ timestamp: Date.now()
479
+ };
480
+ setError(wsError);
481
+ updateMetrics({ lastError: wsError });
482
+ reject(wsError);
483
+ };
484
+ wsRef.current = ws;
485
+ } catch (error2) {
486
+ logger.error("Failed to create WebSocket:", error2);
487
+ const wsError = {
488
+ code: "CONNECTION_FAILED",
489
+ message: error2 instanceof Error ? error2.message : "Failed to create connection",
490
+ retryable: true,
491
+ timestamp: Date.now()
492
+ };
493
+ setError(wsError);
494
+ updateMetrics({ lastError: wsError });
495
+ reject(wsError);
496
+ }
497
+ });
498
+ },
499
+ [
500
+ serverBaseUrl,
501
+ orgId,
502
+ clientType,
503
+ product,
504
+ connectionState,
505
+ logger,
506
+ retryConfig,
507
+ metrics,
508
+ updateMetrics,
509
+ cleanup,
510
+ calculateRetryInterval,
511
+ startHeartbeat,
512
+ emit
513
+ ]
514
+ );
515
+ const sendMessage = useCallback(
516
+ (event, overrideUserId) => {
517
+ return new Promise((resolve, reject) => {
518
+ if (!mountedRef.current) {
519
+ reject(new Error("Component not mounted"));
520
+ return;
521
+ }
522
+ const fullEvent = {
523
+ ...event,
524
+ timestamp: Date.now()
525
+ };
526
+ const messageId = `${fullEvent.type}_${fullEvent.timestamp}_${Math.random()}`;
527
+ logger.debug("Sending message:", fullEvent.type);
528
+ if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
529
+ if (addToQueue(fullEvent)) {
530
+ logger.debug("Message queued, attempting to connect");
531
+ if (connectionState === "disconnected" && overrideUserId) {
532
+ connect(overrideUserId).then(() => resolve()).catch(reject);
533
+ } else {
534
+ resolve();
535
+ }
536
+ } else {
537
+ reject(new Error("Message queue full"));
538
+ }
539
+ return;
540
+ }
541
+ try {
542
+ wsRef.current.send(JSON.stringify(fullEvent));
543
+ updateMetrics({ messagesSent: metrics.messagesSent + 1 });
544
+ logger.debug("Message sent successfully");
545
+ resolve();
546
+ } catch (error2) {
547
+ logger.error("Failed to send message:", error2);
548
+ if (addToQueue(fullEvent)) {
549
+ resolve();
550
+ } else {
551
+ const sendError = {
552
+ code: "SEND_FAILED",
553
+ message: error2 instanceof Error ? error2.message : "Failed to send message",
554
+ retryable: true,
555
+ timestamp: Date.now()
556
+ };
557
+ setError(sendError);
558
+ updateMetrics({ lastError: sendError });
559
+ reject(sendError);
560
+ }
561
+ }
562
+ });
563
+ },
564
+ [connectionState, connect, addToQueue, logger, metrics, updateMetrics]
565
+ );
566
+ const startNewChat = useCallback(
567
+ (userId, data) => {
568
+ return new Promise((resolve, reject) => {
569
+ if (!userId) {
570
+ reject(new Error("User ID is required"));
571
+ return;
572
+ }
573
+ logger.info("Requesting new chat from server with userId:", userId);
574
+ setStartTime(/* @__PURE__ */ new Date());
575
+ chatCreationPromiseRef.current = { resolve, reject };
576
+ sendMessage(
577
+ {
578
+ type: "new_chat",
579
+ orgId,
580
+ chatKey: "",
581
+ // Server will generate
582
+ userId,
583
+ data: data ?? {}
584
+ },
585
+ userId
586
+ ).catch((error2) => {
587
+ chatCreationPromiseRef.current = null;
588
+ reject(error2);
589
+ });
590
+ setTimeout(() => {
591
+ if (chatCreationPromiseRef.current) {
592
+ chatCreationPromiseRef.current = null;
593
+ reject(new Error("Chat creation timed out"));
594
+ }
595
+ }, 3e4);
596
+ });
597
+ },
598
+ [sendMessage, orgId, logger]
599
+ );
600
+ const disconnect = useCallback(
601
+ (intentional = true) => {
602
+ logger.info("Disconnecting WebSocket", { intentional });
603
+ intentionalDisconnectRef.current = intentional;
604
+ cleanup();
605
+ setConnectionState("disconnected");
606
+ messageQueueRef.current = [];
607
+ retryCountRef.current = 0;
608
+ mountedRef.current = false;
609
+ currentChatKeyRef.current = void 0;
610
+ currentUserIdRef.current = void 0;
611
+ },
612
+ [cleanup, logger]
613
+ );
614
+ const clearError = useCallback(() => {
615
+ setError(void 0);
616
+ }, []);
617
+ useEffect(() => {
618
+ mountedRef.current = true;
619
+ return () => {
620
+ mountedRef.current = false;
621
+ disconnect(true);
622
+ };
623
+ }, []);
624
+ return {
625
+ connectionState,
626
+ isConnected,
627
+ sendMessage,
628
+ error,
629
+ connect,
630
+ startNewChat,
631
+ startTime,
632
+ disconnect,
633
+ metrics,
634
+ on,
635
+ off,
636
+ clearError
637
+ };
638
+ };
639
+
640
+ // hooks/use-websocket-chat-customer.ts
641
+ var useWebSocketChatCustomer = ({
642
+ serverBaseUrl,
643
+ orgId,
644
+ chatKey,
645
+ product
646
+ }) => {
647
+ const [currentChat, setCurrentChat] = useState2(void 0);
648
+ const handleMessage = useCallback2((chatEvent) => {
649
+ console.log("Received event:", chatEvent.type);
650
+ switch (chatEvent.type) {
651
+ case "message":
652
+ if (!chatEvent.message) return;
653
+ console.log(
654
+ "got message:",
655
+ chatEvent.message.role,
656
+ ":",
657
+ chatEvent.message.content
658
+ );
659
+ setCurrentChat((prev) => {
660
+ if (!prev) return prev;
661
+ return {
662
+ ...prev,
663
+ messages: [...prev.messages, chatEvent.message]
664
+ };
665
+ });
666
+ break;
667
+ case "chat_updated":
668
+ const chat = chatEvent.data?.chat?.value;
669
+ if (chat) {
670
+ setCurrentChat(chat);
671
+ }
672
+ break;
673
+ case "load_chat":
674
+ const history = chatEvent.data?.chat;
675
+ if (!history) return;
676
+ setCurrentChat(history);
677
+ break;
678
+ default:
679
+ break;
680
+ }
681
+ }, []);
682
+ const base = useWebSocketChatBase({
683
+ serverBaseUrl,
684
+ orgId,
685
+ clientType: "customer",
686
+ onMessage: handleMessage,
687
+ product
688
+ });
689
+ return {
690
+ ...base,
691
+ chatKey,
692
+ title: currentChat?.title,
693
+ messages: currentChat?.messages ?? [],
694
+ users: currentChat?.users ?? [],
695
+ isWaiting: currentChat?.isWaiting ?? false,
696
+ isWaitingForAgent: currentChat?.isWaitingForAgent ?? false,
697
+ aiEngaged: currentChat?.aiEngaged ?? false,
698
+ humanAgentEngaged: currentChat?.humanAgentEngaged ?? false,
699
+ metadata: currentChat?.metadata ?? {},
700
+ status: currentChat?.status
701
+ };
702
+ };
6
703
  export {
7
704
  useWebSocketChatCustomer
8
705
  };