@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 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/eloquent-packages/eloquent-packages/packages/chat/dist/chunk-DTFTLFSY.js","../hooks/use-websocket-chat-base.ts"],"names":["error"],"mappings":"AAAA;ACGA,8BAAyD;AA0DzD,IAAM,oBAAA,EAAsB,CAAC,KAAA,EAAA,GAAA,CAA4B;AAAA,EACvD,KAAA,EAAO,MAAA,EAAQ,OAAA,CAAQ,IAAA,EAAM,CAAA,EAAA,GAAM;AAAA,EAAC,CAAA;AAAA,EACpC,IAAA,EAAM,OAAA,CAAQ,IAAA;AAAA,EACd,IAAA,EAAM,OAAA,CAAQ,IAAA;AAAA,EACd,KAAA,EAAO,OAAA,CAAQ;AACjB,CAAA,CAAA;AAsCA,IAAM,qBAAA,EAAoC;AAAA,EACxC,UAAA,EAAY,EAAA;AAAA,EACZ,SAAA,EAAW,CAAC,GAAA,EAAM,GAAA,EAAM,GAAI,CAAA;AAAA,EAC5B,iBAAA,EAAmB,GAAA;AAAA,EACnB,cAAA,EAAgB;AAClB,CAAA;AAEA,IAAM,qBAAA,EAAoC;AAAA,EACxC,OAAA,EAAS,GAAA;AAAA,EACT,YAAA,EAAc;AAChB,CAAA;AAEA,IAAM,2BAAA,EAA6B,GAAA;AACnC,IAAM,0BAAA,EAA4B,GAAA;AAGlC,SAAS,WAAA,CAAY,IAA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C,YAAA;AACE,cAAA;AAEJA,cAAAA;AAGS,cAAA;AACA,cAAA;AACb,YAAA;AACS,YAAA;AACT,YAAA;AACO,YAAA;AACT,UAAA;AACF,QAAA;AACD,MAAA;AACH,IAAA;AACkB,IAAA;AACpB,EAAA;AAGqB,EAAA;AACiD,IAAA;AAC/C,MAAA;AACJ,QAAA;AACA,UAAA;AACX,UAAA;AACF,QAAA;AAEY,QAAA;AACC,QAAA;AAGb,QAAA;AAGA,QAAA;AACE,UAAA;AACQ,YAAA;AACN,YAAA;AACS,YAAA;AAAA;AACT,YAAA;AACM,YAAA;AACR,UAAA;AACA,UAAA;AACOA,QAAAA;AACP,UAAA;AACY,UAAA;AACb,QAAA;AAGgB,QAAA;AACX,UAAA;AACF,YAAA;AACW,YAAA;AACb,UAAA;AACM,QAAA;AACT,MAAA;AACH,IAAA;AACqB,IAAA;AACvB,EAAA;AAGmB,EAAA;AACO,IAAA;AACV,MAAA;AACZ,MAAA;AACQ,MAAA;AACW,MAAA;AACH,MAAA;AACF,MAAA;AACH,MAAA;AACO,MAAA;AACD,MAAA;AACnB,IAAA;AACgB,IAAA;AAClB,EAAA;AAGmB,EAAA;AACC,IAAA;AACf,EAAA;AAGW,EAAA;AACO,IAAA;AACR,IAAA;AACA,MAAA;AACI,MAAA;AACjB,IAAA;AACG,EAAA;AAEE,EAAA;AACL,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACF;AD9SyB;AACA;AACA;AACA","file":"/home/runner/work/eloquent-packages/eloquent-packages/packages/chat/dist/chunk-DTFTLFSY.js","sourcesContent":[null,"\"use client\";\n\nimport { ProductNameTS } from \"@elqnt/types\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { ChatEvent } from \"../models\";\n\n// Connection state enum\nexport type ConnectionState =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"reconnecting\";\n\n// Error types\nexport interface WebSocketError {\n code:\n | \"CONNECTION_FAILED\"\n | \"PARSE_ERROR\"\n | \"SEND_FAILED\"\n | \"TIMEOUT\"\n | \"NETWORK_ERROR\";\n message: string;\n retryable: boolean;\n timestamp: number;\n}\n\n// Retry configuration\nexport interface RetryConfig {\n maxRetries?: number;\n intervals?: number[];\n backoffMultiplier?: number;\n maxBackoffTime?: number;\n}\n\n// Connection metrics\nexport interface ConnectionMetrics {\n latency: number;\n messagesSent: number;\n messagesReceived: number;\n messagesQueued: number;\n reconnectCount: number;\n lastError?: WebSocketError;\n connectedAt?: number;\n lastMessageAt?: number;\n}\n\n// Message queue configuration\nexport interface QueueConfig {\n maxSize?: number;\n dropStrategy?: \"oldest\" | \"newest\";\n}\n\n// Logger interface\nexport interface Logger {\n debug: (message: string, ...args: any[]) => void;\n info: (message: string, ...args: any[]) => void;\n warn: (message: string, ...args: any[]) => void;\n error: (message: string, ...args: any[]) => void;\n}\n\n// Default logger (can be overridden)\nconst createDefaultLogger = (debug: boolean): Logger => ({\n debug: debug ? console.log : () => {},\n info: console.info,\n warn: console.warn,\n error: console.error,\n});\n\nexport interface UseWebSocketChatBaseConfig {\n serverBaseUrl: string;\n orgId: string;\n clientType: \"customer\" | \"humanAgent\" | \"observer\";\n product: ProductNameTS;\n onMessage?: (event: ChatEvent) => void;\n retryConfig?: RetryConfig;\n queueConfig?: QueueConfig;\n debug?: boolean;\n logger?: Logger;\n heartbeatInterval?: number; // in milliseconds, 0 to disable\n heartbeatTimeout?: number; // in milliseconds\n}\n\nexport interface UseWebSocketChatBaseReturn {\n connectionState: ConnectionState;\n isConnected: boolean;\n sendMessage: (\n event: Omit<ChatEvent, \"timestamp\">,\n overrideUserId?: string\n ) => Promise<void>;\n error: WebSocketError | undefined;\n connect: (userId: string) => Promise<void>;\n startNewChat: (\n userId: string,\n data?: { [key: string]: any }\n ) => Promise<string>;\n startTime: Date | undefined;\n disconnect: (intentional?: boolean) => void;\n metrics: ConnectionMetrics;\n on: (eventType: string, handler: (data: any) => void) => () => void;\n off: (eventType: string, handler: (data: any) => void) => void;\n clearError: () => void;\n}\n\n// Default configurations\nconst DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxRetries: 10,\n intervals: [1000, 2000, 5000],\n backoffMultiplier: 1.5,\n maxBackoffTime: 30000,\n};\n\nconst DEFAULT_QUEUE_CONFIG: QueueConfig = {\n maxSize: 100,\n dropStrategy: \"oldest\",\n};\n\nconst DEFAULT_HEARTBEAT_INTERVAL = 30000; // 30 seconds\nconst DEFAULT_HEARTBEAT_TIMEOUT = 5000; // 5 seconds\n\n// Type guards\nfunction isChatEvent(data: any): data is ChatEvent {\n return (\n data &&\n typeof data === \"object\" &&\n (typeof data.type === \"string\" || data.message)\n );\n}\n\nfunction hasValidChatKey(data: any): boolean {\n return data?.chatKey && typeof data.chatKey === \"string\";\n}\n\nexport const useWebSocketChatBase = ({\n serverBaseUrl,\n orgId,\n clientType,\n product,\n onMessage,\n retryConfig = DEFAULT_RETRY_CONFIG,\n queueConfig = DEFAULT_QUEUE_CONFIG,\n debug = false,\n logger = createDefaultLogger(debug),\n heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL,\n heartbeatTimeout = DEFAULT_HEARTBEAT_TIMEOUT,\n}: UseWebSocketChatBaseConfig): UseWebSocketChatBaseReturn => {\n // State\n const [connectionState, setConnectionState] =\n useState<ConnectionState>(\"disconnected\");\n const [error, setError] = useState<WebSocketError | undefined>(undefined);\n const [startTime, setStartTime] = useState<Date | undefined>(undefined);\n const [metrics, setMetrics] = useState<ConnectionMetrics>({\n latency: 0,\n messagesSent: 0,\n messagesReceived: 0,\n messagesQueued: 0,\n reconnectCount: 0,\n });\n\n // Refs\n const wsRef = useRef<WebSocket | undefined>(undefined);\n const reconnectTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);\n const retryCountRef = useRef(0);\n const messageQueueRef = useRef<ChatEvent[]>([]);\n const mountedRef = useRef(false);\n const currentChatKeyRef = useRef<string | undefined>(undefined);\n const currentUserIdRef = useRef<string | undefined>(undefined);\n const intentionalDisconnectRef = useRef(false);\n const eventHandlersRef = useRef<Map<string, Set<(data: any) => void>>>(\n new Map()\n );\n const onMessageRef = useRef(onMessage);\n const pendingMessagesRef = useRef<\n Map<\n string,\n {\n resolve: () => void;\n reject: (error: Error) => void;\n timeout: NodeJS.Timeout;\n }\n >\n >(new Map());\n const heartbeatIntervalRef = useRef<NodeJS.Timeout | undefined>(undefined);\n const heartbeatTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);\n const lastPongRef = useRef<number>(Date.now());\n const chatCreationPromiseRef = useRef<{\n resolve: (value: string) => void;\n reject: (reason?: any) => void;\n } | null>(null);\n\n // Load chat retry state\n const loadChatRetryMapRef = useRef<Map<string, {\n retryCount: number;\n timeoutId: NodeJS.Timeout | null;\n }>>(new Map());\n\n // Update onMessage ref when it changes\n useEffect(() => {\n onMessageRef.current = onMessage;\n }, [onMessage]);\n\n // Computed state\n const isConnected = connectionState === \"connected\";\n\n // Event subscription system\n const on = useCallback((eventType: string, handler: (data: any) => void) => {\n if (!eventHandlersRef.current.has(eventType)) {\n eventHandlersRef.current.set(eventType, new Set());\n }\n eventHandlersRef.current.get(eventType)!.add(handler);\n\n // Return unsubscribe function\n return () => off(eventType, handler);\n }, []);\n\n const off = useCallback((eventType: string, handler: (data: any) => void) => {\n const handlers = eventHandlersRef.current.get(eventType);\n if (handlers) {\n handlers.delete(handler);\n if (handlers.size === 0) {\n eventHandlersRef.current.delete(eventType);\n }\n }\n }, []);\n\n // Emit event to all registered handlers\n const emit = useCallback(\n (eventType: string, data: any) => {\n const handlers = eventHandlersRef.current.get(eventType);\n if (handlers) {\n handlers.forEach((handler) => {\n try {\n handler(data);\n } catch (error) {\n logger.error(`Error in event handler for ${eventType}:`, error);\n }\n });\n }\n },\n [logger]\n );\n\n // Update metrics\n const updateMetrics = useCallback((updates: Partial<ConnectionMetrics>) => {\n setMetrics((prev) => ({ ...prev, ...updates }));\n }, []);\n\n // Queue management\n const addToQueue = useCallback(\n (event: ChatEvent) => {\n const currentQueueSize = messageQueueRef.current.length;\n const maxSize = queueConfig.maxSize || DEFAULT_QUEUE_CONFIG.maxSize!;\n\n if (currentQueueSize >= maxSize) {\n if (queueConfig.dropStrategy === \"newest\") {\n logger.warn(\"Message queue full, dropping new message\");\n return false;\n } else {\n // Drop oldest\n const dropped = messageQueueRef.current.shift();\n logger.warn(\"Message queue full, dropped oldest message\", dropped);\n }\n }\n\n messageQueueRef.current.push(event);\n updateMetrics({ messagesQueued: messageQueueRef.current.length });\n return true;\n },\n [queueConfig, logger, updateMetrics]\n );\n\n // Calculate retry interval\n const calculateRetryInterval = useCallback(\n (retryCount: number): number => {\n const config = { ...DEFAULT_RETRY_CONFIG, ...retryConfig };\n const {\n intervals = [],\n backoffMultiplier = 1.5,\n maxBackoffTime = 30000,\n } = config;\n\n if (retryCount < intervals.length) {\n return intervals[retryCount];\n }\n\n // Exponential backoff after predefined intervals\n const baseInterval = intervals[intervals.length - 1] || 5000;\n const backoffTime =\n baseInterval *\n Math.pow(backoffMultiplier, retryCount - intervals.length + 1);\n return Math.min(backoffTime, maxBackoffTime);\n },\n [retryConfig]\n );\n\n // Heartbeat mechanism\n const startHeartbeat = useCallback(() => {\n if (!heartbeatInterval || heartbeatInterval <= 0) return;\n\n const sendPing = () => {\n if (wsRef.current?.readyState === WebSocket.OPEN) {\n const pingTime = Date.now();\n wsRef.current.send(\n JSON.stringify({ type: \"ping\", timestamp: pingTime })\n );\n\n // Set timeout for pong response\n heartbeatTimeoutRef.current = setTimeout(() => {\n logger.warn(\"Heartbeat timeout - no pong received\");\n // Force reconnection\n if (wsRef.current) {\n wsRef.current.close(4000, \"Heartbeat timeout\");\n }\n }, heartbeatTimeout);\n }\n };\n\n // Clear existing interval\n if (heartbeatIntervalRef.current) {\n clearInterval(heartbeatIntervalRef.current);\n }\n\n // Start new interval\n heartbeatIntervalRef.current = setInterval(sendPing, heartbeatInterval);\n logger.debug(\"Heartbeat started\");\n }, [heartbeatInterval, heartbeatTimeout, logger]);\n\n const stopHeartbeat = useCallback(() => {\n if (heartbeatIntervalRef.current) {\n clearInterval(heartbeatIntervalRef.current);\n heartbeatIntervalRef.current = undefined;\n }\n if (heartbeatTimeoutRef.current) {\n clearTimeout(heartbeatTimeoutRef.current);\n heartbeatTimeoutRef.current = undefined;\n }\n logger.debug(\"Heartbeat stopped\");\n }, [logger]);\n\n // Cleanup function\n const cleanup = useCallback(() => {\n if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {\n wsRef.current.close(1000, \"Cleanup\");\n }\n wsRef.current = undefined;\n if (reconnectTimeoutRef.current) {\n clearTimeout(reconnectTimeoutRef.current);\n reconnectTimeoutRef.current = undefined;\n }\n stopHeartbeat();\n\n // Clear pending message promises\n pendingMessagesRef.current.forEach(({ reject, timeout }) => {\n clearTimeout(timeout);\n reject(new Error(\"Connection closed\"));\n });\n pendingMessagesRef.current.clear();\n\n // Clear load chat retry timeouts\n loadChatRetryMapRef.current.forEach((retryState) => {\n if (retryState.timeoutId) {\n clearTimeout(retryState.timeoutId);\n }\n });\n loadChatRetryMapRef.current.clear();\n }, [stopHeartbeat]);\n\n // Connect function\n const connect = useCallback(\n async (userId: string): Promise<void> => {\n if (!mountedRef.current) {\n mountedRef.current = true;\n }\n\n // Guard: Don't connect if orgId is not available\n if (!orgId) {\n const error: WebSocketError = {\n code: \"CONNECTION_FAILED\",\n message: \"Cannot connect: orgId is undefined\",\n retryable: false,\n timestamp: Date.now(),\n };\n logger.error(\"Cannot connect: orgId is undefined\");\n setError(error);\n return Promise.reject(error);\n }\n\n if (wsRef.current?.readyState === WebSocket.OPEN) {\n logger.debug(\"Already connected\");\n return Promise.resolve();\n }\n\n if (\n connectionState === \"connecting\" ||\n connectionState === \"reconnecting\"\n ) {\n logger.debug(\"Connection already in progress\");\n return Promise.resolve();\n }\n\n // Check max retries\n const maxRetries =\n retryConfig.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries!;\n if (\n retryCountRef.current >= maxRetries &&\n !intentionalDisconnectRef.current\n ) {\n const error: WebSocketError = {\n code: \"CONNECTION_FAILED\",\n message: `Max retries (${maxRetries}) exceeded`,\n retryable: false,\n timestamp: Date.now(),\n };\n setError(error);\n updateMetrics({ lastError: error });\n return Promise.reject(error);\n }\n\n cleanup();\n setConnectionState(\n retryCountRef.current > 0 ? \"reconnecting\" : \"connecting\"\n );\n intentionalDisconnectRef.current = false;\n\n return new Promise<void>((resolve, reject) => {\n try {\n const wsUrl = `${serverBaseUrl}?orgId=${orgId}&userId=${userId}&clientType=${clientType}&product=${product}`;\n const connectionStartTime = Date.now();\n\n logger.debug(\"Connecting to WebSocket:\", wsUrl);\n console.log(`⏳ Initiating WebSocket connection to ${serverBaseUrl}...`);\n\n const ws = new WebSocket(wsUrl);\n\n ws.onopen = () => {\n if (!mountedRef.current) {\n ws.close(1000, \"Component unmounted\");\n reject(new Error(\"Component unmounted\"));\n return;\n }\n\n const connectionTimeMs = Date.now() - connectionStartTime;\n const connectionTimeSec = (connectionTimeMs / 1000).toFixed(2);\n\n logger.info(\"✅ WebSocket connected\", {\n userId,\n retryCount: retryCountRef.current,\n connectionTime: `${connectionTimeSec}s (${connectionTimeMs}ms)`,\n });\n\n console.log(`🔌 WebSocket connection established in ${connectionTimeSec} seconds`);\n\n setConnectionState(\"connected\");\n setError(undefined);\n const wasReconnecting = retryCountRef.current > 0;\n retryCountRef.current = 0;\n\n // Update metrics\n updateMetrics({\n connectedAt: Date.now(),\n latency: connectionTimeMs,\n reconnectCount: wasReconnecting\n ? metrics.reconnectCount + 1\n : metrics.reconnectCount,\n });\n\n // Process queued messages\n while (\n messageQueueRef.current.length > 0 &&\n ws.readyState === WebSocket.OPEN\n ) {\n const event = messageQueueRef.current.shift();\n if (event) {\n ws.send(JSON.stringify({ ...event, timestamp: Date.now() }));\n updateMetrics({\n messagesSent: metrics.messagesSent + 1,\n messagesQueued: messageQueueRef.current.length,\n });\n }\n }\n\n // Store the userId for reconnection\n currentUserIdRef.current = userId;\n\n // If we have a chat key, resubscribe to the chat\n if (currentChatKeyRef.current) {\n if (!orgId) {\n logger.error(\"Cannot resubscribe to chat: orgId is undefined\");\n } else {\n logger.info(\n \"Resubscribing to chat after reconnection:\",\n currentChatKeyRef.current\n );\n const resubscribeEvent: ChatEvent = {\n type: \"load_chat\",\n orgId,\n chatKey: currentChatKeyRef.current,\n userId,\n timestamp: Date.now(),\n data: {},\n };\n ws.send(JSON.stringify(resubscribeEvent));\n }\n }\n\n // Start heartbeat\n startHeartbeat();\n\n // Emit connected event\n emit(\"connected\", { userId, wasReconnecting });\n\n // Resolve the promise\n resolve();\n };\n\n ws.onmessage = (event) => {\n if (!mountedRef.current) return;\n\n try {\n const data = JSON.parse(event.data);\n\n if (!isChatEvent(data)) {\n logger.warn(\"Received invalid message format:\", data);\n return;\n }\n\n const chatEvent = data as ChatEvent;\n logger.debug(\"Message received:\", chatEvent.type);\n\n // Update metrics\n updateMetrics({\n messagesReceived: metrics.messagesReceived + 1,\n lastMessageAt: Date.now(),\n });\n\n // Handle pong response\n if (chatEvent.type === \"pong\") {\n if (heartbeatTimeoutRef.current) {\n clearTimeout(heartbeatTimeoutRef.current);\n heartbeatTimeoutRef.current = undefined;\n }\n const latency =\n Date.now() - (chatEvent.timestamp || Date.now());\n lastPongRef.current = Date.now();\n updateMetrics({ latency });\n return;\n }\n\n // Handle specific events internally for connection management\n switch (chatEvent.type) {\n case \"new_chat_created\":\n const newChatKey = chatEvent.data?.chatKey as string;\n if (newChatKey) {\n logger.info(\"New chat created with key:\", newChatKey);\n currentChatKeyRef.current = newChatKey;\n\n // Resolve the promise if waiting for chat creation\n if (chatCreationPromiseRef.current) {\n chatCreationPromiseRef.current.resolve(newChatKey);\n chatCreationPromiseRef.current = null;\n }\n\n // Send load_chat to subscribe to the new chat (only if orgId is valid)\n if (!orgId) {\n logger.error(\"Cannot send load_chat: orgId is undefined\");\n return;\n }\n\n const loadChatEvent: ChatEvent = {\n type: \"load_chat\",\n orgId,\n chatKey: newChatKey,\n userId: currentUserIdRef.current || userId,\n timestamp: Date.now(),\n data: {},\n };\n ws.send(JSON.stringify(loadChatEvent));\n }\n break;\n\n case \"load_chat_response\":\n const chat = chatEvent.data?.chat;\n if (chat && chat.key) {\n logger.info(\"Chat loaded with key:\", chat.key);\n currentChatKeyRef.current = chat.key;\n\n // Clear retry state for this chat on success\n const retryState = loadChatRetryMapRef.current.get(chat.key);\n if (retryState) {\n if (retryState.timeoutId) {\n clearTimeout(retryState.timeoutId);\n }\n loadChatRetryMapRef.current.delete(chat.key);\n }\n } else if (!chat) {\n logger.warn(\"Chat load failed, clearing key\");\n currentChatKeyRef.current = undefined;\n }\n break;\n\n case \"chat_ended\":\n logger.info(\"Chat ended, clearing key\");\n currentChatKeyRef.current = undefined;\n break;\n\n case \"error\":\n const errorMessage =\n chatEvent.data?.message || \"Unknown error\";\n logger.error(\"Received error from server:\", errorMessage);\n\n // Check if this is a \"key not found\" error for load_chat\n if (errorMessage.includes(\"nats: key not found\") || errorMessage.includes(\"Failed to load chat\")) {\n const chatKeyFromError = currentChatKeyRef.current;\n if (chatKeyFromError) {\n const maxRetries = 5;\n let retryState = loadChatRetryMapRef.current.get(chatKeyFromError);\n\n if (!retryState) {\n retryState = { retryCount: 0, timeoutId: null };\n loadChatRetryMapRef.current.set(chatKeyFromError, retryState);\n }\n\n if (retryState.retryCount < maxRetries) {\n // Exponential backoff: 200ms, 400ms, 800ms, 1.6s, 3.2s\n const delay = 200 * Math.pow(2, retryState.retryCount);\n retryState.retryCount++;\n\n logger.info(\n `Chat load failed, retrying (${retryState.retryCount}/${maxRetries}) in ${delay}ms...`,\n chatKeyFromError\n );\n\n retryState.timeoutId = setTimeout(() => {\n if (!wsRef.current || !mountedRef.current) return;\n\n // Check if orgId is valid before retrying\n if (!orgId) {\n logger.error(\"Cannot retry load_chat: orgId is undefined\", chatKeyFromError);\n loadChatRetryMapRef.current.delete(chatKeyFromError);\n return;\n }\n\n logger.debug(\"Retrying load_chat:\", chatKeyFromError);\n const retryLoadEvent: ChatEvent = {\n type: \"load_chat\",\n orgId,\n chatKey: chatKeyFromError,\n userId: currentUserIdRef.current || \"\",\n timestamp: Date.now(),\n data: {},\n };\n ws.send(JSON.stringify(retryLoadEvent));\n }, delay);\n } else {\n logger.error(\"Max retries reached for loading chat:\", chatKeyFromError);\n loadChatRetryMapRef.current.delete(chatKeyFromError);\n }\n }\n }\n\n const wsError: WebSocketError = {\n code: \"NETWORK_ERROR\",\n message: errorMessage,\n retryable: true,\n timestamp: Date.now(),\n };\n setError(wsError);\n updateMetrics({ lastError: wsError });\n break;\n }\n\n // Emit event to subscribers\n emit(chatEvent.type || \"message\", chatEvent);\n\n // Call the legacy onMessage handler\n if (onMessageRef.current) {\n onMessageRef.current(chatEvent);\n }\n } catch (error) {\n logger.error(\"Failed to parse WebSocket message:\", error);\n const parseError: WebSocketError = {\n code: \"PARSE_ERROR\",\n message: \"Failed to parse message\",\n retryable: false,\n timestamp: Date.now(),\n };\n setError(parseError);\n updateMetrics({ lastError: parseError });\n }\n };\n\n ws.onclose = (event) => {\n if (!mountedRef.current) return;\n\n logger.info(\"WebSocket closed\", {\n code: event.code,\n reason: event.reason,\n });\n setConnectionState(\"disconnected\");\n wsRef.current = undefined;\n stopHeartbeat();\n\n // Emit disconnected event\n emit(\"disconnected\", { code: event.code, reason: event.reason });\n\n // Handle reconnection\n if (\n event.code !== 1000 &&\n !intentionalDisconnectRef.current &&\n mountedRef.current\n ) {\n const retryInterval = calculateRetryInterval(\n retryCountRef.current\n );\n retryCountRef.current++;\n\n logger.info(\n `Reconnecting in ${retryInterval}ms (attempt ${retryCountRef.current})`\n );\n\n if (reconnectTimeoutRef.current) {\n clearTimeout(reconnectTimeoutRef.current);\n }\n reconnectTimeoutRef.current = setTimeout(() => {\n connect(userId);\n }, retryInterval);\n }\n };\n\n ws.onerror = (error) => {\n logger.error(\"WebSocket error:\", error);\n if (!mountedRef.current) return;\n\n const wsError: WebSocketError = {\n code: \"CONNECTION_FAILED\",\n message: \"WebSocket connection failed\",\n retryable: true,\n timestamp: Date.now(),\n };\n setError(wsError);\n updateMetrics({ lastError: wsError });\n\n // Reject the promise on error\n reject(wsError);\n };\n\n wsRef.current = ws;\n } catch (error) {\n logger.error(\"Failed to create WebSocket:\", error);\n const wsError: WebSocketError = {\n code: \"CONNECTION_FAILED\",\n message:\n error instanceof Error\n ? error.message\n : \"Failed to create connection\",\n retryable: true,\n timestamp: Date.now(),\n };\n setError(wsError);\n updateMetrics({ lastError: wsError });\n reject(wsError);\n }\n });\n },\n [\n serverBaseUrl,\n orgId,\n clientType,\n product,\n connectionState,\n logger,\n retryConfig,\n metrics,\n updateMetrics,\n cleanup,\n calculateRetryInterval,\n startHeartbeat,\n emit,\n ]\n );\n\n // Send message with promise\n const sendMessage = useCallback(\n (\n event: Omit<ChatEvent, \"timestamp\">,\n overrideUserId?: string\n ): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (!mountedRef.current) {\n reject(new Error(\"Component not mounted\"));\n return;\n }\n\n const fullEvent: ChatEvent = {\n ...event,\n timestamp: Date.now(),\n };\n\n const messageId = `${fullEvent.type}_${fullEvent.timestamp}_${Math.random()}`;\n logger.debug(\"Sending message:\", fullEvent.type);\n\n if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {\n // Queue the message\n if (addToQueue(fullEvent)) {\n logger.debug(\"Message queued, attempting to connect\");\n if (connectionState === \"disconnected\" && overrideUserId) {\n connect(overrideUserId)\n .then(() => resolve())\n .catch(reject);\n } else {\n // Message is queued, will be sent when connected\n resolve();\n }\n } else {\n reject(new Error(\"Message queue full\"));\n }\n return;\n }\n\n try {\n wsRef.current.send(JSON.stringify(fullEvent));\n updateMetrics({ messagesSent: metrics.messagesSent + 1 });\n logger.debug(\"Message sent successfully\");\n resolve();\n } catch (error) {\n logger.error(\"Failed to send message:\", error);\n if (addToQueue(fullEvent)) {\n // Message queued for retry\n resolve();\n } else {\n const sendError: WebSocketError = {\n code: \"SEND_FAILED\",\n message:\n error instanceof Error\n ? error.message\n : \"Failed to send message\",\n retryable: true,\n timestamp: Date.now(),\n };\n setError(sendError);\n updateMetrics({ lastError: sendError });\n reject(sendError);\n }\n }\n });\n },\n [connectionState, connect, addToQueue, logger, metrics, updateMetrics]\n );\n\n // Start new chat with promise\n const startNewChat = useCallback(\n (userId: string, data?: { [key: string]: any }): Promise<string> => {\n return new Promise((resolve, reject) => {\n if (!userId) {\n reject(new Error(\"User ID is required\"));\n return;\n }\n\n logger.info(\"Requesting new chat from server with userId:\", userId);\n setStartTime(new Date());\n\n // Set up promise handlers\n chatCreationPromiseRef.current = { resolve, reject };\n\n // Send request to server to create new chat\n sendMessage(\n {\n type: \"new_chat\",\n orgId,\n chatKey: \"\", // Server will generate\n userId,\n data: data ?? {},\n },\n userId\n ).catch((error) => {\n chatCreationPromiseRef.current = null;\n reject(error);\n });\n\n // Set timeout for chat creation\n setTimeout(() => {\n if (chatCreationPromiseRef.current) {\n chatCreationPromiseRef.current = null;\n reject(new Error(\"Chat creation timed out\"));\n }\n }, 30000); // 30 second timeout\n });\n },\n [sendMessage, orgId, logger]\n );\n\n // Disconnect function\n const disconnect = useCallback(\n (intentional: boolean = true) => {\n logger.info(\"Disconnecting WebSocket\", { intentional });\n intentionalDisconnectRef.current = intentional;\n cleanup();\n setConnectionState(\"disconnected\");\n messageQueueRef.current = [];\n retryCountRef.current = 0;\n mountedRef.current = false;\n currentChatKeyRef.current = undefined;\n currentUserIdRef.current = undefined;\n },\n [cleanup, logger]\n );\n\n // Clear error\n const clearError = useCallback(() => {\n setError(undefined);\n }, []);\n\n // Cleanup on unmount\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n disconnect(true);\n };\n }, []);\n\n return {\n connectionState,\n isConnected,\n sendMessage,\n error,\n connect,\n startNewChat,\n startTime,\n disconnect,\n metrics,\n on,\n off,\n clearError,\n };\n};\n"]}
@@ -1,529 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
-
3
- var _chunkDTFTLFSYjs = require('./chunk-DTFTLFSY.js');
4
-
5
- // hooks/use-websocket-chat-admin.ts
6
- var _react = require('react');
7
-
8
- // models/chat-models.ts
9
- var ChatStatusActive = "active";
10
- var ChatStatusDisconnected = "disconnected";
11
- var ChatStatusAbandoned = "abandoned";
12
- var ChatStatusClosed = "closed";
13
- var ChatStatusArchived = "archived";
14
- var ChatTypeCustomerSupport = "customer_support";
15
- var ChatTypePublicRoom = "public_room";
16
- var ChatTypePrivateRoom = "private_room";
17
- var ChatTypeDirect = "direct";
18
- var ChatTypeGroup = "group";
19
- var ChatRoleUser = "user";
20
- var ChatRoleAI = "ai";
21
- var ChatRoleEvent = "event";
22
- var ChatRoleHumanAgent = "humanAgent";
23
- var ChatRoleObserver = "observer";
24
- var ChatRoleDataQuery = "dataQuery";
25
- var ChatRoleSystem = "system";
26
- var ChatRoleTool = "tool";
27
- var AgentStatusOnline = "online";
28
- var AgentStatusAway = "away";
29
- var AgentStatusBusy = "busy";
30
- var AgentStatusOffline = "offline";
31
- var ChatEventTypeUserJoined = "user_joined";
32
- var ChatEventTypeUserLeft = "user_left";
33
- var ChatEventTypeTyping = "typing";
34
- var ChatEventTypeStoppedTyping = "stopped_typing";
35
- var ChatEventTypeRead = "read";
36
- var ChatEventTypeDelivered = "delivered";
37
- var ChatEventTypeReconnected = "reconnected";
38
- var ChatEventTypeError = "error";
39
- var ChatEventTypeWaiting = "waiting";
40
- var ChatEventTypeLoadChat = "load_chat";
41
- var ChatEventTypeLoadChatResponse = "load_chat_response";
42
- var ChatEventTypeMessage = "message";
43
- var ChatEventTypeWaitingForAgent = "waiting_for_agent";
44
- var ChatEventTypeMessageStatusUpdate = "message_status_update";
45
- var ChatEventTypeHumanAgentJoined = "human_agent_joined";
46
- var ChatEventTypeHumanAgentLeft = "human_agent_left";
47
- var ChatEventTypeObserverJoined = "observer_joined";
48
- var ChatEventTypeObserverLeft = "observer_left";
49
- var ChatEventTypeListChats = "list_chats";
50
- var ChatEventTypeChatUpdated = "chat_updated";
51
- var ChatEventTypeChatRemoved = "chat_removed";
52
- var ChatEventTypeSyncMetadata = "sync_metadata";
53
- var ChatEventTypeSyncMetadataResponse = "sync_metadata_response";
54
- var ChatEventTypeSyncUserSession = "sync_user_session";
55
- var ChatEventTypeSyncUserSessionResponse = "sync_user_session_response";
56
- var ChatEventTypeClientAction = "client_action";
57
- var ChatEventTypeClientActionCallback = "client_action_callback";
58
- var ChatEventTypeBlockUser = "block_user";
59
- var ChatEventTypeCreateRoom = "create_room";
60
- var ChatEventTypeRoomCreated = "room_created";
61
- var ChatEventTypeJoinRoom = "join_room";
62
- var ChatEventTypeLeaveRoom = "leave_room";
63
- var ChatEventTypeDeleteRoom = "delete_room";
64
- var ChatEventTypeRoomDeleted = "room_deleted";
65
- var ChatEventTypeUpdateRoom = "update_room";
66
- var ChatEventTypeRoomUpdated = "room_updated";
67
- var ChatEventTypeInviteUser = "invite_user";
68
- var ChatEventTypeUserInvited = "user_invited";
69
- var ChatEventTypeRoomUserJoined = "room_user_joined";
70
- var ChatEventTypeRoomUserLeft = "room_user_left";
71
- var ChatEventTypeUserRemoved = "user_removed";
72
- var ChatEventTypeListRooms = "list_rooms";
73
- var ChatEventTypeRoomsResponse = "rooms_response";
74
- var ChatEventTypeMessageEdited = "message_edited";
75
- var ChatEventTypeMessageDeleted = "message_deleted";
76
- var ChatEventTypeMessageReaction = "message_reaction";
77
- var ChatEventTypeMessageReply = "message_reply";
78
- var ChatEventTypeMentionUser = "mention_user";
79
- var ChatEventTypeMessageEditedResponse = "message_edited_response";
80
- var ChatEventTypeMessageDeletedResponse = "message_deleted_response";
81
- var ChatEventTypeMessageReactionResponse = "message_reaction_response";
82
- var ChatEventTypeUserPresenceStart = "user_presence_start";
83
- var ChatEventTypeUserPresenceEnd = "user_presence_end";
84
- var ChatEventTypeUserStatusChange = "user_status_change";
85
- var ChatEventTypeUserActivity = "user_activity";
86
- var ChatEventTypeUserPresenceChanged = "user_presence_changed";
87
- var ChatEventTypeUserActivityUpdate = "user_activity_update";
88
- var ChatEventTypeGetOnlineUsers = "get_online_users";
89
- var ChatEventTypeOnlineUsersResponse = "online_users";
90
- var ChatEventTypeEndChat = "end_chat";
91
- var ChatEventTypeChatEnded = "chat_ended";
92
- var ChatEventTypeAgentSessionStart = "agent_session_start";
93
- var ChatEventTypeAgentSessionEnd = "agent_session_end";
94
- var ChatEventTypeAgentStatusChange = "agent_status_change";
95
- var ChatEventTypeAgentActivityPing = "agent_activity_ping";
96
- var ChatEventTypeAgentChatAssigned = "agent_chat_assigned";
97
- var ChatEventTypeAgentChatCompleted = "agent_chat_completed";
98
- var ChatEventTypeGetAgents = "get_agents";
99
- var ChatEventTypeGetAgentsResponse = "get_agents_response";
100
- var ChatEventTypeCSATRequest = "csat_request";
101
- var ChatEventTypeCSATSurvey = "show_csat_survey";
102
- var ChatEventTypeCSATResponse = "csat_response";
103
- var ChatEventTypeUserSuggestedActions = "user_suggested_actions";
104
- var ChatEventTypeUserSuggestedActionSelected = "user_suggested_action_selected";
105
- var ChatEventTypeSummaryUpdate = "summary_update";
106
- var ChatEventTypeAgentContextUpdate = "agent_context_update";
107
- var ChatEventTypeAgentExecutionStarted = "agent_execution_started";
108
- var ChatEventTypeAgentExecutionEnded = "agent_execution_ended";
109
- var ChatEventTypeLoadAgentContext = "load_agent_context";
110
- var ChatEventTypeLoadAgentContextResponse = "load_agent_context_response";
111
- var ChatEventTypePlanPendingApproval = "plan_pending_approval";
112
- var ChatEventTypePlanApproved = "plan_approved";
113
- var ChatEventTypePlanRejected = "plan_rejected";
114
- var ChatEventTypePlanCompleted = "plan_completed";
115
- var ChatEventTypeStepStarted = "step_started";
116
- var ChatEventTypeStepCompleted = "step_completed";
117
- var ChatEventTypeStepFailed = "step_failed";
118
- var ChatEventTypeNewChat = "new_chat";
119
- var ChatEventTypeNewChatCreated = "new_chat_created";
120
- var ChatEventTypePing = "ping";
121
- var ChatEventTypePong = "pong";
122
- var MessageStatusSending = "sending";
123
- var MessageStatusSent = "sent";
124
- var MessageStatusDelivered = "delivered";
125
- var MessageStatusRead = "read";
126
- var MessageStatusFailed = "failed";
127
- var AttachmentTypeDocument = "document";
128
- var AttachmentTypeDocumentAnalysis = "document_analysis";
129
- var AttachmentTypeImage = "image";
130
- var AttachmentTypeAudio = "audio";
131
- var AttachmentTypeVideo = "video";
132
- var AttachmentTypeLocation = "location";
133
- var AttachmentTypeReferences = "references";
134
- var AttachmentTypeSubsections = "subsections";
135
- var AttachmentTypeArticles = "articles";
136
- var AttachmentTypeRecords = "records";
137
- var AttachmentTypeActions = "actions";
138
- var AttachmentTypeBullets = "bullets";
139
- var AttachmentTypeSticker = "sticker";
140
- var AttachmentTypeData = "data";
141
- var AttachmentTypeKGNodes = "kgNodes";
142
- var AttachmentTypeDocumentSources = "document_sources";
143
- var ChatSessionStatusActive = "active";
144
- var ChatSessionStatusIdle = "idle";
145
- var ChatSessionStatusExpired = "expired";
146
- var UserStatusOnline = "online";
147
- var UserStatusAway = "away";
148
- var UserStatusBusy = "busy";
149
- var UserStatusOffline = "offline";
150
- var QueueTypes = {
151
- skill: { value: "skill", label: "Skill-based", description: "Route by agent expertise and skills" },
152
- priority: { value: "priority", label: "Priority-based", description: "Route by customer tier and urgency level" },
153
- department: { value: "department", label: "Department-based", description: "Route by business function alignment" },
154
- complexity: { value: "complexity", label: "Complexity-based", description: "Route by issue difficulty assessment" }
155
- };
156
- var QueueTypeSkill = "skill";
157
- var QueueTypePriority = "priority";
158
- var QueueTypeDepartment = "department";
159
- var QueueTypeComplexity = "complexity";
160
- var GetWaitingForAgentChatCountSubject = "chat.get_waiting_for_agent_chat_count";
161
- var GetActiveChatCountSubject = "chat.get_active_chat_count";
162
- var GetWaitingForAgentChatsSubject = "chat.get_waiting_for_agent_chats";
163
- var GetActiveChatsSubject = "chat.get_active_chats";
164
- var GetUserChatsSubject = "chat.get_user_chats";
165
- var GetChatSubject = "chat.get_chat";
166
- var ChatArchiveSubjectPattern = "chat.archive.%s.server";
167
- var StartAgentSessionSubject = "chat.agent_session.start";
168
- var EndAgentSessionSubject = "chat.agent_session.end";
169
- var UpdateAgentStatusSubject = "chat.agent_session.update_status";
170
- var UpdateAgentLastActivitySubject = "chat.agent_session.update_last_activity";
171
- var AssignChatToAgentSubject = "chat.agent_session.assign_chat";
172
- var CompleteChatByAgentSubject = "chat.agent_session.complete_chat";
173
- var GetAgentSessionSubject = "chat.agent_session.get";
174
- var GetOnlineAgentsSubject = "chat.agent_session.get_online_agents";
175
- var GetOnlineAgentCountSubject = "chat.agent_session.get_online_agent_count";
176
- var CreateAgentQueueSubject = "chat.agent_queue.create";
177
- var GetAgentQueuesSubject = "chat.agent_queue.get";
178
- var UpdateAgentQueueSubject = "chat.agent_queue.update";
179
- var DeleteAgentQueueSubject = "chat.agent_queue.delete";
180
- var GetQueueChatsSubject = "chat.queue.get_chats";
181
- var GetQueueChatCountSubject = "chat.queue.get_chat_count";
182
- var GetDailyChatCountSubject = "chat.get_daily_chat_count";
183
- var UpdateUserStatusSubject = "chat.user.status.update";
184
- var GetOnlineUsersSubject = "chat.users.online.get";
185
- var TriggerAnalyticsScanSubject = "chat.analytics.trigger-scan";
186
- var SetupOrgSubject = "chat.org.setup";
187
-
188
- // hooks/use-websocket-chat-admin.ts
189
- var useWebSocketChatAdmin = ({
190
- serverBaseUrl,
191
- orgId,
192
- product
193
- }) => {
194
- const [chats, setChats] = _react.useState.call(void 0, /* @__PURE__ */ new Map());
195
- const [selectedChat, setSelectedChat] = _react.useState.call(void 0, void 0);
196
- const handleMessage = _react.useCallback.call(void 0,
197
- (chatEvent) => {
198
- switch (chatEvent.type) {
199
- case "message":
200
- if (!selectedChat || !chatEvent.message) return;
201
- setChats((prev) => {
202
- const newMap = new Map(prev);
203
- newMap.set(selectedChat.key, {
204
- ...selectedChat,
205
- messages: [...selectedChat.messages, chatEvent.message]
206
- });
207
- return newMap;
208
- });
209
- setSelectedChat((prev) => {
210
- if (!prev) return prev;
211
- return {
212
- ...prev,
213
- messages: [...prev.messages, chatEvent.message]
214
- };
215
- });
216
- break;
217
- case "list_chats":
218
- const chatList = _optionalChain([chatEvent, 'access', _ => _.data, 'optionalAccess', _2 => _2.chats]);
219
- if (!chatList) return;
220
- setChats(new Map(chatList.map((chat) => [chat.key, chat])));
221
- break;
222
- case "chat_updated":
223
- const updatedChat = _optionalChain([chatEvent, 'access', _3 => _3.data, 'optionalAccess', _4 => _4.chat, 'optionalAccess', _5 => _5.value]);
224
- if (updatedChat) {
225
- setChats((prev) => new Map(prev).set(updatedChat.key, updatedChat));
226
- }
227
- break;
228
- case "chat_removed":
229
- const chatKey = _optionalChain([chatEvent, 'access', _6 => _6.data, 'optionalAccess', _7 => _7.chatKey, 'optionalAccess', _8 => _8.value]);
230
- if (chatKey) {
231
- setChats((prev) => {
232
- const newMap = new Map(prev);
233
- newMap.delete(chatKey);
234
- return newMap;
235
- });
236
- }
237
- break;
238
- case "load_chat":
239
- const history = _optionalChain([chatEvent, 'access', _9 => _9.data, 'optionalAccess', _10 => _10.chat, 'optionalAccess', _11 => _11.value]);
240
- if (history) {
241
- setChats((prev) => {
242
- const existingChat = prev.get(history.key);
243
- if (!existingChat) return prev;
244
- return new Map(prev).set(history.key, {
245
- ...existingChat,
246
- messages: history.messages
247
- });
248
- });
249
- }
250
- break;
251
- }
252
- },
253
- [selectedChat]
254
- );
255
- const base = _chunkDTFTLFSYjs.useWebSocketChatBase.call(void 0, {
256
- serverBaseUrl,
257
- orgId,
258
- clientType: "humanAgent",
259
- onMessage: handleMessage,
260
- product
261
- });
262
- const selectChat = _react.useCallback.call(void 0,
263
- (chatKey) => {
264
- const chat = chats.get(chatKey);
265
- if (!chat) {
266
- console.error("Unable to select chat", chatKey);
267
- return;
268
- }
269
- setSelectedChat(chat);
270
- },
271
- [chats, orgId, base.sendMessage]
272
- );
273
- const addUserToChat = _react.useCallback.call(void 0,
274
- (orgId2, chatKey, user) => {
275
- base.sendMessage({
276
- type: "human_agent_joined",
277
- orgId: orgId2,
278
- chatKey,
279
- userId: user.email,
280
- data: { user }
281
- });
282
- setChats((prev) => {
283
- const newMap = new Map(prev);
284
- const chat = newMap.get(chatKey);
285
- if (!chat) return prev;
286
- newMap.set(chatKey, {
287
- ...chat,
288
- humanAgentEngaged: user.role === ChatRoleHumanAgent,
289
- users: [..._nullishCoalesce(_optionalChain([chat, 'optionalAccess', _12 => _12.users]), () => ( [])), user]
290
- });
291
- return newMap;
292
- });
293
- setSelectedChat((prev) => {
294
- if (!prev) return prev;
295
- return {
296
- ...prev,
297
- humanAgentEngaged: user.role === ChatRoleHumanAgent,
298
- users: [..._nullishCoalesce(prev.users, () => ( [])), user]
299
- };
300
- });
301
- },
302
- [base.sendMessage]
303
- );
304
- const removeUserFromChat = _react.useCallback.call(void 0,
305
- (orgId2, chatKey, userId) => {
306
- const chat = chats.get(chatKey);
307
- if (!chat) return;
308
- const user = _optionalChain([chat, 'access', _13 => _13.users, 'optionalAccess', _14 => _14.find, 'call', _15 => _15((u) => u.id === userId)]);
309
- if (!user) return;
310
- base.sendMessage({
311
- type: "human_agent_left",
312
- orgId: orgId2,
313
- chatKey,
314
- userId,
315
- data: { user }
316
- });
317
- setChats((prev) => {
318
- const newMap = new Map(prev);
319
- const chat2 = newMap.get(chatKey);
320
- if (!chat2) return prev;
321
- newMap.set(chatKey, {
322
- ...chat2,
323
- humanAgentEngaged: false,
324
- users: _optionalChain([chat2, 'access', _16 => _16.users, 'optionalAccess', _17 => _17.filter, 'call', _18 => _18((u) => u.id !== userId)])
325
- });
326
- return newMap;
327
- });
328
- },
329
- [chats, base.sendMessage]
330
- );
331
- const blockUser = _react.useCallback.call(void 0,
332
- (orgId2, chatKey, userId) => {
333
- base.sendMessage({
334
- type: "block_user",
335
- orgId: orgId2,
336
- chatKey,
337
- userId
338
- });
339
- },
340
- [base.sendMessage]
341
- );
342
- return {
343
- ...base,
344
- chats,
345
- selectedChat,
346
- selectChat,
347
- addUserToChat,
348
- removeUserFromChat,
349
- blockUser
350
- };
351
- };
352
-
353
-
354
-
355
-
356
-
357
-
358
-
359
-
360
-
361
-
362
-
363
-
364
-
365
-
366
-
367
-
368
-
369
-
370
-
371
-
372
-
373
-
374
-
375
-
376
-
377
-
378
-
379
-
380
-
381
-
382
-
383
-
384
-
385
-
386
-
387
-
388
-
389
-
390
-
391
-
392
-
393
-
394
-
395
-
396
-
397
-
398
-
399
-
400
-
401
-
402
-
403
-
404
-
405
-
406
-
407
-
408
-
409
-
410
-
411
-
412
-
413
-
414
-
415
-
416
-
417
-
418
-
419
-
420
-
421
-
422
-
423
-
424
-
425
-
426
-
427
-
428
-
429
-
430
-
431
-
432
-
433
-
434
-
435
-
436
-
437
-
438
-
439
-
440
-
441
-
442
-
443
-
444
-
445
-
446
-
447
-
448
-
449
-
450
-
451
-
452
-
453
-
454
-
455
-
456
-
457
-
458
-
459
-
460
-
461
-
462
-
463
-
464
-
465
-
466
-
467
-
468
-
469
-
470
-
471
-
472
-
473
-
474
-
475
-
476
-
477
-
478
-
479
-
480
-
481
-
482
-
483
-
484
-
485
-
486
-
487
-
488
-
489
-
490
-
491
-
492
-
493
-
494
-
495
-
496
-
497
-
498
-
499
-
500
-
501
-
502
-
503
-
504
-
505
-
506
-
507
-
508
-
509
-
510
-
511
-
512
-
513
-
514
-
515
-
516
-
517
-
518
-
519
-
520
-
521
-
522
-
523
-
524
-
525
-
526
-
527
-
528
- exports.ChatStatusActive = ChatStatusActive; exports.ChatStatusDisconnected = ChatStatusDisconnected; exports.ChatStatusAbandoned = ChatStatusAbandoned; exports.ChatStatusClosed = ChatStatusClosed; exports.ChatStatusArchived = ChatStatusArchived; exports.ChatTypeCustomerSupport = ChatTypeCustomerSupport; exports.ChatTypePublicRoom = ChatTypePublicRoom; exports.ChatTypePrivateRoom = ChatTypePrivateRoom; exports.ChatTypeDirect = ChatTypeDirect; exports.ChatTypeGroup = ChatTypeGroup; exports.ChatRoleUser = ChatRoleUser; exports.ChatRoleAI = ChatRoleAI; exports.ChatRoleEvent = ChatRoleEvent; exports.ChatRoleHumanAgent = ChatRoleHumanAgent; exports.ChatRoleObserver = ChatRoleObserver; exports.ChatRoleDataQuery = ChatRoleDataQuery; exports.ChatRoleSystem = ChatRoleSystem; exports.ChatRoleTool = ChatRoleTool; exports.AgentStatusOnline = AgentStatusOnline; exports.AgentStatusAway = AgentStatusAway; exports.AgentStatusBusy = AgentStatusBusy; exports.AgentStatusOffline = AgentStatusOffline; exports.ChatEventTypeUserJoined = ChatEventTypeUserJoined; exports.ChatEventTypeUserLeft = ChatEventTypeUserLeft; exports.ChatEventTypeTyping = ChatEventTypeTyping; exports.ChatEventTypeStoppedTyping = ChatEventTypeStoppedTyping; exports.ChatEventTypeRead = ChatEventTypeRead; exports.ChatEventTypeDelivered = ChatEventTypeDelivered; exports.ChatEventTypeReconnected = ChatEventTypeReconnected; exports.ChatEventTypeError = ChatEventTypeError; exports.ChatEventTypeWaiting = ChatEventTypeWaiting; exports.ChatEventTypeLoadChat = ChatEventTypeLoadChat; exports.ChatEventTypeLoadChatResponse = ChatEventTypeLoadChatResponse; exports.ChatEventTypeMessage = ChatEventTypeMessage; exports.ChatEventTypeWaitingForAgent = ChatEventTypeWaitingForAgent; exports.ChatEventTypeMessageStatusUpdate = ChatEventTypeMessageStatusUpdate; exports.ChatEventTypeHumanAgentJoined = ChatEventTypeHumanAgentJoined; exports.ChatEventTypeHumanAgentLeft = ChatEventTypeHumanAgentLeft; exports.ChatEventTypeObserverJoined = ChatEventTypeObserverJoined; exports.ChatEventTypeObserverLeft = ChatEventTypeObserverLeft; exports.ChatEventTypeListChats = ChatEventTypeListChats; exports.ChatEventTypeChatUpdated = ChatEventTypeChatUpdated; exports.ChatEventTypeChatRemoved = ChatEventTypeChatRemoved; exports.ChatEventTypeSyncMetadata = ChatEventTypeSyncMetadata; exports.ChatEventTypeSyncMetadataResponse = ChatEventTypeSyncMetadataResponse; exports.ChatEventTypeSyncUserSession = ChatEventTypeSyncUserSession; exports.ChatEventTypeSyncUserSessionResponse = ChatEventTypeSyncUserSessionResponse; exports.ChatEventTypeClientAction = ChatEventTypeClientAction; exports.ChatEventTypeClientActionCallback = ChatEventTypeClientActionCallback; exports.ChatEventTypeBlockUser = ChatEventTypeBlockUser; exports.ChatEventTypeCreateRoom = ChatEventTypeCreateRoom; exports.ChatEventTypeRoomCreated = ChatEventTypeRoomCreated; exports.ChatEventTypeJoinRoom = ChatEventTypeJoinRoom; exports.ChatEventTypeLeaveRoom = ChatEventTypeLeaveRoom; exports.ChatEventTypeDeleteRoom = ChatEventTypeDeleteRoom; exports.ChatEventTypeRoomDeleted = ChatEventTypeRoomDeleted; exports.ChatEventTypeUpdateRoom = ChatEventTypeUpdateRoom; exports.ChatEventTypeRoomUpdated = ChatEventTypeRoomUpdated; exports.ChatEventTypeInviteUser = ChatEventTypeInviteUser; exports.ChatEventTypeUserInvited = ChatEventTypeUserInvited; exports.ChatEventTypeRoomUserJoined = ChatEventTypeRoomUserJoined; exports.ChatEventTypeRoomUserLeft = ChatEventTypeRoomUserLeft; exports.ChatEventTypeUserRemoved = ChatEventTypeUserRemoved; exports.ChatEventTypeListRooms = ChatEventTypeListRooms; exports.ChatEventTypeRoomsResponse = ChatEventTypeRoomsResponse; exports.ChatEventTypeMessageEdited = ChatEventTypeMessageEdited; exports.ChatEventTypeMessageDeleted = ChatEventTypeMessageDeleted; exports.ChatEventTypeMessageReaction = ChatEventTypeMessageReaction; exports.ChatEventTypeMessageReply = ChatEventTypeMessageReply; exports.ChatEventTypeMentionUser = ChatEventTypeMentionUser; exports.ChatEventTypeMessageEditedResponse = ChatEventTypeMessageEditedResponse; exports.ChatEventTypeMessageDeletedResponse = ChatEventTypeMessageDeletedResponse; exports.ChatEventTypeMessageReactionResponse = ChatEventTypeMessageReactionResponse; exports.ChatEventTypeUserPresenceStart = ChatEventTypeUserPresenceStart; exports.ChatEventTypeUserPresenceEnd = ChatEventTypeUserPresenceEnd; exports.ChatEventTypeUserStatusChange = ChatEventTypeUserStatusChange; exports.ChatEventTypeUserActivity = ChatEventTypeUserActivity; exports.ChatEventTypeUserPresenceChanged = ChatEventTypeUserPresenceChanged; exports.ChatEventTypeUserActivityUpdate = ChatEventTypeUserActivityUpdate; exports.ChatEventTypeGetOnlineUsers = ChatEventTypeGetOnlineUsers; exports.ChatEventTypeOnlineUsersResponse = ChatEventTypeOnlineUsersResponse; exports.ChatEventTypeEndChat = ChatEventTypeEndChat; exports.ChatEventTypeChatEnded = ChatEventTypeChatEnded; exports.ChatEventTypeAgentSessionStart = ChatEventTypeAgentSessionStart; exports.ChatEventTypeAgentSessionEnd = ChatEventTypeAgentSessionEnd; exports.ChatEventTypeAgentStatusChange = ChatEventTypeAgentStatusChange; exports.ChatEventTypeAgentActivityPing = ChatEventTypeAgentActivityPing; exports.ChatEventTypeAgentChatAssigned = ChatEventTypeAgentChatAssigned; exports.ChatEventTypeAgentChatCompleted = ChatEventTypeAgentChatCompleted; exports.ChatEventTypeGetAgents = ChatEventTypeGetAgents; exports.ChatEventTypeGetAgentsResponse = ChatEventTypeGetAgentsResponse; exports.ChatEventTypeCSATRequest = ChatEventTypeCSATRequest; exports.ChatEventTypeCSATSurvey = ChatEventTypeCSATSurvey; exports.ChatEventTypeCSATResponse = ChatEventTypeCSATResponse; exports.ChatEventTypeUserSuggestedActions = ChatEventTypeUserSuggestedActions; exports.ChatEventTypeUserSuggestedActionSelected = ChatEventTypeUserSuggestedActionSelected; exports.ChatEventTypeSummaryUpdate = ChatEventTypeSummaryUpdate; exports.ChatEventTypeAgentContextUpdate = ChatEventTypeAgentContextUpdate; exports.ChatEventTypeAgentExecutionStarted = ChatEventTypeAgentExecutionStarted; exports.ChatEventTypeAgentExecutionEnded = ChatEventTypeAgentExecutionEnded; exports.ChatEventTypeLoadAgentContext = ChatEventTypeLoadAgentContext; exports.ChatEventTypeLoadAgentContextResponse = ChatEventTypeLoadAgentContextResponse; exports.ChatEventTypePlanPendingApproval = ChatEventTypePlanPendingApproval; exports.ChatEventTypePlanApproved = ChatEventTypePlanApproved; exports.ChatEventTypePlanRejected = ChatEventTypePlanRejected; exports.ChatEventTypePlanCompleted = ChatEventTypePlanCompleted; exports.ChatEventTypeStepStarted = ChatEventTypeStepStarted; exports.ChatEventTypeStepCompleted = ChatEventTypeStepCompleted; exports.ChatEventTypeStepFailed = ChatEventTypeStepFailed; exports.ChatEventTypeNewChat = ChatEventTypeNewChat; exports.ChatEventTypeNewChatCreated = ChatEventTypeNewChatCreated; exports.ChatEventTypePing = ChatEventTypePing; exports.ChatEventTypePong = ChatEventTypePong; exports.MessageStatusSending = MessageStatusSending; exports.MessageStatusSent = MessageStatusSent; exports.MessageStatusDelivered = MessageStatusDelivered; exports.MessageStatusRead = MessageStatusRead; exports.MessageStatusFailed = MessageStatusFailed; exports.AttachmentTypeDocument = AttachmentTypeDocument; exports.AttachmentTypeDocumentAnalysis = AttachmentTypeDocumentAnalysis; exports.AttachmentTypeImage = AttachmentTypeImage; exports.AttachmentTypeAudio = AttachmentTypeAudio; exports.AttachmentTypeVideo = AttachmentTypeVideo; exports.AttachmentTypeLocation = AttachmentTypeLocation; exports.AttachmentTypeReferences = AttachmentTypeReferences; exports.AttachmentTypeSubsections = AttachmentTypeSubsections; exports.AttachmentTypeArticles = AttachmentTypeArticles; exports.AttachmentTypeRecords = AttachmentTypeRecords; exports.AttachmentTypeActions = AttachmentTypeActions; exports.AttachmentTypeBullets = AttachmentTypeBullets; exports.AttachmentTypeSticker = AttachmentTypeSticker; exports.AttachmentTypeData = AttachmentTypeData; exports.AttachmentTypeKGNodes = AttachmentTypeKGNodes; exports.AttachmentTypeDocumentSources = AttachmentTypeDocumentSources; exports.ChatSessionStatusActive = ChatSessionStatusActive; exports.ChatSessionStatusIdle = ChatSessionStatusIdle; exports.ChatSessionStatusExpired = ChatSessionStatusExpired; exports.UserStatusOnline = UserStatusOnline; exports.UserStatusAway = UserStatusAway; exports.UserStatusBusy = UserStatusBusy; exports.UserStatusOffline = UserStatusOffline; exports.QueueTypes = QueueTypes; exports.QueueTypeSkill = QueueTypeSkill; exports.QueueTypePriority = QueueTypePriority; exports.QueueTypeDepartment = QueueTypeDepartment; exports.QueueTypeComplexity = QueueTypeComplexity; exports.GetWaitingForAgentChatCountSubject = GetWaitingForAgentChatCountSubject; exports.GetActiveChatCountSubject = GetActiveChatCountSubject; exports.GetWaitingForAgentChatsSubject = GetWaitingForAgentChatsSubject; exports.GetActiveChatsSubject = GetActiveChatsSubject; exports.GetUserChatsSubject = GetUserChatsSubject; exports.GetChatSubject = GetChatSubject; exports.ChatArchiveSubjectPattern = ChatArchiveSubjectPattern; exports.StartAgentSessionSubject = StartAgentSessionSubject; exports.EndAgentSessionSubject = EndAgentSessionSubject; exports.UpdateAgentStatusSubject = UpdateAgentStatusSubject; exports.UpdateAgentLastActivitySubject = UpdateAgentLastActivitySubject; exports.AssignChatToAgentSubject = AssignChatToAgentSubject; exports.CompleteChatByAgentSubject = CompleteChatByAgentSubject; exports.GetAgentSessionSubject = GetAgentSessionSubject; exports.GetOnlineAgentsSubject = GetOnlineAgentsSubject; exports.GetOnlineAgentCountSubject = GetOnlineAgentCountSubject; exports.CreateAgentQueueSubject = CreateAgentQueueSubject; exports.GetAgentQueuesSubject = GetAgentQueuesSubject; exports.UpdateAgentQueueSubject = UpdateAgentQueueSubject; exports.DeleteAgentQueueSubject = DeleteAgentQueueSubject; exports.GetQueueChatsSubject = GetQueueChatsSubject; exports.GetQueueChatCountSubject = GetQueueChatCountSubject; exports.GetDailyChatCountSubject = GetDailyChatCountSubject; exports.UpdateUserStatusSubject = UpdateUserStatusSubject; exports.GetOnlineUsersSubject = GetOnlineUsersSubject; exports.TriggerAnalyticsScanSubject = TriggerAnalyticsScanSubject; exports.SetupOrgSubject = SetupOrgSubject; exports.useWebSocketChatAdmin = useWebSocketChatAdmin;
529
- //# sourceMappingURL=chunk-E2FJX52R.js.map