@blockspark/chat-widget 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { jsxs, Fragment, jsx } from "react/jsx-runtime";
2
2
  import React, { useState, useEffect, useCallback, useRef } from "react";
3
- import { c as createChatService, l as linkifyText, a as createDialogflowSession, C as ChatResolvedError, s as sendDialogflowMessage } from "./sanitize-Cm1kskSD.js";
3
+ import { c as createChatService, l as linkifyText, a as createDialogflowSession, C as ChatResolvedError, s as sendDialogflowMessage } from "./sanitize-Q7JIm8H8.js";
4
4
  import require$$0 from "react-dom";
5
5
  const MODE_STORAGE_KEY = "chartsconnectect_chat_mode";
6
6
  const CHAT_ID_STORAGE_KEY = "chartsconnect_chat_id";
@@ -88,25 +88,19 @@ function ChatWidget$1({
88
88
  const [wsConnected, setWsConnected] = useState(false);
89
89
  const [agentTyping, setAgentTyping] = useState(false);
90
90
  const [currentAgent, setCurrentAgent] = useState({ name: "Agent" });
91
- const [collectingUserInfo, setCollectingUserInfo] = useState(false);
92
91
  const [chatResolved, setChatResolved] = useState(false);
93
92
  const [isStartingNewChat, setIsStartingNewChat] = useState(false);
94
93
  const [agentAccepted, setAgentAccepted] = useState(false);
95
- const [userInfoStep, setUserInfoStep] = useState(null);
96
- const [collectedUserName, setCollectedUserName] = useState("");
97
- const [collectedUserEmail, setCollectedUserEmail] = useState("");
98
- const [collectedUserMobile, setCollectedUserMobile] = useState("");
99
- const collectedUserNameRef = useRef("");
100
94
  const messagesEndRef = useRef(null);
101
95
  const typingTimeoutRef = useRef(null);
102
96
  const agentTypingTimeoutRef = useRef(null);
103
97
  const creatingSessionRef = useRef(false);
104
98
  const createSessionRef = useRef(null);
105
99
  const getBackendBaseUrl = () => {
106
- return backendBaseUrl || typeof process !== "undefined" && process.env?.REACT_APP_BACKEND_BASE_URL;
100
+ return backendBaseUrl || "https://chartconnect.blockspark.in";
107
101
  };
108
102
  const getBackendWsUrl = () => {
109
- return backendWsUrl || typeof process !== "undefined" && process.env?.REACT_APP_BACKEND_WS_URL;
103
+ return backendWsUrl || "wss://chartconnect.blockspark.in";
110
104
  };
111
105
  const chatServiceRef = useRef(
112
106
  createChatService({
@@ -150,12 +144,6 @@ function ChatWidget$1({
150
144
  switchToBotMode();
151
145
  setChatResolved(false);
152
146
  setMessages([]);
153
- setCollectingUserInfo(false);
154
- setUserInfoStep(null);
155
- setCollectedUserName("");
156
- setCollectedUserEmail("");
157
- setCollectedUserMobile("");
158
- collectedUserNameRef.current = "";
159
147
  if (createSessionRef.current) {
160
148
  createSessionRef.current().catch(console.error);
161
149
  }
@@ -168,14 +156,8 @@ function ChatWidget$1({
168
156
  if (isStartingNewChat) return;
169
157
  setIsStartingNewChat(true);
170
158
  try {
171
- const customerName = collectedUserNameRef.current || collectedUserName || null;
172
- const customerEmail = collectedUserEmail || null;
173
- const customerMobile = collectedUserMobile || null;
174
159
  const newSession = await chatServiceRef.current.startSupportChat(
175
- sessionId || null,
176
- customerName,
177
- customerEmail,
178
- customerMobile
160
+ sessionId || null
179
161
  );
180
162
  switchToHumanMode();
181
163
  setChatId(newSession.chat_id);
@@ -197,9 +179,6 @@ function ChatWidget$1({
197
179
  setIsStartingNewChat(false);
198
180
  }
199
181
  }, [
200
- collectedUserEmail,
201
- collectedUserMobile,
202
- collectedUserName,
203
182
  debug,
204
183
  isStartingNewChat,
205
184
  sessionId,
@@ -461,17 +440,14 @@ function ChatWidget$1({
461
440
  historyLoadedRef.current = null;
462
441
  }
463
442
  }, [currentMode, chatId, supportSessionId, loadMessageHistory, messages.length]);
464
- const handleHandoff = async (customerName, customerEmail, customerMobile) => {
443
+ const handleHandoff = async (webhookChatId, webhookSessionId) => {
465
444
  try {
466
445
  setIsConnectingToAgent(true);
467
446
  const dialogflowSessionId = sessionId;
468
- const session = await chatServiceRef.current.ensureChatInitialized(
447
+ const session = webhookChatId && webhookSessionId ? { chat_id: webhookChatId, session_id: webhookSessionId } : await chatServiceRef.current.ensureChatInitialized(
469
448
  chatId,
470
449
  supportSessionId,
471
- dialogflowSessionId || null,
472
- customerName || null,
473
- customerEmail || null,
474
- customerMobile || null
450
+ dialogflowSessionId || null
475
451
  );
476
452
  if (!session || !session.chat_id) {
477
453
  throw new Error("Failed to initialize chat session");
@@ -485,59 +461,54 @@ function ChatWidget$1({
485
461
  console.log("✅ Chat initialized:", { chatId: currentChatId, sessionId: currentSupportSessionId });
486
462
  }
487
463
  }
488
- try {
489
- await chatServiceRef.current.requestHandoff(
490
- currentChatId,
491
- currentSupportSessionId,
492
- "Customer requested human agent",
493
- dialogflowSessionId || null,
494
- customerName || null,
495
- customerEmail || null,
496
- customerMobile || null
497
- );
498
- if (debug) {
499
- console.log("✅ Handoff requested successfully");
500
- }
501
- } catch (handoffError) {
502
- if (handoffError.message?.includes("Invalid chat_id") || handoffError.message?.includes("Chat not found") || handoffError.message?.includes("unauthorized") || handoffError.message?.includes("400") || handoffError.message?.includes("401") || handoffError.message?.includes("404") || handoffError.message?.includes("expired")) {
503
- if (debug) {
504
- console.log("⚠️ Chat expired or not found. Re-initializing chat...");
505
- }
506
- setChatId(null);
507
- setSupportSessionId(null);
508
- const newSession = await chatServiceRef.current.startSupportChat(
509
- dialogflowSessionId || null,
510
- customerName || null,
511
- customerEmail || null,
512
- customerMobile || null
513
- );
514
- if (!newSession || !newSession.chat_id) {
515
- throw new Error("Failed to re-initialize chat session");
516
- }
517
- const newChatId = newSession.chat_id;
518
- const newSessionId = newSession.session_id;
519
- setChatId(newChatId);
520
- setSupportSessionId(newSessionId);
464
+ if (!webhookChatId) {
465
+ try {
521
466
  await chatServiceRef.current.requestHandoff(
522
- newChatId,
523
- newSessionId,
467
+ currentChatId,
468
+ currentSupportSessionId,
524
469
  "Customer requested human agent",
525
- dialogflowSessionId || null,
526
- customerName || null,
527
- customerEmail || null,
528
- customerMobile || null
470
+ dialogflowSessionId || null
529
471
  );
530
472
  if (debug) {
531
- console.log("✅ Handoff requested successfully after retry");
473
+ console.log("✅ Handoff requested successfully");
532
474
  }
533
- const newSessionKey = `${newChatId}-${newSessionId}`;
534
- if (historyLoadedRef.current !== newSessionKey) {
535
- historyLoadedRef.current = newSessionKey;
536
- await loadMessageHistory(true);
475
+ } catch (handoffError) {
476
+ if (handoffError.message?.includes("Invalid chat_id") || handoffError.message?.includes("Chat not found") || handoffError.message?.includes("unauthorized") || handoffError.message?.includes("400") || handoffError.message?.includes("401") || handoffError.message?.includes("404") || handoffError.message?.includes("expired")) {
477
+ if (debug) {
478
+ console.log("⚠️ Chat expired or not found. Re-initializing chat...");
479
+ }
480
+ setChatId(null);
481
+ setSupportSessionId(null);
482
+ const newSession = await chatServiceRef.current.startSupportChat(
483
+ dialogflowSessionId || null
484
+ );
485
+ if (!newSession || !newSession.chat_id) {
486
+ throw new Error("Failed to re-initialize chat session");
487
+ }
488
+ const newChatId = newSession.chat_id;
489
+ const newSessionId = newSession.session_id;
490
+ setChatId(newChatId);
491
+ setSupportSessionId(newSessionId);
492
+ await chatServiceRef.current.requestHandoff(
493
+ newChatId,
494
+ newSessionId,
495
+ "Customer requested human agent",
496
+ dialogflowSessionId || null
497
+ );
498
+ if (debug) {
499
+ console.log("✅ Handoff requested successfully after retry");
500
+ }
501
+ const newSessionKey = `${newChatId}-${newSessionId}`;
502
+ if (historyLoadedRef.current !== newSessionKey) {
503
+ historyLoadedRef.current = newSessionKey;
504
+ await loadMessageHistory(true);
505
+ }
506
+ } else {
507
+ throw handoffError;
537
508
  }
538
- } else {
539
- throw handoffError;
540
509
  }
510
+ } else if (debug) {
511
+ console.log("✅ Using webhook-created chat, skipping requestHandoff");
541
512
  }
542
513
  switchToHumanMode();
543
514
  setChatResolved(false);
@@ -625,92 +596,6 @@ function ChatWidget$1({
625
596
  createSessionRef.current = createSession;
626
597
  const sendMessage = async (text, displayText, skipUserMessage = false) => {
627
598
  if (!text.trim()) return;
628
- if (collectingUserInfo) {
629
- if (userInfoStep === "name") {
630
- const name = text.trim();
631
- setCollectedUserName(name);
632
- collectedUserNameRef.current = name;
633
- setUserInfoStep("email");
634
- const userMessage = {
635
- id: Date.now().toString(),
636
- text: name,
637
- sender: "user",
638
- timestamp: /* @__PURE__ */ new Date()
639
- };
640
- setMessages((prev) => [...prev, userMessage]);
641
- const emailPrompt = {
642
- id: (Date.now() + 1).toString(),
643
- text: "Thank you! Now please provide your email address:",
644
- sender: "bot",
645
- timestamp: /* @__PURE__ */ new Date()
646
- };
647
- setMessages((prev) => [...prev, emailPrompt]);
648
- setInputValue("");
649
- return;
650
- } else if (userInfoStep === "email") {
651
- const email = text.trim();
652
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
653
- if (!emailRegex.test(email)) {
654
- const invalidEmailMessage = {
655
- id: (Date.now() + 1).toString(),
656
- text: "Please provide a valid email address:",
657
- sender: "bot",
658
- timestamp: /* @__PURE__ */ new Date()
659
- };
660
- setMessages((prev) => [...prev, invalidEmailMessage]);
661
- setInputValue("");
662
- return;
663
- }
664
- setCollectedUserEmail(email);
665
- setUserInfoStep("mobile");
666
- const userMessage = {
667
- id: Date.now().toString(),
668
- text: email,
669
- sender: "user",
670
- timestamp: /* @__PURE__ */ new Date()
671
- };
672
- setMessages((prev) => [...prev, userMessage]);
673
- const mobilePrompt = {
674
- id: (Date.now() + 1).toString(),
675
- text: "Thank you! Now please provide your mobile number:",
676
- sender: "bot",
677
- timestamp: /* @__PURE__ */ new Date()
678
- };
679
- setMessages((prev) => [...prev, mobilePrompt]);
680
- setInputValue("");
681
- return;
682
- } else if (userInfoStep === "mobile") {
683
- const mobile = text.trim();
684
- const mobileRegex = /^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/;
685
- if (!mobileRegex.test(mobile) || mobile.length < 10) {
686
- const invalidMobileMessage = {
687
- id: (Date.now() + 1).toString(),
688
- text: "Please provide a valid mobile number (e.g., +1234567890):",
689
- sender: "bot",
690
- timestamp: /* @__PURE__ */ new Date()
691
- };
692
- setMessages((prev) => [...prev, invalidMobileMessage]);
693
- setInputValue("");
694
- return;
695
- }
696
- setCollectedUserMobile(mobile);
697
- const userMessage = {
698
- id: Date.now().toString(),
699
- text: mobile,
700
- sender: "user",
701
- timestamp: /* @__PURE__ */ new Date()
702
- };
703
- setMessages((prev) => [...prev, userMessage]);
704
- const userName = collectedUserNameRef.current;
705
- const userEmail = collectedUserEmail;
706
- setCollectingUserInfo(false);
707
- setUserInfoStep(null);
708
- collectedUserNameRef.current = "";
709
- await handleHandoff(userName, userEmail, mobile);
710
- setInputValue("");
711
- return;
712
- }
713
- }
714
599
  if (currentMode === "HUMAN") {
715
600
  if (!chatId || !supportSessionId) {
716
601
  const errorMessage = {
@@ -757,10 +642,7 @@ function ChatWidget$1({
757
642
  setSupportSessionId(null);
758
643
  try {
759
644
  const newSession = await chatServiceRef.current.startSupportChat(
760
- sessionId || null,
761
- null,
762
- null,
763
- null
645
+ sessionId || null
764
646
  );
765
647
  setChatId(newSession.chat_id);
766
648
  setSupportSessionId(newSession.session_id);
@@ -854,36 +736,29 @@ function ChatWidget$1({
854
736
  console.log("Handoff detected:", data.handoff);
855
737
  }
856
738
  if (data.handoff === true) {
857
- const botMessage2 = {
739
+ if (data.response || data.richContent) {
740
+ const botMessage = {
741
+ id: (Date.now() + 1).toString(),
742
+ text: data.response,
743
+ sender: "bot",
744
+ timestamp: new Date(data.timestamp || Date.now()),
745
+ richContent: data.richContent
746
+ };
747
+ setMessages((prev) => [...prev, botMessage]);
748
+ }
749
+ await handleHandoff(data.chat_id, data.support_session_id);
750
+ return;
751
+ }
752
+ if (data.response || data.richContent) {
753
+ const botMessage = {
858
754
  id: (Date.now() + 1).toString(),
859
755
  text: data.response,
860
756
  sender: "bot",
861
757
  timestamp: new Date(data.timestamp || Date.now()),
862
758
  richContent: data.richContent
863
759
  };
864
- setMessages((prev) => [...prev, botMessage2]);
865
- setCollectingUserInfo(true);
866
- setUserInfoStep("name");
867
- setCollectedUserName("");
868
- setCollectedUserEmail("");
869
- collectedUserNameRef.current = "";
870
- const namePrompt = {
871
- id: (Date.now() + 2).toString(),
872
- text: "To connect you with a human agent, I'll need some information. Please provide your name:",
873
- sender: "bot",
874
- timestamp: /* @__PURE__ */ new Date()
875
- };
876
- setMessages((prev) => [...prev, namePrompt]);
877
- return;
760
+ setMessages((prev) => [...prev, botMessage]);
878
761
  }
879
- const botMessage = {
880
- id: (Date.now() + 1).toString(),
881
- text: data.response,
882
- sender: "bot",
883
- timestamp: new Date(data.timestamp || Date.now()),
884
- richContent: data.richContent
885
- };
886
- setMessages((prev) => [...prev, botMessage]);
887
762
  } catch (error) {
888
763
  console.error("Error sending message:", error);
889
764
  if (debug) {