@elqnt/chat 3.1.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.
@@ -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: { "Content-Type": "application/json" },
135
+ headers,
121
136
  body: JSON.stringify(body)
122
137
  });
123
138
  if (!response.ok) {
@@ -143,6 +158,7 @@ function createSSETransport(options = {}) {
143
158
  function setupEventListeners(es) {
144
159
  es.addEventListener("message", handleMessage);
145
160
  const eventTypes = [
161
+ "error",
146
162
  "reconnected",
147
163
  "typing",
148
164
  "stopped_typing",
@@ -152,21 +168,53 @@ function createSSETransport(options = {}) {
152
168
  "human_agent_left",
153
169
  "chat_ended",
154
170
  "chat_updated",
171
+ "chat_removed",
155
172
  "load_chat_response",
156
173
  "new_chat_created",
157
174
  "show_csat_survey",
158
175
  "csat_response",
159
176
  "user_suggested_actions",
177
+ "user_suggested_action_selected",
160
178
  "agent_execution_started",
161
179
  "agent_execution_ended",
162
180
  "agent_context_update",
181
+ "load_agent_context_response",
163
182
  "plan_pending_approval",
183
+ "plan_approved",
184
+ "plan_rejected",
164
185
  "step_started",
165
186
  "step_completed",
166
187
  "step_failed",
167
188
  "plan_completed",
168
189
  "skills_changed",
169
- "summary_update"
190
+ "summary_update",
191
+ "message_status_update",
192
+ "delivered",
193
+ "read",
194
+ "sync_metadata_response",
195
+ "sync_user_session_response",
196
+ "client_action",
197
+ "client_action_callback",
198
+ "attachment_processing_started",
199
+ "attachment_processing_progress",
200
+ "attachment_processing_complete",
201
+ "attachment_processing_error",
202
+ "observer_joined",
203
+ "observer_left",
204
+ "block_user",
205
+ "message_edited",
206
+ "message_deleted",
207
+ "message_reaction",
208
+ "user_presence_changed",
209
+ "online_users",
210
+ "get_agents_response",
211
+ "room_created",
212
+ "room_updated",
213
+ "room_deleted",
214
+ "rooms_response",
215
+ "room_user_joined",
216
+ "room_user_left",
217
+ "user_invited"
170
218
  ];
171
219
  eventTypes.forEach((type) => {
172
220
  es.addEventListener(type, handleMessage);
@@ -211,20 +259,38 @@ function createSSETransport(options = {}) {
211
259
  reconnectTimeout = void 0;
212
260
  }
213
261
  state = retryCount > 0 ? "reconnecting" : "connecting";
262
+ const connectToken = await resolveTransportToken(cfg);
214
263
  return new Promise((resolve, reject) => {
215
264
  const connectionStart = Date.now();
216
- const url = `${cfg.baseUrl}/stream?orgId=${cfg.orgId}&userId=${cfg.userId}&clientType=${cfg.clientType}${cfg.chatKey ? `&chatId=${cfg.chatKey}` : ""}`;
265
+ const streamParams = new URLSearchParams({
266
+ orgId: cfg.orgId,
267
+ userId: cfg.userId,
268
+ clientType: cfg.clientType
269
+ });
270
+ if (cfg.chatKey) streamParams.set("chatId", cfg.chatKey);
271
+ if (connectToken) streamParams.set("token", connectToken);
272
+ const url = `${cfg.baseUrl}/stream?${streamParams.toString()}`;
217
273
  logger.debug("Connecting to:", url);
218
274
  const es = new EventSource(url);
219
275
  es.onopen = () => {
220
276
  const connectionTime = Date.now() - connectionStart;
221
277
  logger.info(`Connected in ${connectionTime}ms`);
278
+ const wasReconnect = retryCount > 0;
222
279
  state = "connected";
223
280
  error = void 0;
224
281
  retryCount = 0;
225
282
  metrics.connectedAt = Date.now();
226
283
  metrics.latency = connectionTime;
227
284
  setupEventListeners(es);
285
+ if (wasReconnect) {
286
+ emit({
287
+ type: "transport_reconnected",
288
+ orgId: cfg.orgId,
289
+ chatKey: cfg.chatKey || "",
290
+ userId: cfg.userId,
291
+ timestamp: Date.now()
292
+ });
293
+ }
228
294
  resolve();
229
295
  };
230
296
  es.onerror = () => {
@@ -456,9 +522,12 @@ function createFetchSSETransport(options = {}) {
456
522
  }
457
523
  const url = `${config.baseUrl}/${endpoint}`;
458
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}`;
459
528
  const response = await customFetch(url, {
460
529
  method: "POST",
461
- headers: { "Content-Type": "application/json" },
530
+ headers,
462
531
  body: JSON.stringify(body)
463
532
  });
464
533
  if (!response.ok) {
@@ -495,15 +564,25 @@ function createFetchSSETransport(options = {}) {
495
564
  return events;
496
565
  }
497
566
  async function startStream(cfg) {
498
- const url = `${cfg.baseUrl}/stream?orgId=${cfg.orgId}&userId=${cfg.userId}&clientType=${cfg.clientType}${cfg.chatKey ? `&chatId=${cfg.chatKey}` : ""}`;
567
+ const streamParams = new URLSearchParams({
568
+ orgId: cfg.orgId,
569
+ userId: cfg.userId,
570
+ clientType: cfg.clientType
571
+ });
572
+ if (cfg.chatKey) streamParams.set("chatId", cfg.chatKey);
573
+ const token = await resolveTransportToken(cfg);
574
+ if (token) streamParams.set("token", token);
575
+ const url = `${cfg.baseUrl}/stream?${streamParams.toString()}`;
499
576
  logger.debug("Connecting to:", url);
500
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}`;
501
583
  const response = await customFetch(url, {
502
584
  method: "GET",
503
- headers: {
504
- Accept: "text/event-stream",
505
- "Cache-Control": "no-cache"
506
- },
585
+ headers: streamHeaders,
507
586
  signal: abortController.signal
508
587
  });
509
588
  if (!response.ok) {
@@ -601,6 +680,7 @@ function createFetchSSETransport(options = {}) {
601
680
  state = retryCount > 0 ? "reconnecting" : "connecting";
602
681
  const connectionStart = Date.now();
603
682
  try {
683
+ const wasReconnect = retryCount > 0;
604
684
  await startStream(cfg);
605
685
  const connectionTime = Date.now() - connectionStart;
606
686
  logger.info(`Connected in ${connectionTime}ms`);
@@ -609,6 +689,15 @@ function createFetchSSETransport(options = {}) {
609
689
  retryCount = 0;
610
690
  metrics.connectedAt = Date.now();
611
691
  metrics.latency = connectionTime;
692
+ if (wasReconnect) {
693
+ emit({
694
+ type: "transport_reconnected",
695
+ orgId: cfg.orgId,
696
+ chatKey: cfg.chatKey || "",
697
+ userId: cfg.userId,
698
+ timestamp: Date.now()
699
+ });
700
+ }
612
701
  } catch (err) {
613
702
  const connectError = {
614
703
  code: "CONNECTION_FAILED",
@@ -650,7 +739,8 @@ function createFetchSSETransport(options = {}) {
650
739
  orgId: event.orgId,
651
740
  chatKey: event.chatKey,
652
741
  userId: event.userId,
653
- message: event.message
742
+ message: event.message,
743
+ ...event.data ? { data: event.data } : {}
654
744
  });
655
745
  break;
656
746
  case "typing":
@@ -806,7 +896,9 @@ function useChat(options) {
806
896
  onConnectionChange,
807
897
  autoConnect = false,
808
898
  retryConfig,
809
- debug = false
899
+ debug = false,
900
+ token,
901
+ getToken
810
902
  } = options;
811
903
  const [connectionState, setConnectionState] = (0, import_react.useState)("disconnected");
812
904
  const [currentChat, setCurrentChat] = (0, import_react.useState)(null);
@@ -825,10 +917,14 @@ function useChat(options) {
825
917
  const onMessageRef = (0, import_react.useRef)(onMessage);
826
918
  const onErrorRef = (0, import_react.useRef)(onError);
827
919
  const typingTimeoutRef = (0, import_react.useRef)(null);
920
+ const getTokenRef = (0, import_react.useRef)(getToken);
921
+ const tokenRef = (0, import_react.useRef)(token);
828
922
  (0, import_react.useEffect)(() => {
829
923
  onMessageRef.current = onMessage;
830
924
  onErrorRef.current = onError;
831
- }, [onMessage, onError]);
925
+ getTokenRef.current = getToken;
926
+ tokenRef.current = token;
927
+ }, [onMessage, onError, getToken, token]);
832
928
  (0, import_react.useEffect)(() => {
833
929
  if (typeof transportOption === "object") {
834
930
  transportRef.current = transportOption;
@@ -911,7 +1007,10 @@ function useChat(options) {
911
1007
  userId,
912
1008
  clientType,
913
1009
  chatKey: chatKey || void 0,
914
- 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
915
1014
  });
916
1015
  setConnectionState("connected");
917
1016
  setError(null);
@@ -970,7 +1069,7 @@ function useChat(options) {
970
1069
  [orgId, userId]
971
1070
  );
972
1071
  const sendMessage = (0, import_react.useCallback)(
973
- async (content, attachments) => {
1072
+ async (content, attachments, data) => {
974
1073
  const transport = transportRef.current;
975
1074
  if (!transport) {
976
1075
  throw new Error("Transport not initialized");
@@ -995,7 +1094,8 @@ function useChat(options) {
995
1094
  chatKey,
996
1095
  userId,
997
1096
  timestamp: Date.now(),
998
- message
1097
+ message,
1098
+ ...data ? { data } : {}
999
1099
  });
1000
1100
  setMetrics((prev) => ({
1001
1101
  ...prev,