@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/README.md +6 -0
- package/SKILL.md +531 -0
- package/TIER2_AUTH.md +258 -0
- package/dist/api/index.d.mts +11 -0
- package/dist/api/index.d.ts +11 -0
- package/dist/api/index.js +27 -9
- package/dist/api/index.js.map +1 -1
- package/dist/api/index.mjs +27 -10
- package/dist/api/index.mjs.map +1 -1
- package/dist/hooks/index.d.mts +73 -35
- package/dist/hooks/index.d.ts +73 -35
- package/dist/hooks/index.js +43 -10
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +42 -9
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/index.d.mts +1 -6
- package/dist/index.d.ts +1 -6
- package/dist/index.js +2 -1487
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1480
- package/dist/index.mjs.map +1 -1
- package/dist/models/index.js +0 -1
- package/dist/models/index.js.map +1 -1
- package/dist/models/index.mjs +0 -2
- package/dist/models/index.mjs.map +1 -1
- package/dist/transport/index.d.mts +2 -2
- package/dist/transport/index.d.ts +2 -2
- package/dist/transport/index.js +30 -7
- package/dist/transport/index.js.map +1 -1
- package/dist/transport/index.mjs +30 -8
- package/dist/transport/index.mjs.map +1 -1
- package/dist/{types-CQHtUQ6p.d.mts → types-CLtQA6Qq.d.mts} +16 -0
- package/dist/{types-7UNI1iYv.d.ts → types-CxibhkqW.d.ts} +16 -0
- package/package.json +7 -5
package/dist/api/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../api/index.ts","../../api/stream-api.ts","../../api/memory.ts"],"sourcesContent":["/**\n * Chat API\n *\n * API functions for chat operations.\n *\n * ## Browser API (uses @elqnt/api-client)\n * ```typescript\n * import { getChatHistoryApi, getChatApi } from \"@elqnt/chat/api\";\n *\n * const history = await getChatHistoryApi({ baseUrl, orgId, limit: 10 });\n * const chat = await getChatApi(chatKey, { baseUrl, orgId });\n * ```\n *\n * ## Stream API (direct HTTP calls)\n * ```typescript\n * import { createChat, sendChatMessage, loadChat } from \"@elqnt/chat/api\";\n *\n * const chatKey = await createChat({ baseUrl, orgId, userId });\n * await sendChatMessage({ baseUrl, orgId, chatKey, userId, content: \"Hello!\" });\n * ```\n */\n\nimport { browserApiRequest } from \"@elqnt/api-client/browser\";\nimport type { ApiResponse, ApiClientOptions } from \"@elqnt/api-client\";\nimport type { ResponseMetadata } from \"@elqnt/types\";\nimport type { ChatSummary, Chat } from \"../models\";\n\n// Re-export types from models\nexport type { ChatSummary, Chat } from \"../models\";\n\n// Re-export stream API functions\nexport {\n createChat,\n sendChatMessage,\n loadChat,\n endChat,\n sendTypingIndicator,\n sendEvent,\n} from \"./stream-api\";\n\nexport type {\n StreamApiOptions,\n StreamApiResponse,\n CreateChatApiOptions,\n CreateChatResponseData,\n SendMessageApiOptions,\n LoadChatApiOptions,\n LoadChatResponseData,\n EndChatApiOptions,\n TypingApiOptions,\n SendEventApiOptions,\n} from \"./stream-api\";\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface ChatHistoryResponse {\n chats: ChatSummary[];\n total: number;\n hasMore: boolean;\n metadata: ResponseMetadata;\n}\n\nexport interface ChatResponse {\n chat: ChatSummary;\n metadata: ResponseMetadata;\n}\n\nexport interface UpdateChatResponse {\n chatKey: string;\n title: string;\n pinned: boolean;\n metadata: ResponseMetadata;\n}\n\nexport interface ActiveChatsResponse {\n chats: ChatSummary[];\n metadata: ResponseMetadata;\n}\n\nexport interface ActiveChatsCountResponse {\n count: number;\n metadata: ResponseMetadata;\n}\n\nexport interface WaitingChatsCountResponse {\n count: number;\n metadata: ResponseMetadata;\n}\n\nexport interface QueueResponse {\n queues: Queue[];\n metadata: ResponseMetadata;\n}\n\nexport interface Queue {\n id: string;\n name: string;\n agentId: string;\n waitingCount: number;\n activeCount: number;\n}\n\nexport interface AgentSession {\n agentId: string;\n userId: string;\n userEmail: string;\n status: string;\n connectedAt: string;\n lastActivityAt: string;\n}\n\nexport interface OnlineSessionsResponse {\n sessions: AgentSession[];\n metadata: ResponseMetadata;\n}\n\nexport interface AgentSessionResponse {\n session: AgentSession;\n metadata: ResponseMetadata;\n}\n\n// =============================================================================\n// CHAT HISTORY\n// =============================================================================\n\nexport async function getChatHistoryApi(\n options: ApiClientOptions & { limit?: number; offset?: number; skipCache?: boolean }\n): Promise<ApiResponse<ChatHistoryResponse>> {\n return browserApiRequest(\"/api/v1/chats\", {\n method: \"POST\",\n body: {\n limit: options.limit || 15,\n offset: options.offset || 0,\n ...(options.skipCache ? { skipCache: true } : {}),\n },\n ...options,\n });\n}\n\nexport async function getChatApi(\n chatKey: string,\n options: ApiClientOptions\n): Promise<ApiResponse<ChatResponse>> {\n return browserApiRequest(`/api/v1/chats/${chatKey}`, {\n method: \"GET\",\n ...options,\n });\n}\n\nexport async function updateChatApi(\n chatKey: string,\n updates: { title?: string; pinned?: boolean },\n options: ApiClientOptions\n): Promise<ApiResponse<UpdateChatResponse>> {\n return browserApiRequest(`/api/v1/chats/${chatKey}`, {\n method: \"PATCH\",\n body: updates,\n ...options,\n });\n}\n\nexport async function deleteChatApi(\n chatKey: string,\n options: ApiClientOptions\n): Promise<ApiResponse<{ success: boolean; metadata: ResponseMetadata }>> {\n return browserApiRequest(`/api/v1/chats/${chatKey}`, {\n method: \"DELETE\",\n ...options,\n });\n}\n\n// =============================================================================\n// ACTIVE CHATS\n// =============================================================================\n\nexport async function getActiveChatsCountApi(\n options: ApiClientOptions\n): Promise<ApiResponse<ActiveChatsCountResponse>> {\n return browserApiRequest(\"/api/v1/chats/active/count\", {\n method: \"GET\",\n ...options,\n });\n}\n\nexport async function getActiveChatsApi(\n options: ApiClientOptions & { pastHours?: number }\n): Promise<ApiResponse<ActiveChatsResponse>> {\n const params = new URLSearchParams();\n if (options.pastHours) params.set(\"pastHours\", String(options.pastHours));\n const queryString = params.toString();\n return browserApiRequest(`/api/v1/chats/active${queryString ? `?${queryString}` : \"\"}`, {\n method: \"GET\",\n ...options,\n });\n}\n\n// =============================================================================\n// PROJECT CHATS\n// =============================================================================\n\nexport async function updateProjectChatTitleApi(\n projectId: string,\n chatKey: string,\n title: string,\n options: ApiClientOptions\n): Promise<ApiResponse<{ success: boolean; metadata: ResponseMetadata }>> {\n return browserApiRequest(`/api/v1/projects/${projectId}/chats/${chatKey}/title`, {\n method: \"PUT\",\n body: { title },\n ...options,\n });\n}\n\nexport async function addChatToProjectApi(\n projectId: string,\n chatKey: string,\n options: ApiClientOptions\n): Promise<ApiResponse<{ success: boolean; metadata: ResponseMetadata }>> {\n return browserApiRequest(`/api/v1/projects/${projectId}/chats`, {\n method: \"POST\",\n body: { chatKey },\n ...options,\n });\n}\n\n// =============================================================================\n// WAITING CHATS\n// =============================================================================\n\nexport async function getWaitingChatsCountApi(\n options: ApiClientOptions\n): Promise<ApiResponse<WaitingChatsCountResponse>> {\n return browserApiRequest(\"/api/v1/chats/waiting/count\", {\n method: \"GET\",\n ...options,\n });\n}\n\nexport async function getChatsByUserApi(\n userEmail: string,\n options: ApiClientOptions\n): Promise<ApiResponse<ChatHistoryResponse>> {\n return browserApiRequest(`/api/v1/chats/user/${encodeURIComponent(userEmail)}`, {\n method: \"GET\",\n ...options,\n });\n}\n\n// =============================================================================\n// QUEUES\n// =============================================================================\n\nexport async function listQueuesApi(\n options: ApiClientOptions\n): Promise<ApiResponse<QueueResponse>> {\n return browserApiRequest(\"/api/v1/queues\", {\n method: \"GET\",\n ...options,\n });\n}\n\n// =============================================================================\n// AGENT SESSIONS\n// =============================================================================\n\nexport async function getOnlineSessionsApi(\n options: ApiClientOptions\n): Promise<ApiResponse<OnlineSessionsResponse>> {\n return browserApiRequest(\"/api/v1/agents/sessions/online\", {\n method: \"GET\",\n ...options,\n });\n}\n\nexport async function getAgentSessionApi(\n agentId: string,\n options: ApiClientOptions\n): Promise<ApiResponse<AgentSessionResponse>> {\n return browserApiRequest(`/api/v1/agents/sessions/${agentId}`, {\n method: \"GET\",\n ...options,\n });\n}\n\n// =============================================================================\n// MEMORY\n// =============================================================================\n\nexport {\n getProfileApi,\n patchProfileApi,\n replaceProfileApi,\n clearProfileApi,\n deleteContactApi,\n deleteNoteApi,\n getSummaryApi,\n clearSummaryApi,\n regenerateSummaryApi,\n} from \"./memory\";\n\nexport type { SummaryView } from \"./memory\";\n","/**\n * Stream API\n *\n * Low-level functions for chat streaming operations.\n * These are used internally by the transport layer but can also\n * be used directly for custom implementations.\n *\n * @example\n * ```typescript\n * import { createChat, sendChatMessage, loadChat } from \"@elqnt/chat/api\";\n *\n * // Create a new chat\n * const chatKey = await createChat({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * userId: \"user-456\",\n * });\n *\n * // Send a message\n * await sendChatMessage({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey,\n * userId: \"user-456\",\n * content: \"Hello!\",\n * });\n * ```\n */\n\nimport type { Chat, ChatMessage } from \"../models\";\n\n/**\n * Base options for all stream API calls\n */\nexport interface StreamApiOptions {\n /** Base URL for the chat server */\n baseUrl: string;\n /** Organization ID */\n orgId: string;\n /** User ID */\n userId: string;\n}\n\n/**\n * Response from stream API calls\n */\nexport interface StreamApiResponse<T = unknown> {\n success: boolean;\n data?: T;\n error?: string;\n}\n\n/**\n * Create chat options\n */\nexport interface CreateChatApiOptions extends StreamApiOptions {\n /** Optional metadata for the new chat */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Create chat response data\n */\nexport interface CreateChatResponseData {\n chatKey: string;\n}\n\n/**\n * Send message options\n */\nexport interface SendMessageApiOptions extends StreamApiOptions {\n /** Chat key */\n chatKey: string;\n /** Message content */\n content: string;\n /** Optional attachments */\n attachments?: unknown[];\n /** Optional message metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Load chat options\n */\nexport interface LoadChatApiOptions extends StreamApiOptions {\n /** Chat key to load */\n chatKey: string;\n}\n\n/**\n * Load chat response data\n */\nexport interface LoadChatResponseData {\n chat: Chat;\n}\n\n/**\n * End chat options\n */\nexport interface EndChatApiOptions extends StreamApiOptions {\n /** Chat key to end */\n chatKey: string;\n /** Optional end reason */\n reason?: string;\n}\n\n/**\n * Typing indicator options\n */\nexport interface TypingApiOptions extends StreamApiOptions {\n /** Chat key */\n chatKey: string;\n /** Whether user is typing */\n typing: boolean;\n}\n\n/**\n * Generic event options\n */\nexport interface SendEventApiOptions extends StreamApiOptions {\n /** Chat key */\n chatKey: string;\n /** Event type */\n type: string;\n /** Event data */\n data?: Record<string, unknown>;\n}\n\n/**\n * Internal fetch helper\n */\nasync function streamFetch<T>(\n url: string,\n body: Record<string, unknown>\n): Promise<StreamApiResponse<T>> {\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n return {\n success: false,\n error: `API error: ${response.status} - ${errorText}`,\n };\n }\n\n const data = await response.json();\n return { success: true, data };\n}\n\n/**\n * Create a new chat session\n *\n * @param options - Create chat options\n * @returns Chat key of the created chat\n *\n * @example\n * ```typescript\n * const chatKey = await createChat({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * userId: \"user-456\",\n * metadata: { source: \"website\" },\n * });\n * ```\n */\nexport async function createChat(\n options: CreateChatApiOptions\n): Promise<string> {\n const { baseUrl, orgId, userId, metadata } = options;\n\n const result = await streamFetch<CreateChatResponseData>(\n `${baseUrl}/create`,\n { orgId, userId, metadata }\n );\n\n if (!result.success || !result.data?.chatKey) {\n throw new Error(result.error || \"Failed to create chat\");\n }\n\n return result.data.chatKey;\n}\n\n/**\n * Send a message in a chat\n *\n * @param options - Send message options\n *\n * @example\n * ```typescript\n * await sendChatMessage({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * content: \"Hello!\",\n * });\n * ```\n */\nexport async function sendChatMessage(\n options: SendMessageApiOptions\n): Promise<void> {\n const { baseUrl, orgId, chatKey, userId, content, attachments, metadata } =\n options;\n\n const message: Partial<ChatMessage> = {\n id: `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`,\n role: \"user\",\n content,\n time: Date.now(),\n status: \"sending\",\n senderId: userId,\n createdAt: Date.now(),\n attachments: attachments as ChatMessage[\"attachments\"],\n };\n\n const result = await streamFetch(`${baseUrl}/send`, {\n orgId,\n chatKey,\n userId,\n message,\n metadata,\n });\n\n if (!result.success) {\n throw new Error(result.error || \"Failed to send message\");\n }\n}\n\n/**\n * Load an existing chat\n *\n * @param options - Load chat options\n * @returns The loaded chat object\n *\n * @example\n * ```typescript\n * const chat = await loadChat({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * });\n * ```\n */\nexport async function loadChat(options: LoadChatApiOptions): Promise<Chat> {\n const { baseUrl, orgId, chatKey, userId } = options;\n\n const result = await streamFetch<LoadChatResponseData>(`${baseUrl}/load`, {\n orgId,\n chatKey,\n userId,\n });\n\n if (!result.success || !result.data?.chat) {\n throw new Error(result.error || \"Failed to load chat\");\n }\n\n return result.data.chat;\n}\n\n/**\n * End a chat session\n *\n * @param options - End chat options\n *\n * @example\n * ```typescript\n * await endChat({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * reason: \"User closed chat\",\n * });\n * ```\n */\nexport async function endChat(options: EndChatApiOptions): Promise<void> {\n const { baseUrl, orgId, chatKey, userId, reason } = options;\n\n const result = await streamFetch(`${baseUrl}/end`, {\n orgId,\n chatKey,\n userId,\n data: reason ? { reason } : undefined,\n });\n\n if (!result.success) {\n throw new Error(result.error || \"Failed to end chat\");\n }\n}\n\n/**\n * Send typing indicator\n *\n * @param options - Typing indicator options\n *\n * @example\n * ```typescript\n * // User started typing\n * await sendTypingIndicator({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * typing: true,\n * });\n *\n * // User stopped typing\n * await sendTypingIndicator({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * typing: false,\n * });\n * ```\n */\nexport async function sendTypingIndicator(\n options: TypingApiOptions\n): Promise<void> {\n const { baseUrl, orgId, chatKey, userId, typing } = options;\n\n const result = await streamFetch(`${baseUrl}/typing`, {\n orgId,\n chatKey,\n userId,\n typing,\n });\n\n if (!result.success) {\n throw new Error(result.error || \"Failed to send typing indicator\");\n }\n}\n\n/**\n * Send a generic event\n *\n * @param options - Event options\n *\n * @example\n * ```typescript\n * await sendEvent({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * type: \"skill_activate\",\n * data: { skillId: \"research\" },\n * });\n * ```\n */\nexport async function sendEvent(options: SendEventApiOptions): Promise<void> {\n const { baseUrl, orgId, chatKey, userId, type, data } = options;\n\n const result = await streamFetch(`${baseUrl}/event`, {\n type,\n orgId,\n chatKey,\n userId,\n data,\n });\n\n if (!result.success) {\n throw new Error(result.error || \"Failed to send event\");\n }\n}\n","import { browserApiRequest } from \"@elqnt/api-client/browser\";\nimport type { ApiClientOptions, ApiResponse } from \"@elqnt/api-client\";\nimport type { MemoryProfile } from \"../models\";\n\nexport interface SummaryView {\n chatKey: string;\n text: string;\n updatedAt: string;\n}\n\nexport const getProfileApi = (o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(\"/api/v1/memory/profile\", { method: \"GET\", ...o });\n\nexport const patchProfileApi = (patch: Partial<MemoryProfile>, o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(\"/api/v1/memory/profile\", { method: \"PATCH\", body: patch, ...o });\n\nexport const replaceProfileApi = (p: MemoryProfile, o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(\"/api/v1/memory/profile\", { method: \"PUT\", body: p, ...o });\n\nexport const clearProfileApi = (o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(\"/api/v1/memory/profile\", { method: \"DELETE\", ...o });\n\nexport const deleteContactApi = (name: string, o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(`/api/v1/memory/profile/contacts/${encodeURIComponent(name)}`, { method: \"DELETE\", ...o });\n\nexport const deleteNoteApi = (index: number, o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(`/api/v1/memory/profile/notes/${index}`, { method: \"DELETE\", ...o });\n\nexport const getSummaryApi = (chatKey: string, o: ApiClientOptions): Promise<ApiResponse<SummaryView>> =>\n browserApiRequest(`/api/v1/chats/${chatKey}/summary`, { method: \"GET\", ...o });\n\nexport const clearSummaryApi = (chatKey: string, o: ApiClientOptions): Promise<ApiResponse<void>> =>\n browserApiRequest(`/api/v1/chats/${chatKey}/summary`, { method: \"DELETE\", ...o });\n\nexport const regenerateSummaryApi = (chatKey: string, o: ApiClientOptions): Promise<ApiResponse<SummaryView>> =>\n browserApiRequest(`/api/v1/chats/${chatKey}/summary/regenerate`, { method: \"POST\", ...o });\n"],"mappings":";;;AAsBA,SAAS,qBAAAA,0BAAyB;;;AC6GlC,eAAe,YACb,KACA,MAC+B;AAC/B,QAAM,WAAW,MAAM,MAAM,KAAK;AAAA,IAChC,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAC9C,MAAM,KAAK,UAAU,IAAI;AAAA,EAC3B,CAAC;AAED,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,YAAY,MAAM,SAAS,KAAK;AACtC,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,cAAc,SAAS,MAAM,MAAM,SAAS;AAAA,IACrD;AAAA,EACF;AAEA,QAAM,OAAO,MAAM,SAAS,KAAK;AAC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C;AACH;AAMA,eAAsB,qBACpB,SAC8C;AAC9C,SAAOA,mBAAkB,kCAAkC;AAAA,IACzD,QAAQ;AAAA,IACR,GAAG;AAAA,EACL,CAAC;AACH;AAEA,eAAsB,mBACpB,SACA,SAC4C;AAC5C,SAAOA,mBAAkB,2BAA2B,OAAO,IAAI;AAAA,IAC7D,QAAQ;AAAA,IACR,GAAG;AAAA,EACL,CAAC;AACH;","names":["browserApiRequest","browserApiRequest"]}
|
|
1
|
+
{"version":3,"sources":["../../api/index.ts","../../api/stream-api.ts","../../api/memory.ts"],"sourcesContent":["/**\n * Chat API\n *\n * API functions for chat operations.\n *\n * ## Browser API (uses @elqnt/api-client)\n * ```typescript\n * import { getChatHistoryApi, getChatApi } from \"@elqnt/chat/api\";\n *\n * const history = await getChatHistoryApi({ baseUrl, orgId, limit: 10 });\n * const chat = await getChatApi(chatKey, { baseUrl, orgId });\n * ```\n *\n * ## Stream API (direct HTTP calls)\n * ```typescript\n * import { createChat, sendChatMessage, loadChat } from \"@elqnt/chat/api\";\n *\n * const chatKey = await createChat({ baseUrl, orgId, userId });\n * await sendChatMessage({ baseUrl, orgId, chatKey, userId, content: \"Hello!\" });\n * ```\n */\n\nimport { browserApiRequest } from \"@elqnt/api-client/browser\";\nimport type { ApiResponse, ApiClientOptions } from \"@elqnt/api-client\";\nimport type { ResponseMetadata } from \"@elqnt/types\";\nimport type { ChatSummary, Chat } from \"../models\";\n\n// Re-export types from models\nexport type { ChatSummary, Chat } from \"../models\";\n\n// Re-export stream API functions\nexport {\n createChat,\n sendChatMessage,\n loadChat,\n endChat,\n sendTypingIndicator,\n sendEvent,\n} from \"./stream-api\";\n\nexport type {\n StreamApiOptions,\n StreamApiResponse,\n CreateChatApiOptions,\n CreateChatResponseData,\n SendMessageApiOptions,\n LoadChatApiOptions,\n LoadChatResponseData,\n EndChatApiOptions,\n TypingApiOptions,\n SendEventApiOptions,\n} from \"./stream-api\";\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface ChatHistoryResponse {\n chats: ChatSummary[];\n total: number;\n hasMore: boolean;\n metadata: ResponseMetadata;\n}\n\nexport interface ChatResponse {\n chat: ChatSummary;\n metadata: ResponseMetadata;\n}\n\nexport interface UpdateChatResponse {\n chatKey: string;\n title: string;\n pinned: boolean;\n metadata: ResponseMetadata;\n}\n\nexport interface ActiveChatsResponse {\n chats: ChatSummary[];\n metadata: ResponseMetadata;\n}\n\nexport interface ActiveChatsCountResponse {\n count: number;\n metadata: ResponseMetadata;\n}\n\nexport interface WaitingChatsCountResponse {\n count: number;\n metadata: ResponseMetadata;\n}\n\nexport interface QueueResponse {\n queues: Queue[];\n metadata: ResponseMetadata;\n}\n\nexport interface Queue {\n id: string;\n name: string;\n agentId: string;\n waitingCount: number;\n activeCount: number;\n}\n\nexport interface AgentSession {\n agentId: string;\n userId: string;\n userEmail: string;\n status: string;\n connectedAt: string;\n lastActivityAt: string;\n}\n\nexport interface OnlineSessionsResponse {\n sessions: AgentSession[];\n metadata: ResponseMetadata;\n}\n\nexport interface AgentSessionResponse {\n session: AgentSession;\n metadata: ResponseMetadata;\n}\n\n// =============================================================================\n// CHAT HISTORY\n// =============================================================================\n\nexport async function getChatHistoryApi(\n options: ApiClientOptions & { limit?: number; offset?: number; skipCache?: boolean }\n): Promise<ApiResponse<ChatHistoryResponse>> {\n return browserApiRequest(\"/api/v1/chats\", {\n method: \"POST\",\n body: {\n limit: options.limit || 15,\n offset: options.offset || 0,\n ...(options.skipCache ? { skipCache: true } : {}),\n },\n ...options,\n });\n}\n\nexport async function getChatApi(\n chatKey: string,\n options: ApiClientOptions\n): Promise<ApiResponse<ChatResponse>> {\n return browserApiRequest(`/api/v1/chats/${chatKey}`, {\n method: \"GET\",\n ...options,\n });\n}\n\nexport async function updateChatApi(\n chatKey: string,\n updates: { title?: string; pinned?: boolean },\n options: ApiClientOptions\n): Promise<ApiResponse<UpdateChatResponse>> {\n return browserApiRequest(`/api/v1/chats/${chatKey}`, {\n method: \"PATCH\",\n body: updates,\n ...options,\n });\n}\n\nexport async function deleteChatApi(\n chatKey: string,\n options: ApiClientOptions\n): Promise<ApiResponse<{ success: boolean; metadata: ResponseMetadata }>> {\n return browserApiRequest(`/api/v1/chats/${chatKey}`, {\n method: \"DELETE\",\n ...options,\n });\n}\n\n// =============================================================================\n// ACTIVE CHATS\n// =============================================================================\n\nexport async function getActiveChatsCountApi(\n options: ApiClientOptions\n): Promise<ApiResponse<ActiveChatsCountResponse>> {\n return browserApiRequest(\"/api/v1/chats/active/count\", {\n method: \"GET\",\n ...options,\n });\n}\n\nexport async function getActiveChatsApi(\n options: ApiClientOptions & { pastHours?: number }\n): Promise<ApiResponse<ActiveChatsResponse>> {\n const params = new URLSearchParams();\n if (options.pastHours) params.set(\"pastHours\", String(options.pastHours));\n const queryString = params.toString();\n return browserApiRequest(`/api/v1/chats/active${queryString ? `?${queryString}` : \"\"}`, {\n method: \"GET\",\n ...options,\n });\n}\n\n// =============================================================================\n// PROJECT CHATS\n// =============================================================================\n\nexport async function updateProjectChatTitleApi(\n projectId: string,\n chatKey: string,\n title: string,\n options: ApiClientOptions\n): Promise<ApiResponse<{ success: boolean; metadata: ResponseMetadata }>> {\n return browserApiRequest(`/api/v1/projects/${projectId}/chats/${chatKey}/title`, {\n method: \"PUT\",\n body: { title },\n ...options,\n });\n}\n\nexport async function addChatToProjectApi(\n projectId: string,\n chatKey: string,\n options: ApiClientOptions\n): Promise<ApiResponse<{ success: boolean; metadata: ResponseMetadata }>> {\n return browserApiRequest(`/api/v1/projects/${projectId}/chats`, {\n method: \"POST\",\n body: { chatKey },\n ...options,\n });\n}\n\n// =============================================================================\n// WAITING CHATS\n// =============================================================================\n\nexport async function getWaitingChatsCountApi(\n options: ApiClientOptions\n): Promise<ApiResponse<WaitingChatsCountResponse>> {\n return browserApiRequest(\"/api/v1/chats/waiting/count\", {\n method: \"GET\",\n ...options,\n });\n}\n\nexport async function getChatsByUserApi(\n userEmail: string,\n options: ApiClientOptions\n): Promise<ApiResponse<ChatHistoryResponse>> {\n return browserApiRequest(`/api/v1/chats/user/${encodeURIComponent(userEmail)}`, {\n method: \"GET\",\n ...options,\n });\n}\n\n// =============================================================================\n// QUEUES\n// =============================================================================\n\nexport async function listQueuesApi(\n options: ApiClientOptions\n): Promise<ApiResponse<QueueResponse>> {\n return browserApiRequest(\"/api/v1/queues\", {\n method: \"GET\",\n ...options,\n });\n}\n\n// =============================================================================\n// AGENT SESSIONS\n// =============================================================================\n\nexport async function getOnlineSessionsApi(\n options: ApiClientOptions\n): Promise<ApiResponse<OnlineSessionsResponse>> {\n return browserApiRequest(\"/api/v1/agents/sessions/online\", {\n method: \"GET\",\n ...options,\n });\n}\n\nexport async function getAgentSessionApi(\n agentId: string,\n options: ApiClientOptions\n): Promise<ApiResponse<AgentSessionResponse>> {\n return browserApiRequest(`/api/v1/agents/sessions/${agentId}`, {\n method: \"GET\",\n ...options,\n });\n}\n\n// =============================================================================\n// MEMORY\n// =============================================================================\n\nexport {\n getProfileApi,\n patchProfileApi,\n replaceProfileApi,\n clearProfileApi,\n deleteContactApi,\n deleteNoteApi,\n getSummaryApi,\n clearSummaryApi,\n regenerateSummaryApi,\n} from \"./memory\";\n\nexport type { SummaryView } from \"./memory\";\n","/**\n * Stream API\n *\n * Low-level functions for chat streaming operations.\n * These are used internally by the transport layer but can also\n * be used directly for custom implementations.\n *\n * @example\n * ```typescript\n * import { createChat, sendChatMessage, loadChat } from \"@elqnt/chat/api\";\n *\n * // Create a new chat\n * const chatKey = await createChat({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * userId: \"user-456\",\n * });\n *\n * // Send a message\n * await sendChatMessage({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey,\n * userId: \"user-456\",\n * content: \"Hello!\",\n * });\n * ```\n */\n\nimport type { Chat, ChatMessage } from \"../models\";\n\n/**\n * Base options for all stream API calls\n */\nexport interface StreamApiOptions {\n /** Base URL for the chat server */\n baseUrl: string;\n /** Organization ID */\n orgId: string;\n /** User ID */\n userId: string;\n /**\n * Tier-2 signed token (REQUIRED in production). The chat service authorizes\n * the request from this token and derives orgId/userId/product from its\n * claims (the body orgId/userId are not trusted for authorization). Pass a\n * static `token`, or a `getToken` provider that is awaited per call so\n * short-lived tokens refresh. See SKILL.md and @elqnt/api-client/server's\n * generateServerToken for the claim shape.\n */\n token?: string;\n /** Token provider, awaited per call. Takes precedence over `token`. */\n getToken?: () => Promise<string | null | undefined> | string | null | undefined;\n}\n\n/** Resolve a per-call token from a static value or provider (never throws). */\nasync function resolveToken(opts: {\n token?: string;\n getToken?: StreamApiOptions[\"getToken\"];\n}): Promise<string | undefined> {\n if (opts.getToken) {\n try {\n return (await opts.getToken()) ?? undefined;\n } catch {\n return undefined;\n }\n }\n return opts.token ?? undefined;\n}\n\n/**\n * Response from stream API calls\n */\nexport interface StreamApiResponse<T = unknown> {\n success: boolean;\n data?: T;\n error?: string;\n}\n\n/**\n * Create chat options\n */\nexport interface CreateChatApiOptions extends StreamApiOptions {\n /** Optional metadata for the new chat */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Create chat response data\n */\nexport interface CreateChatResponseData {\n chatKey: string;\n}\n\n/**\n * Send message options\n */\nexport interface SendMessageApiOptions extends StreamApiOptions {\n /** Chat key */\n chatKey: string;\n /** Message content */\n content: string;\n /** Optional attachments */\n attachments?: unknown[];\n /** Optional message metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Load chat options\n */\nexport interface LoadChatApiOptions extends StreamApiOptions {\n /** Chat key to load */\n chatKey: string;\n}\n\n/**\n * Load chat response data\n */\nexport interface LoadChatResponseData {\n chat: Chat;\n}\n\n/**\n * End chat options\n */\nexport interface EndChatApiOptions extends StreamApiOptions {\n /** Chat key to end */\n chatKey: string;\n /** Optional end reason */\n reason?: string;\n}\n\n/**\n * Typing indicator options\n */\nexport interface TypingApiOptions extends StreamApiOptions {\n /** Chat key */\n chatKey: string;\n /** Whether user is typing */\n typing: boolean;\n}\n\n/**\n * Generic event options\n */\nexport interface SendEventApiOptions extends StreamApiOptions {\n /** Chat key */\n chatKey: string;\n /** Event type */\n type: string;\n /** Event data */\n data?: Record<string, unknown>;\n}\n\n/**\n * Internal fetch helper\n */\nasync function streamFetch<T>(\n url: string,\n body: Record<string, unknown>,\n token?: string\n): Promise<StreamApiResponse<T>> {\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n return {\n success: false,\n error: `API error: ${response.status} - ${errorText}`,\n };\n }\n\n const data = await response.json();\n return { success: true, data };\n}\n\n/**\n * Create a new chat session\n *\n * @param options - Create chat options\n * @returns Chat key of the created chat\n *\n * @example\n * ```typescript\n * const chatKey = await createChat({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * userId: \"user-456\",\n * metadata: { source: \"website\" },\n * });\n * ```\n */\nexport async function createChat(\n options: CreateChatApiOptions\n): Promise<string> {\n const { baseUrl, orgId, userId, metadata } = options;\n const token = await resolveToken(options);\n\n const result = await streamFetch<CreateChatResponseData>(\n `${baseUrl}/create`,\n { orgId, userId, metadata },\n token\n );\n\n if (!result.success || !result.data?.chatKey) {\n throw new Error(result.error || \"Failed to create chat\");\n }\n\n return result.data.chatKey;\n}\n\n/**\n * Send a message in a chat\n *\n * @param options - Send message options\n *\n * @example\n * ```typescript\n * await sendChatMessage({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * content: \"Hello!\",\n * });\n * ```\n */\nexport async function sendChatMessage(\n options: SendMessageApiOptions\n): Promise<void> {\n const { baseUrl, orgId, chatKey, userId, content, attachments, metadata } =\n options;\n const token = await resolveToken(options);\n\n const message: Partial<ChatMessage> = {\n id: `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`,\n role: \"user\",\n content,\n time: Date.now(),\n status: \"sending\",\n senderId: userId,\n createdAt: Date.now(),\n attachments: attachments as ChatMessage[\"attachments\"],\n };\n\n const result = await streamFetch(`${baseUrl}/send`, {\n orgId,\n chatKey,\n userId,\n message,\n metadata,\n }, token);\n\n if (!result.success) {\n throw new Error(result.error || \"Failed to send message\");\n }\n}\n\n/**\n * Load an existing chat\n *\n * @param options - Load chat options\n * @returns The loaded chat object\n *\n * @example\n * ```typescript\n * const chat = await loadChat({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * });\n * ```\n */\nexport async function loadChat(options: LoadChatApiOptions): Promise<Chat> {\n const { baseUrl, orgId, chatKey, userId } = options;\n const token = await resolveToken(options);\n\n const result = await streamFetch<LoadChatResponseData>(`${baseUrl}/load`, {\n orgId,\n chatKey,\n userId,\n }, token);\n\n if (!result.success || !result.data?.chat) {\n throw new Error(result.error || \"Failed to load chat\");\n }\n\n return result.data.chat;\n}\n\n/**\n * End a chat session\n *\n * @param options - End chat options\n *\n * @example\n * ```typescript\n * await endChat({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * reason: \"User closed chat\",\n * });\n * ```\n */\nexport async function endChat(options: EndChatApiOptions): Promise<void> {\n const { baseUrl, orgId, chatKey, userId, reason } = options;\n const token = await resolveToken(options);\n\n const result = await streamFetch(`${baseUrl}/end`, {\n orgId,\n chatKey,\n userId,\n data: reason ? { reason } : undefined,\n }, token);\n\n if (!result.success) {\n throw new Error(result.error || \"Failed to end chat\");\n }\n}\n\n/**\n * Send typing indicator\n *\n * @param options - Typing indicator options\n *\n * @example\n * ```typescript\n * // User started typing\n * await sendTypingIndicator({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * typing: true,\n * });\n *\n * // User stopped typing\n * await sendTypingIndicator({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * typing: false,\n * });\n * ```\n */\nexport async function sendTypingIndicator(\n options: TypingApiOptions\n): Promise<void> {\n const { baseUrl, orgId, chatKey, userId, typing } = options;\n const token = await resolveToken(options);\n\n const result = await streamFetch(`${baseUrl}/typing`, {\n orgId,\n chatKey,\n userId,\n typing,\n }, token);\n\n if (!result.success) {\n throw new Error(result.error || \"Failed to send typing indicator\");\n }\n}\n\n/**\n * Send a generic event\n *\n * @param options - Event options\n *\n * @example\n * ```typescript\n * await sendEvent({\n * baseUrl: \"https://api.example.com/chat\",\n * orgId: \"org-123\",\n * chatKey: \"chat-789\",\n * userId: \"user-456\",\n * type: \"skill_activate\",\n * data: { skillId: \"research\" },\n * });\n * ```\n */\nexport async function sendEvent(options: SendEventApiOptions): Promise<void> {\n const { baseUrl, orgId, chatKey, userId, type, data } = options;\n const token = await resolveToken(options);\n\n const result = await streamFetch(`${baseUrl}/event`, {\n type,\n orgId,\n chatKey,\n userId,\n data,\n }, token);\n\n if (!result.success) {\n throw new Error(result.error || \"Failed to send event\");\n }\n}\n","import { browserApiRequest } from \"@elqnt/api-client/browser\";\nimport type { ApiClientOptions, ApiResponse } from \"@elqnt/api-client\";\nimport type { MemoryProfile } from \"../models\";\n\nexport interface SummaryView {\n chatKey: string;\n text: string;\n updatedAt: string;\n}\n\nexport const getProfileApi = (o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(\"/api/v1/memory/profile\", { method: \"GET\", ...o });\n\nexport const patchProfileApi = (patch: Partial<MemoryProfile>, o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(\"/api/v1/memory/profile\", { method: \"PATCH\", body: patch, ...o });\n\nexport const replaceProfileApi = (p: MemoryProfile, o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(\"/api/v1/memory/profile\", { method: \"PUT\", body: p, ...o });\n\nexport const clearProfileApi = (o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(\"/api/v1/memory/profile\", { method: \"DELETE\", ...o });\n\nexport const deleteContactApi = (name: string, o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(`/api/v1/memory/profile/contacts/${encodeURIComponent(name)}`, { method: \"DELETE\", ...o });\n\nexport const deleteNoteApi = (index: number, o: ApiClientOptions): Promise<ApiResponse<MemoryProfile>> =>\n browserApiRequest(`/api/v1/memory/profile/notes/${index}`, { method: \"DELETE\", ...o });\n\nexport const getSummaryApi = (chatKey: string, o: ApiClientOptions): Promise<ApiResponse<SummaryView>> =>\n browserApiRequest(`/api/v1/chats/${chatKey}/summary`, { method: \"GET\", ...o });\n\nexport const clearSummaryApi = (chatKey: string, o: ApiClientOptions): Promise<ApiResponse<void>> =>\n browserApiRequest(`/api/v1/chats/${chatKey}/summary`, { method: \"DELETE\", ...o });\n\nexport const regenerateSummaryApi = (chatKey: string, o: ApiClientOptions): Promise<ApiResponse<SummaryView>> =>\n browserApiRequest(`/api/v1/chats/${chatKey}/summary/regenerate`, { method: \"POST\", ...o });\n"],"mappings":";AAsBA,SAAS,qBAAAA,0BAAyB;;;ACiClC,eAAe,aAAa,MAGI;AAC9B,MAAI,KAAK,UAAU;AACjB,QAAI;AACF,aAAQ,MAAM,KAAK,SAAS,KAAM;AAAA,IACpC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO,KAAK,SAAS;AACvB;AA0FA,eAAe,YACb,KACA,MACA,OAC+B;AAC/B,QAAM,UAAkC,EAAE,gBAAgB,mBAAmB;AAC7E,MAAI,MAAO,SAAQ,eAAe,IAAI,UAAU,KAAK;AAErD,QAAM,WAAW,MAAM,MAAM,KAAK;AAAA,IAChC,QAAQ;AAAA,IACR;AAAA,IACA,MAAM,KAAK,UAAU,IAAI;AAAA,EAC3B,CAAC;AAED,MAAI,CAAC,S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AAQ;AAAA,IACR,MAAM,EAAE,QAAQ;AAAA,IAChB,GAAG;AAAA,EACL,CAAC;AACH;AAMA,eAAsB,wBACpB,SACiD;AACjD,SAAOA,mBAAkB,+BAA+B;AAAA,IACtD,QAAQ;AAAA,IACR,GAAG;AAAA,EACL,CAAC;AACH;AAEA,eAAsB,kBACpB,WACA,SAC2C;AAC3C,SAAOA,mBAAkB,sBAAsB,mBAAmB,SAAS,CAAC,IAAI;AAAA,IAC9E,QAAQ;AAAA,IACR,GAAG;AAAA,EACL,CAAC;AACH;AAMA,eAAsB,cACpB,SACqC;AACrC,SAAOA,mBAAkB,kBAAkB;AAAA,IACzC,QAAQ;AAAA,IACR,GAAG;AAAA,EACL,CAAC;AACH;AAMA,eAAsB,qBACpB,SAC8C;AAC9C,SAAOA,mBAAkB,kCAAkC;AAAA,IACzD,QAAQ;AAAA,IACR,GAAG;AAAA,EACL,CAAC;AACH;AAEA,eAAsB,mBACpB,SACA,SAC4C;AAC5C,SAAOA,mBAAkB,2BAA2B,OAAO,IAAI;AAAA,IAC7D,QAAQ;AAAA,IACR,GAAG;AAAA,EACL,CAAC;AACH;","names":["browserApiRequest","browserApiRequest"]}
|
package/dist/hooks/index.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { UseAsyncOptions, UseAsyncReturn, useApiAsync } from '@elqnt/api-client/hooks';
|
|
2
1
|
import { ChatEvent, Chat, ChatMessage, ChatSummary, MemoryProfile } from '../models/index.mjs';
|
|
3
|
-
import { C as ChatTransport, e as TransportError, g as TransportState, R as RetryConfig, b as ConnectionMetrics, U as Unsubscribe } from '../types-
|
|
2
|
+
import { C as ChatTransport, e as TransportError, g as TransportState, R as RetryConfig, b as ConnectionMetrics, U as Unsubscribe } from '../types-CLtQA6Qq.mjs';
|
|
4
3
|
import { ApiClientOptions } from '@elqnt/api-client';
|
|
5
4
|
import { Queue, AgentSession, SummaryView } from '../api/index.mjs';
|
|
5
|
+
export { UseAsyncOptions, UseAsyncReturn, useApiAsync } from '@elqnt/api-client/hooks';
|
|
6
6
|
import '@elqnt/kg';
|
|
7
7
|
import '@elqnt/types';
|
|
8
8
|
import '@elqnt/docs';
|
|
@@ -33,6 +33,19 @@ interface UseChatOptions {
|
|
|
33
33
|
retryConfig?: RetryConfig;
|
|
34
34
|
/** Enable debug logging */
|
|
35
35
|
debug?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Tier-2 authorization (REQUIRED in production). Chat realtime reaches the
|
|
38
|
+
* chat service directly, bypassing the API gateway, so the service authorizes
|
|
39
|
+
* each connection from a signed token and derives orgId/userId/product from
|
|
40
|
+
* its claims. Provide `getToken` (preferred — awaited on every connect and
|
|
41
|
+
* REST send so short-lived tokens refresh over a long stream) or a static
|
|
42
|
+
* `token`. Mint it from a server route (e.g. /api/gateway-token or a
|
|
43
|
+
* dedicated chat-token route); the token's org/user MUST match this hook's
|
|
44
|
+
* orgId/userId. See packages/@elqnt/chat/SKILL.md.
|
|
45
|
+
*/
|
|
46
|
+
getToken?: () => Promise<string | null | undefined> | string | null | undefined;
|
|
47
|
+
/** Static signed token. Ignored when `getToken` is provided. */
|
|
48
|
+
token?: string;
|
|
36
49
|
}
|
|
37
50
|
/**
|
|
38
51
|
* Chat hook return type
|
|
@@ -89,41 +102,66 @@ interface ChatHistoryResult {
|
|
|
89
102
|
hasMore: boolean;
|
|
90
103
|
}
|
|
91
104
|
/**
|
|
92
|
-
*
|
|
105
|
+
* Return surface of {@link useChatHistory}.
|
|
93
106
|
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
* });
|
|
100
|
-
*
|
|
101
|
-
* const { chats, total, hasMore } = await getChatHistory({ limit: 20 });
|
|
102
|
-
* await deleteChat(chatKey);
|
|
103
|
-
* ```
|
|
107
|
+
* Every verb is an imperative `execute` from `useApiAsync`: you `await` it for
|
|
108
|
+
* data, and it resolves to its default (`{ chats: [], total: 0, hasMore: false }`,
|
|
109
|
+
* `null`, `false`, `[]`) on failure rather than throwing — inspect `error` /
|
|
110
|
+
* the result instead of try/catch. Unlike `useChat` (realtime, no bearer), these
|
|
111
|
+
* hit `/api/v1/chats**` through `@elqnt/api-client` with the gateway JWT.
|
|
104
112
|
*/
|
|
105
|
-
|
|
113
|
+
interface UseChatHistoryReturn {
|
|
114
|
+
/** True while any history verb is in flight. */
|
|
106
115
|
loading: boolean;
|
|
116
|
+
/** Last error from any history verb (string), or null. */
|
|
107
117
|
error: string | null;
|
|
118
|
+
/** List the caller's chats (paged). `POST /api/v1/chats`. */
|
|
108
119
|
getChatHistory: (params?: {
|
|
109
120
|
limit?: number;
|
|
110
121
|
offset?: number;
|
|
111
122
|
skipCache?: boolean;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
total: number;
|
|
115
|
-
hasMore: boolean;
|
|
116
|
-
}>;
|
|
123
|
+
}) => Promise<ChatHistoryResult>;
|
|
124
|
+
/** Fetch one chat summary by key. `GET /api/v1/chats/{chatKey}`. */
|
|
117
125
|
getChat: (chatKey: string) => Promise<ChatSummary | null>;
|
|
126
|
+
/** Rename / pin a chat. `PATCH /api/v1/chats/{chatKey}`. */
|
|
118
127
|
updateChat: (chatKey: string, updates: {
|
|
119
128
|
title?: string;
|
|
120
129
|
pinned?: boolean;
|
|
121
130
|
}) => Promise<boolean>;
|
|
131
|
+
/** Delete a chat. `DELETE /api/v1/chats/{chatKey}`. */
|
|
122
132
|
deleteChat: (chatKey: string) => Promise<boolean>;
|
|
133
|
+
/** List a user's chats by email. `GET /api/v1/chats/user/{email}`. */
|
|
123
134
|
getChatsByUser: (userEmail: string) => Promise<ChatSummary[]>;
|
|
124
|
-
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Hook for chat history CRUD operations
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```tsx
|
|
141
|
+
* const { loading, error, getChatHistory, deleteChat } = useChatHistory({
|
|
142
|
+
* baseUrl: apiGatewayUrl,
|
|
143
|
+
* orgId: selectedOrgId,
|
|
144
|
+
* });
|
|
145
|
+
*
|
|
146
|
+
* const { chats, total, hasMore } = await getChatHistory({ limit: 20 });
|
|
147
|
+
* await deleteChat(chatKey);
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
declare function useChatHistory(options: UseChatHistoryOptions): UseChatHistoryReturn;
|
|
125
151
|
|
|
126
152
|
type UseChatMonitoringOptions = ApiClientOptions;
|
|
153
|
+
/**
|
|
154
|
+
* The exact, stable return surface of `useChatMonitoring`. Imperative no-throw:
|
|
155
|
+
* each method resolves to a default on failure and sets `error`. See SKILL.md.
|
|
156
|
+
*/
|
|
157
|
+
interface UseChatMonitoringReturn {
|
|
158
|
+
loading: boolean;
|
|
159
|
+
error: string | null;
|
|
160
|
+
getActiveChats: (pastHours?: number) => Promise<ChatSummary[]>;
|
|
161
|
+
getActiveChatsCount: () => Promise<number>;
|
|
162
|
+
getWaitingChatsCount: () => Promise<number>;
|
|
163
|
+
listQueues: () => Promise<Queue[]>;
|
|
164
|
+
}
|
|
127
165
|
/**
|
|
128
166
|
* Hook for monitoring active/waiting chats and queues
|
|
129
167
|
*
|
|
@@ -138,16 +176,19 @@ type UseChatMonitoringOptions = ApiClientOptions;
|
|
|
138
176
|
* const waitingCount = await getWaitingChatsCount();
|
|
139
177
|
* ```
|
|
140
178
|
*/
|
|
141
|
-
declare function useChatMonitoring(options: UseChatMonitoringOptions):
|
|
142
|
-
loading: boolean;
|
|
143
|
-
error: string | null;
|
|
144
|
-
getActiveChats: (pastHours?: number | undefined) => Promise<ChatSummary[]>;
|
|
145
|
-
getActiveChatsCount: () => Promise<number>;
|
|
146
|
-
getWaitingChatsCount: () => Promise<number>;
|
|
147
|
-
listQueues: () => Promise<Queue[]>;
|
|
148
|
-
};
|
|
179
|
+
declare function useChatMonitoring(options: UseChatMonitoringOptions): UseChatMonitoringReturn;
|
|
149
180
|
|
|
150
181
|
type UseHumanAgentSessionsOptions = ApiClientOptions;
|
|
182
|
+
/**
|
|
183
|
+
* The exact, stable return surface of `useHumanAgentSessions`. Imperative
|
|
184
|
+
* no-throw: each method resolves to a default on failure and sets `error`.
|
|
185
|
+
*/
|
|
186
|
+
interface UseHumanAgentSessionsReturn {
|
|
187
|
+
loading: boolean;
|
|
188
|
+
error: string | null;
|
|
189
|
+
getOnlineSessions: () => Promise<AgentSession[]>;
|
|
190
|
+
getAgentSession: (agentId: string) => Promise<AgentSession | null>;
|
|
191
|
+
}
|
|
151
192
|
/**
|
|
152
193
|
* Hook for human agent session management
|
|
153
194
|
*
|
|
@@ -162,13 +203,10 @@ type UseHumanAgentSessionsOptions = ApiClientOptions;
|
|
|
162
203
|
* const session = await getAgentSession(agentId);
|
|
163
204
|
* ```
|
|
164
205
|
*/
|
|
165
|
-
declare function useHumanAgentSessions(options: UseHumanAgentSessionsOptions):
|
|
166
|
-
loading: boolean;
|
|
167
|
-
error: string | null;
|
|
168
|
-
getOnlineSessions: () => Promise<AgentSession[]>;
|
|
169
|
-
getAgentSession: (agentId: string) => Promise<AgentSession | null>;
|
|
170
|
-
};
|
|
206
|
+
declare function useHumanAgentSessions(options: UseHumanAgentSessionsOptions): UseHumanAgentSessionsReturn;
|
|
171
207
|
|
|
208
|
+
/** Canonical SDK name for the memory hook's return surface (alias of UseMemoryResult). */
|
|
209
|
+
type UseMemoryReturn = UseMemoryResult;
|
|
172
210
|
interface UseMemoryResult {
|
|
173
211
|
/** Current local copy of the user profile (null before first load/mutation) */
|
|
174
212
|
profile: MemoryProfile | null;
|
|
@@ -211,4 +249,4 @@ declare function useMemory(options: ApiClientOptions, initialProfile?: MemoryPro
|
|
|
211
249
|
*/
|
|
212
250
|
declare function useOptionsRef<T>(options: T): React.MutableRefObject<T>;
|
|
213
251
|
|
|
214
|
-
export { type ChatHistoryResult, type UseChatHistoryOptions, type UseChatMonitoringOptions, type UseChatOptions, type UseChatReturn, type UseHumanAgentSessionsOptions, type UseMemoryResult, useChat, useChatHistory, useChatMonitoring, useHumanAgentSessions, useMemory, useOptionsRef };
|
|
252
|
+
export { type ChatHistoryResult, type UseChatHistoryOptions, type UseChatHistoryReturn, type UseChatMonitoringOptions, type UseChatMonitoringReturn, type UseChatOptions, type UseChatReturn, type UseHumanAgentSessionsOptions, type UseHumanAgentSessionsReturn, type UseMemoryResult, type UseMemoryReturn, useChat, useChatHistory, useChatMonitoring, useHumanAgentSessions, useMemory, useOptionsRef };
|
package/dist/hooks/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { UseAsyncOptions, UseAsyncReturn, useApiAsync } from '@elqnt/api-client/hooks';
|
|
2
1
|
import { ChatEvent, Chat, ChatMessage, ChatSummary, MemoryProfile } from '../models/index.js';
|
|
3
|
-
import { C as ChatTransport, e as TransportError, g as TransportState, R as RetryConfig, b as ConnectionMetrics, U as Unsubscribe } from '../types-
|
|
2
|
+
import { C as ChatTransport, e as TransportError, g as TransportState, R as RetryConfig, b as ConnectionMetrics, U as Unsubscribe } from '../types-CxibhkqW.js';
|
|
4
3
|
import { ApiClientOptions } from '@elqnt/api-client';
|
|
5
4
|
import { Queue, AgentSession, SummaryView } from '../api/index.js';
|
|
5
|
+
export { UseAsyncOptions, UseAsyncReturn, useApiAsync } from '@elqnt/api-client/hooks';
|
|
6
6
|
import '@elqnt/kg';
|
|
7
7
|
import '@elqnt/types';
|
|
8
8
|
import '@elqnt/docs';
|
|
@@ -33,6 +33,19 @@ interface UseChatOptions {
|
|
|
33
33
|
retryConfig?: RetryConfig;
|
|
34
34
|
/** Enable debug logging */
|
|
35
35
|
debug?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Tier-2 authorization (REQUIRED in production). Chat realtime reaches the
|
|
38
|
+
* chat service directly, bypassing the API gateway, so the service authorizes
|
|
39
|
+
* each connection from a signed token and derives orgId/userId/product from
|
|
40
|
+
* its claims. Provide `getToken` (preferred — awaited on every connect and
|
|
41
|
+
* REST send so short-lived tokens refresh over a long stream) or a static
|
|
42
|
+
* `token`. Mint it from a server route (e.g. /api/gateway-token or a
|
|
43
|
+
* dedicated chat-token route); the token's org/user MUST match this hook's
|
|
44
|
+
* orgId/userId. See packages/@elqnt/chat/SKILL.md.
|
|
45
|
+
*/
|
|
46
|
+
getToken?: () => Promise<string | null | undefined> | string | null | undefined;
|
|
47
|
+
/** Static signed token. Ignored when `getToken` is provided. */
|
|
48
|
+
token?: string;
|
|
36
49
|
}
|
|
37
50
|
/**
|
|
38
51
|
* Chat hook return type
|
|
@@ -89,41 +102,66 @@ interface ChatHistoryResult {
|
|
|
89
102
|
hasMore: boolean;
|
|
90
103
|
}
|
|
91
104
|
/**
|
|
92
|
-
*
|
|
105
|
+
* Return surface of {@link useChatHistory}.
|
|
93
106
|
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
* });
|
|
100
|
-
*
|
|
101
|
-
* const { chats, total, hasMore } = await getChatHistory({ limit: 20 });
|
|
102
|
-
* await deleteChat(chatKey);
|
|
103
|
-
* ```
|
|
107
|
+
* Every verb is an imperative `execute` from `useApiAsync`: you `await` it for
|
|
108
|
+
* data, and it resolves to its default (`{ chats: [], total: 0, hasMore: false }`,
|
|
109
|
+
* `null`, `false`, `[]`) on failure rather than throwing — inspect `error` /
|
|
110
|
+
* the result instead of try/catch. Unlike `useChat` (realtime, no bearer), these
|
|
111
|
+
* hit `/api/v1/chats**` through `@elqnt/api-client` with the gateway JWT.
|
|
104
112
|
*/
|
|
105
|
-
|
|
113
|
+
interface UseChatHistoryReturn {
|
|
114
|
+
/** True while any history verb is in flight. */
|
|
106
115
|
loading: boolean;
|
|
116
|
+
/** Last error from any history verb (string), or null. */
|
|
107
117
|
error: string | null;
|
|
118
|
+
/** List the caller's chats (paged). `POST /api/v1/chats`. */
|
|
108
119
|
getChatHistory: (params?: {
|
|
109
120
|
limit?: number;
|
|
110
121
|
offset?: number;
|
|
111
122
|
skipCache?: boolean;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
total: number;
|
|
115
|
-
hasMore: boolean;
|
|
116
|
-
}>;
|
|
123
|
+
}) => Promise<ChatHistoryResult>;
|
|
124
|
+
/** Fetch one chat summary by key. `GET /api/v1/chats/{chatKey}`. */
|
|
117
125
|
getChat: (chatKey: string) => Promise<ChatSummary | null>;
|
|
126
|
+
/** Rename / pin a chat. `PATCH /api/v1/chats/{chatKey}`. */
|
|
118
127
|
updateChat: (chatKey: string, updates: {
|
|
119
128
|
title?: string;
|
|
120
129
|
pinned?: boolean;
|
|
121
130
|
}) => Promise<boolean>;
|
|
131
|
+
/** Delete a chat. `DELETE /api/v1/chats/{chatKey}`. */
|
|
122
132
|
deleteChat: (chatKey: string) => Promise<boolean>;
|
|
133
|
+
/** List a user's chats by email. `GET /api/v1/chats/user/{email}`. */
|
|
123
134
|
getChatsByUser: (userEmail: string) => Promise<ChatSummary[]>;
|
|
124
|
-
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Hook for chat history CRUD operations
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```tsx
|
|
141
|
+
* const { loading, error, getChatHistory, deleteChat } = useChatHistory({
|
|
142
|
+
* baseUrl: apiGatewayUrl,
|
|
143
|
+
* orgId: selectedOrgId,
|
|
144
|
+
* });
|
|
145
|
+
*
|
|
146
|
+
* const { chats, total, hasMore } = await getChatHistory({ limit: 20 });
|
|
147
|
+
* await deleteChat(chatKey);
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
declare function useChatHistory(options: UseChatHistoryOptions): UseChatHistoryReturn;
|
|
125
151
|
|
|
126
152
|
type UseChatMonitoringOptions = ApiClientOptions;
|
|
153
|
+
/**
|
|
154
|
+
* The exact, stable return surface of `useChatMonitoring`. Imperative no-throw:
|
|
155
|
+
* each method resolves to a default on failure and sets `error`. See SKILL.md.
|
|
156
|
+
*/
|
|
157
|
+
interface UseChatMonitoringReturn {
|
|
158
|
+
loading: boolean;
|
|
159
|
+
error: string | null;
|
|
160
|
+
getActiveChats: (pastHours?: number) => Promise<ChatSummary[]>;
|
|
161
|
+
getActiveChatsCount: () => Promise<number>;
|
|
162
|
+
getWaitingChatsCount: () => Promise<number>;
|
|
163
|
+
listQueues: () => Promise<Queue[]>;
|
|
164
|
+
}
|
|
127
165
|
/**
|
|
128
166
|
* Hook for monitoring active/waiting chats and queues
|
|
129
167
|
*
|
|
@@ -138,16 +176,19 @@ type UseChatMonitoringOptions = ApiClientOptions;
|
|
|
138
176
|
* const waitingCount = await getWaitingChatsCount();
|
|
139
177
|
* ```
|
|
140
178
|
*/
|
|
141
|
-
declare function useChatMonitoring(options: UseChatMonitoringOptions):
|
|
142
|
-
loading: boolean;
|
|
143
|
-
error: string | null;
|
|
144
|
-
getActiveChats: (pastHours?: number | undefined) => Promise<ChatSummary[]>;
|
|
145
|
-
getActiveChatsCount: () => Promise<number>;
|
|
146
|
-
getWaitingChatsCount: () => Promise<number>;
|
|
147
|
-
listQueues: () => Promise<Queue[]>;
|
|
148
|
-
};
|
|
179
|
+
declare function useChatMonitoring(options: UseChatMonitoringOptions): UseChatMonitoringReturn;
|
|
149
180
|
|
|
150
181
|
type UseHumanAgentSessionsOptions = ApiClientOptions;
|
|
182
|
+
/**
|
|
183
|
+
* The exact, stable return surface of `useHumanAgentSessions`. Imperative
|
|
184
|
+
* no-throw: each method resolves to a default on failure and sets `error`.
|
|
185
|
+
*/
|
|
186
|
+
interface UseHumanAgentSessionsReturn {
|
|
187
|
+
loading: boolean;
|
|
188
|
+
error: string | null;
|
|
189
|
+
getOnlineSessions: () => Promise<AgentSession[]>;
|
|
190
|
+
getAgentSession: (agentId: string) => Promise<AgentSession | null>;
|
|
191
|
+
}
|
|
151
192
|
/**
|
|
152
193
|
* Hook for human agent session management
|
|
153
194
|
*
|
|
@@ -162,13 +203,10 @@ type UseHumanAgentSessionsOptions = ApiClientOptions;
|
|
|
162
203
|
* const session = await getAgentSession(agentId);
|
|
163
204
|
* ```
|
|
164
205
|
*/
|
|
165
|
-
declare function useHumanAgentSessions(options: UseHumanAgentSessionsOptions):
|
|
166
|
-
loading: boolean;
|
|
167
|
-
error: string | null;
|
|
168
|
-
getOnlineSessions: () => Promise<AgentSession[]>;
|
|
169
|
-
getAgentSession: (agentId: string) => Promise<AgentSession | null>;
|
|
170
|
-
};
|
|
206
|
+
declare function useHumanAgentSessions(options: UseHumanAgentSessionsOptions): UseHumanAgentSessionsReturn;
|
|
171
207
|
|
|
208
|
+
/** Canonical SDK name for the memory hook's return surface (alias of UseMemoryResult). */
|
|
209
|
+
type UseMemoryReturn = UseMemoryResult;
|
|
172
210
|
interface UseMemoryResult {
|
|
173
211
|
/** Current local copy of the user profile (null before first load/mutation) */
|
|
174
212
|
profile: MemoryProfile | null;
|
|
@@ -211,4 +249,4 @@ declare function useMemory(options: ApiClientOptions, initialProfile?: MemoryPro
|
|
|
211
249
|
*/
|
|
212
250
|
declare function useOptionsRef<T>(options: T): React.MutableRefObject<T>;
|
|
213
251
|
|
|
214
|
-
export { type ChatHistoryResult, type UseChatHistoryOptions, type UseChatMonitoringOptions, type UseChatOptions, type UseChatReturn, type UseHumanAgentSessionsOptions, type UseMemoryResult, useChat, useChatHistory, useChatMonitoring, useHumanAgentSessions, useMemory, useOptionsRef };
|
|
252
|
+
export { type ChatHistoryResult, type UseChatHistoryOptions, type UseChatHistoryReturn, type UseChatMonitoringOptions, type UseChatMonitoringReturn, type UseChatOptions, type UseChatReturn, type UseHumanAgentSessionsOptions, type UseHumanAgentSessionsReturn, type UseMemoryResult, type UseMemoryReturn, useChat, useChatHistory, useChatMonitoring, useHumanAgentSessions, useMemory, useOptionsRef };
|
package/dist/hooks/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use client";
|
|
2
1
|
"use strict";
|
|
2
|
+
"use client";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
@@ -35,6 +35,18 @@ module.exports = __toCommonJS(hooks_exports);
|
|
|
35
35
|
var import_react = require("react");
|
|
36
36
|
|
|
37
37
|
// transport/types.ts
|
|
38
|
+
async function resolveTransportToken(cfg) {
|
|
39
|
+
if (!cfg) return void 0;
|
|
40
|
+
if (cfg.getToken) {
|
|
41
|
+
try {
|
|
42
|
+
const t = await cfg.getToken();
|
|
43
|
+
return t ?? void 0;
|
|
44
|
+
} catch {
|
|
45
|
+
return void 0;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return cfg.token ?? void 0;
|
|
49
|
+
}
|
|
38
50
|
function createLogger(debug = false) {
|
|
39
51
|
return {
|
|
40
52
|
debug: debug ? console.log.bind(console, "[chat]") : () => {
|
|
@@ -115,9 +127,12 @@ function createSSETransport(options = {}) {
|
|
|
115
127
|
}
|
|
116
128
|
const url = `${config.baseUrl}/${endpoint}`;
|
|
117
129
|
logger.debug(`POST ${endpoint}`, body);
|
|
130
|
+
const token = await resolveTransportToken(config);
|
|
131
|
+
const headers = { "Content-Type": "application/json" };
|
|
132
|
+
if (token) headers["Authorization"] = `Bearer ${token}`;
|
|
118
133
|
const response = await fetch(url, {
|
|
119
134
|
method: "POST",
|
|
120
|
-
headers
|
|
135
|
+
headers,
|
|
121
136
|
body: JSON.stringify(body)
|
|
122
137
|
});
|
|
123
138
|
if (!response.ok) {
|
|
@@ -244,6 +259,7 @@ function createSSETransport(options = {}) {
|
|
|
244
259
|
reconnectTimeout = void 0;
|
|
245
260
|
}
|
|
246
261
|
state = retryCount > 0 ? "reconnecting" : "connecting";
|
|
262
|
+
const connectToken = await resolveTransportToken(cfg);
|
|
247
263
|
return new Promise((resolve, reject) => {
|
|
248
264
|
const connectionStart = Date.now();
|
|
249
265
|
const streamParams = new URLSearchParams({
|
|
@@ -252,6 +268,7 @@ function createSSETransport(options = {}) {
|
|
|
252
268
|
clientType: cfg.clientType
|
|
253
269
|
});
|
|
254
270
|
if (cfg.chatKey) streamParams.set("chatId", cfg.chatKey);
|
|
271
|
+
if (connectToken) streamParams.set("token", connectToken);
|
|
255
272
|
const url = `${cfg.baseUrl}/stream?${streamParams.toString()}`;
|
|
256
273
|
logger.debug("Connecting to:", url);
|
|
257
274
|
const es = new EventSource(url);
|
|
@@ -505,9 +522,12 @@ function createFetchSSETransport(options = {}) {
|
|
|
505
522
|
}
|
|
506
523
|
const url = `${config.baseUrl}/${endpoint}`;
|
|
507
524
|
logger.debug(`POST ${endpoint}`, body);
|
|
525
|
+
const token = await resolveTransportToken(config);
|
|
526
|
+
const headers = { "Content-Type": "application/json" };
|
|
527
|
+
if (token) headers["Authorization"] = `Bearer ${token}`;
|
|
508
528
|
const response = await customFetch(url, {
|
|
509
529
|
method: "POST",
|
|
510
|
-
headers
|
|
530
|
+
headers,
|
|
511
531
|
body: JSON.stringify(body)
|
|
512
532
|
});
|
|
513
533
|
if (!response.ok) {
|
|
@@ -550,15 +570,19 @@ function createFetchSSETransport(options = {}) {
|
|
|
550
570
|
clientType: cfg.clientType
|
|
551
571
|
});
|
|
552
572
|
if (cfg.chatKey) streamParams.set("chatId", cfg.chatKey);
|
|
573
|
+
const token = await resolveTransportToken(cfg);
|
|
574
|
+
if (token) streamParams.set("token", token);
|
|
553
575
|
const url = `${cfg.baseUrl}/stream?${streamParams.toString()}`;
|
|
554
576
|
logger.debug("Connecting to:", url);
|
|
555
577
|
abortController = new AbortController();
|
|
578
|
+
const streamHeaders = {
|
|
579
|
+
Accept: "text/event-stream",
|
|
580
|
+
"Cache-Control": "no-cache"
|
|
581
|
+
};
|
|
582
|
+
if (token) streamHeaders["Authorization"] = `Bearer ${token}`;
|
|
556
583
|
const response = await customFetch(url, {
|
|
557
584
|
method: "GET",
|
|
558
|
-
headers:
|
|
559
|
-
Accept: "text/event-stream",
|
|
560
|
-
"Cache-Control": "no-cache"
|
|
561
|
-
},
|
|
585
|
+
headers: streamHeaders,
|
|
562
586
|
signal: abortController.signal
|
|
563
587
|
});
|
|
564
588
|
if (!response.ok) {
|
|
@@ -872,7 +896,9 @@ function useChat(options) {
|
|
|
872
896
|
onConnectionChange,
|
|
873
897
|
autoConnect = false,
|
|
874
898
|
retryConfig,
|
|
875
|
-
debug = false
|
|
899
|
+
debug = false,
|
|
900
|
+
token,
|
|
901
|
+
getToken
|
|
876
902
|
} = options;
|
|
877
903
|
const [connectionState, setConnectionState] = (0, import_react.useState)("disconnected");
|
|
878
904
|
const [currentChat, setCurrentChat] = (0, import_react.useState)(null);
|
|
@@ -891,10 +917,14 @@ function useChat(options) {
|
|
|
891
917
|
const onMessageRef = (0, import_react.useRef)(onMessage);
|
|
892
918
|
const onErrorRef = (0, import_react.useRef)(onError);
|
|
893
919
|
const typingTimeoutRef = (0, import_react.useRef)(null);
|
|
920
|
+
const getTokenRef = (0, import_react.useRef)(getToken);
|
|
921
|
+
const tokenRef = (0, import_react.useRef)(token);
|
|
894
922
|
(0, import_react.useEffect)(() => {
|
|
895
923
|
onMessageRef.current = onMessage;
|
|
896
924
|
onErrorRef.current = onError;
|
|
897
|
-
|
|
925
|
+
getTokenRef.current = getToken;
|
|
926
|
+
tokenRef.current = token;
|
|
927
|
+
}, [onMessage, onError, getToken, token]);
|
|
898
928
|
(0, import_react.useEffect)(() => {
|
|
899
929
|
if (typeof transportOption === "object") {
|
|
900
930
|
transportRef.current = transportOption;
|
|
@@ -977,7 +1007,10 @@ function useChat(options) {
|
|
|
977
1007
|
userId,
|
|
978
1008
|
clientType,
|
|
979
1009
|
chatKey: chatKey || void 0,
|
|
980
|
-
debug
|
|
1010
|
+
debug,
|
|
1011
|
+
// Always resolve via the ref so a long-lived/reconnecting stream picks
|
|
1012
|
+
// up a freshly-minted token rather than a stale captured one.
|
|
1013
|
+
getToken: () => getTokenRef.current ? getTokenRef.current() : tokenRef.current
|
|
981
1014
|
});
|
|
982
1015
|
setConnectionState("connected");
|
|
983
1016
|
setError(null);
|