@opencx/widget 2.6.0 → 2.6.2

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 (102) hide show
  1. package/dist/api-BEtFfKMB.cjs +2 -0
  2. package/dist/api-BEtFfKMB.cjs.map +1 -0
  3. package/dist/api-Cez5T-se.js +1393 -0
  4. package/dist/api-Cez5T-se.js.map +1 -0
  5. package/dist/basic.cjs +85 -85
  6. package/dist/basic.cjs.map +1 -1
  7. package/dist/basic.js +13159 -12639
  8. package/dist/basic.js.map +1 -1
  9. package/dist/core/client/api.d.ts +414 -40
  10. package/dist/core/client/chat.d.ts +33 -19
  11. package/dist/core/client/config.d.ts +13 -3
  12. package/dist/core/client/contact.d.ts +9 -13
  13. package/dist/core/client/index.d.ts +1 -1
  14. package/dist/core/index.d.ts +1 -1
  15. package/dist/core/sdk/index.d.ts +11 -0
  16. package/dist/core/types/contact.d.ts +2 -0
  17. package/dist/core/types/helpers.d.ts +5 -2
  18. package/dist/core/types/index.d.ts +6 -6
  19. package/dist/core/types/messages.d.ts +20 -9
  20. package/dist/core/types/schemas-v2.d.ts +10 -713
  21. package/dist/index-BzidnDPX.cjs +18 -0
  22. package/dist/index-BzidnDPX.cjs.map +1 -0
  23. package/dist/index-DUlnC30_.js +1219 -0
  24. package/dist/index-DUlnC30_.js.map +1 -0
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.js +22 -1071
  28. package/dist/index.js.map +1 -1
  29. package/dist/react-web/core-integration/ChatProvider.d.ts +107 -0
  30. package/dist/react-web/core-integration/components.d.ts +11 -0
  31. package/dist/react-web/core-integration/hooks/useChatMessages.d.ts +70 -0
  32. package/dist/react-web/core-integration/hooks/useChatSession.d.ts +83 -0
  33. package/dist/react-web/core-integration/hooks/useConfig.d.ts +1 -0
  34. package/dist/react-web/core-integration/hooks/useContact.d.ts +17 -0
  35. package/dist/react-web/core-integration/hooks/useLocale.d.ts +4 -0
  36. package/dist/react-web/core-integration/hooks/usePreludeData.d.ts +36 -0
  37. package/dist/react-web/core-integration/hooks/usePubsub.d.ts +2 -0
  38. package/dist/react-web/{hooks → core-integration/hooks}/useUploadFiles.d.ts +2 -2
  39. package/dist/react-web/{hooks → core-integration/hooks}/useVote.d.ts +2 -2
  40. package/dist/react-web/core-integration/hooks.d.ts +9 -0
  41. package/dist/react-web/core-integration/index.d.ts +2 -0
  42. package/dist/react-web/index.d.ts +4 -10
  43. package/dist/react-web/types/components.d.ts +6 -3
  44. package/dist/react-web/types/index.d.ts +3 -2
  45. package/dist/react-web/types/options.d.ts +4 -30
  46. package/dist/react.cjs +1 -1
  47. package/dist/react.cjs.map +1 -1
  48. package/dist/react.js +10 -46
  49. package/dist/react.js.map +1 -1
  50. package/dist/src/@components/BotOrAgentMessageGroup.d.ts +1 -2
  51. package/dist/src/@components/BotOrAgentMessageWrapper.d.ts +2 -2
  52. package/dist/src/@components/ChatEvent.component.d.ts +3 -3
  53. package/dist/src/@components/Text.component.d.ts +1 -1
  54. package/dist/src/components/button.d.ts +1 -1
  55. package/dist/src/components/dialog.d.ts +9 -9
  56. package/dist/src/designs/basic/index.d.ts +1 -1
  57. package/dist/style.css +1 -1
  58. package/dist-embed/script.js +119 -124
  59. package/dist-embed/script.js.map +1 -1
  60. package/package.json +7 -4
  61. package/dist/core/tests/utils/create-fetch.test.d.ts +0 -1
  62. package/dist/core/types/schemas.d.ts +0 -543
  63. package/dist/core/utils/create-fetch.d.ts +0 -25
  64. package/dist/core/utils/genId.d.ts +0 -2
  65. package/dist/core/utils/history-to-widget-messages.d.ts +0 -4
  66. package/dist/genUuid-C12yFv3j.js +0 -137
  67. package/dist/genUuid-C12yFv3j.js.map +0 -1
  68. package/dist/genUuid-DdeSE04H.cjs +0 -2
  69. package/dist/genUuid-DdeSE04H.cjs.map +0 -1
  70. package/dist/index-C87obATS.js +0 -2616
  71. package/dist/index-C87obATS.js.map +0 -1
  72. package/dist/index-ChwS_h0D.cjs +0 -18
  73. package/dist/index-ChwS_h0D.cjs.map +0 -1
  74. package/dist/package.json.d.ts +0 -158
  75. package/dist/react-web/Root.d.ts +0 -6
  76. package/dist/react-web/hooks/index.d.ts +0 -6
  77. package/dist/react-web/hooks/use-sound.d.ts +0 -13
  78. package/dist/react-web/hooks/use-sound.test.d.ts +0 -1
  79. package/dist/react-web/hooks/use-sync-state.test.d.ts +0 -1
  80. package/dist/react-web/hooks/useAbstractChat.d.ts +0 -157
  81. package/dist/react-web/hooks/useAxiosInstance.d.ts +0 -190
  82. package/dist/react-web/hooks/useSyncState.d.ts +0 -4
  83. package/dist/react-web/hooks/useTimeoutState.d.ts +0 -3
  84. package/dist/react-web/providers/ChatProvider.d.ts +0 -143
  85. package/dist/react-web/providers/ConfigDataProvider.d.ts +0 -62
  86. package/dist/react-web/providers/ContactProvider.d.ts +0 -58
  87. package/dist/react-web/providers/LocalesProvider.d.ts +0 -11
  88. package/dist/react-web/providers/componentRegistry.d.ts +0 -13
  89. package/dist/react-web/providers/use-widget-sfx.d.ts +0 -7
  90. package/dist/react-web/providers/usePreludeData.d.ts +0 -2
  91. package/dist/react-web/utils/debug.d.ts +0 -2
  92. package/dist/react-web/utils/getters.d.ts +0 -24
  93. package/dist/react-web/utils/index.d.ts +0 -1
  94. package/dist/src/hooks/useShouldCollectData.d.ts +0 -3
  95. /package/dist/react-web/{locales → core-integration/locales}/ar.locale.d.ts +0 -0
  96. /package/dist/react-web/{locales → core-integration/locales}/de.locale.d.ts +0 -0
  97. /package/dist/react-web/{locales → core-integration/locales}/en.locale.d.ts +0 -0
  98. /package/dist/react-web/{locales → core-integration/locales}/fr.locale.d.ts +0 -0
  99. /package/dist/react-web/{locales → core-integration/locales}/helper.d.ts +0 -0
  100. /package/dist/react-web/{locales → core-integration/locales}/index.d.ts +0 -0
  101. /package/dist/react-web/{locales → core-integration/locales}/nl.locale.d.ts +0 -0
  102. /package/dist/react-web/{locales → core-integration/locales}/pt.locale.d.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-DUlnC30_.js","sources":["../react-web/utils/create-safe-context.ts","../react-web/core-integration/components.ts","../react-web/core-integration/locales/ar.locale.ts","../react-web/core-integration/locales/de.locale.ts","../react-web/core-integration/locales/en.locale.ts","../react-web/core-integration/locales/fr.locale.ts","../react-web/core-integration/locales/nl.locale.ts","../react-web/core-integration/locales/pt.locale.ts","../react-web/core-integration/locales/helper.ts","../react-web/core-integration/ChatProvider.tsx","../react-web/core-integration/hooks/usePubsub.ts","../react-web/core-integration/hooks/useChatMessages.ts","../react-web/core-integration/hooks/useChatSession.ts","../react-web/core-integration/hooks/useConfig.ts","../node_modules/.pnpm/use-sync-external-store@1.2.2_react@18.3.1/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js","../node_modules/.pnpm/use-sync-external-store@1.2.2_react@18.3.1/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js","../node_modules/.pnpm/use-sync-external-store@1.2.2_react@18.3.1/node_modules/use-sync-external-store/shim/index.js","../node_modules/.pnpm/swr@2.2.5_react@18.3.1/node_modules/swr/dist/_internal/index.mjs","../node_modules/.pnpm/swr@2.2.5_react@18.3.1/node_modules/swr/dist/core/index.mjs","../react-web/core-integration/hooks/usePreludeData.tsx","../react-web/core-integration/hooks/useLocale.ts","../react-web/core-integration/hooks/useUploadFiles.ts","../react-web/core-integration/hooks/useContact.ts"],"sourcesContent":["import { createContext, useContext } from \"react\";\n\nexport function createSafeContext<TDdata>(init?: TDdata) {\n const context = createContext(init ?? ({} as TDdata));\n\n const useSafeContext = () => {\n const ctx = useContext(context);\n if (ctx === undefined) {\n throw new Error(\"useSafeContext must be used within a Provider\");\n }\n return ctx;\n };\n\n return [useSafeContext, context.Provider] as const;\n}\n","import { WidgetComponentKey, WidgetComponentType } from \"@react/types\";\n\nexport class ComponentRegistry {\n components: WidgetComponentType[] = [\n {\n key: \"fallback\",\n component: (data) => \"fallback\",\n },\n {\n key: \"loading\",\n component: (data) => \"loading\",\n },\n ] as const;\n\n constructor(opts: { components?: WidgetComponentType[] }) {\n const { components } = opts;\n\n if (components) {\n components.forEach((c) => this.register(c));\n }\n\n if (this.components.length === 0) {\n throw new Error(\"No components registered\");\n } else if (!this.get(\"fallback\")) {\n throw new Error(\"No fallback component registered\");\n }\n }\n\n register(com: WidgetComponentType) {\n // Replace the key if it already exists\n const index = this.components.findIndex((c) => c.key === com.key);\n if (index !== -1) {\n this.components[index] = com;\n } else {\n this.components.push(com);\n }\n return this;\n }\n\n private get(key: WidgetComponentKey) {\n const c = this.components.find(\n (c) => c.key.toUpperCase() === key.toUpperCase(),\n );\n if (c) return c;\n return null;\n }\n\n private getOrFallback(key?: string) {\n return key ? this.get(key) || this.get(\"fallback\")! : this.get(\"fallback\")!;\n }\n\n public getComponent(key: string, getFallback?: boolean) {\n if (getFallback) {\n return this.getOrFallback(key).component;\n }\n\n return this.get(key)?.component;\n }\n}\n","import { TranslatableMessages } from \".\";\n\nexport const arLocale: TranslatableMessages = {\n ok: \"حسنا\",\n yes: \"نعم\",\n no: \"لا\",\n agree: \"موافق\",\n cancel: \"إلغاء\",\n \"yes-exit\": \"نعم، اخرج\",\n \"yes-reset\": \"نعم، إعادة تعيين\",\n \"no-cancel\": \"لا، إلغاء\",\n \"are-you-sure\": \"هل أنت متأكد؟\",\n recording: \"تسجيل\",\n \"thank-you\": \"شكرا\",\n \"sorry-try-again\": \"عذرا، حاول مرة أخرى\",\n \"error-occurred\": \"حدث خطأ\",\n \"please-try-again\": \"يرجى المحاولة مرة أخرى\",\n \"write-a-message\": \"اكتب رسالة...\",\n \"send-message\": \"إرسال رسالة\",\n connected: \"متصل\",\n connecting: \"جاري الاتصال\",\n reconnecting: \"جاري إعادة الاتصال\",\n reconnected: \"تم إعادة الاتصال\",\n disconnecting: \"جاري قطع الاتصال\",\n disconnected: \"قطع الاتصال\",\n error: \"خطأ\",\n \"persist-session\": \"حفظ الجلسة\",\n settings: \"إعدادات\",\n close: \"إغلاق\",\n help: \"مساعدة\",\n chat: \"محادثة\",\n send: \"إرسال\",\n copy: \"نسخ\",\n copied: \"تم النسخ\",\n \"sound-effects\": \"التاثيرات الصوتية\",\n language: \"اللغة\",\n select: \"اختر\",\n agent: \"الوكيل\",\n user: \"المستخدم\",\n bot: \"البوت\",\n \"reset-conversation-confirm\":\n \"هل أنت متأكد من أنك تريد إعادة تعيين المحادثة؟\",\n \"close-widget\": \"إغلاق الودجة\",\n \"got-any-questions\": \"هل لديك أي أسئلة؟ تحدث معنا!\",\n \"typical-response-time\": \"عادة ما نرد في أقل من دقيقة واحدة\",\n \"session-closed-lead\": \"تم حل مشكلتك!\",\n exit: \"خروج\",\n \"create-new-ticket\": \"إنشاء تذكرة جديدة\",\n \"reset-conversation\": \"إعادة تعيين المحادثة\",\n \"welcome-title\": \"مرحبًا بك في دردشة الدعم الخاصة بنا\",\n \"welcome-description\":\n \"نحن هنا للمساعدة! ابدأ محادثة وسنرد عليك في أقرب وقت ممكن.\",\n \"your-name\": \"اسمك\",\n \"your-email\": \"عنوان بريدك الإلكتروني\",\n \"start-chat\": \"تحدث إلى الدعم\",\n \"starting-chat\": \"جاري الاتصال...\",\n \"hello-greeting\": \"مرحبًا! كيف يمكننا مساعدتك اليوم؟\",\n};\n","import { TranslatableMessages } from \".\";\n\nexport const deLocale: TranslatableMessages = {\n ok: \"OK\",\n yes: \"Ja\",\n no: \"Nein\",\n agree: \"Zustimmen\",\n cancel: \"Stornieren\",\n \"yes-exit\": \"Ja, beenden\",\n \"yes-reset\": \"Ja, zurücksetzen\",\n \"no-cancel\": \"Nein, abbrechen\",\n \"are-you-sure\": \"Sind Sie sicher?\",\n recording: \"Aufnahme läuft\",\n \"thank-you\": \"Vielen Dank\",\n \"sorry-try-again\": \"Entschuldigung, bitte versuchen Sie es erneut\",\n \"error-occurred\": \"Ein Fehler ist aufgetreten\",\n \"please-try-again\": \"Bitte versuchen Sie es erneut\",\n \"write-a-message\": \"Nachricht schreiben...\",\n \"send-message\": \"Nachricht senden\",\n connected: \"Verbunden\",\n connecting: \"Verbindung wird hergestellt\",\n reconnecting: \"Verbindung wird wiederhergestellt\",\n reconnected: \"Wieder verbunden\",\n disconnecting: \"Verbindung wird getrennt\",\n disconnected: \"Verbindung getrennt\",\n error: \"Fehler\",\n \"persist-session\": \"Sitzung beibehalten\",\n settings: \"Einstellungen\",\n close: \"Schließen\",\n help: \"Hilfe\",\n chat: \"Chat\",\n send: \"Senden\",\n copy: \"Kopieren\",\n copied: \"Kopiert\",\n \"sound-effects\": \"Soundeffekte\",\n language: \"Sprache\",\n select: \"Auswählen\",\n agent: \"Agent\",\n user: \"Benutzer\",\n bot: \"Bot\",\n \"got-any-questions\": \"Haben Sie Fragen? Chatten Sie mit uns!\",\n \"typical-response-time\":\n \"Üblicherweise antworten wir in weniger als 1 Minute\",\n \"reset-conversation-confirm\":\n \"Möchten Sie die Konversation wirklich zurücksetzen?\",\n \"close-widget\": \"Widget schließen\",\n \"session-closed-lead\": \"Ihr Problem wurde gelöst!\",\n \"create-new-ticket\": \"Neues Ticket erstellen\",\n exit: \"Beenden\",\n \"reset-conversation\": \"Konversation zurücksetzen\",\n \"welcome-title\": \"Willkommen in unserem Support-Chat\",\n \"welcome-description\":\n \"Wir sind hier, um zu helfen! Beginnen Sie ein Gespräch und wir werden so schnell wie möglich antworten.\",\n \"your-name\": \"Ihr Name\",\n \"your-email\": \"Ihre E-Mail-Adresse\",\n \"start-chat\": \"Mit dem Support sprechen\",\n \"starting-chat\": \"Verbindung wird hergestellt...\",\n \"hello-greeting\": \"Hallo! Wie können wir Ihnen heute helfen?\",\n};\n","export const enLocale = {\n ok: \"OK\",\n yes: \"Yes\",\n no: \"No\",\n agree: \"Agree\",\n cancel: \"Cancel\",\n \"yes-exit\": \"Yes, exit\",\n \"yes-reset\": \"Yes, reset\",\n \"no-cancel\": \"No, cancel\",\n \"are-you-sure\": \"Are you sure?\",\n recording: \"Recording...\",\n \"thank-you\": \"Thank you\",\n \"sorry-try-again\": \"Sorry, please try again\",\n \"error-occurred\": \"An error occurred\",\n \"please-try-again\": \"Please try again\",\n \"write-a-message\": \"Write a message...\",\n \"send-message\": \"Send message\",\n connected: \"Connected\",\n connecting: \"Connecting\",\n reconnecting: \"Reconnecting\",\n reconnected: \"Reconnected\",\n disconnecting: \"Disconnecting\",\n disconnected: \"Disconnected\",\n error: \"Error\",\n \"persist-session\": \"Persist session\",\n settings: \"Settings\",\n close: \"Close\",\n help: \"Help\",\n chat: \"Chat\",\n send: \"Send\",\n copy: \"Copy\",\n copied: \"Copied\",\n \"sound-effects\": \"Sound effects\",\n language: \"Language\",\n select: \"Select\",\n agent: \"Agent\",\n user: \"User\",\n bot: \"Bot\",\n \"reset-conversation-confirm\":\n \"Are you sure you want to reset the conversation?\",\n \"close-widget\": \"Close widget\",\n \"got-any-questions\": \"Got any questions? Chat with us!\",\n \"typical-response-time\": \"Typically respond in less than 1 minute\",\n \"session-closed-lead\": \"Your issue has been resolved!\",\n \"create-new-ticket\": \"Create new ticket\",\n exit: \"Exit\",\n \"reset-conversation\": \"Reset conversation\",\n \"welcome-title\": \"Welcome to our support chat\",\n \"welcome-description\":\n \"We're here to help! Start a conversation and we'll get back to you as soon as possible.\",\n \"your-name\": \"Your name\",\n \"your-email\": \"Your email address\",\n \"start-chat\": \"Talk to support\",\n \"starting-chat\": \"Connecting...\",\n \"hello-greeting\": \"Hi there!\",\n};\n\nexport type TranslationKeysType = keyof typeof enLocale;\n","import { TranslatableMessages } from \".\";\n\nexport const frLocale: TranslatableMessages = {\n ok: \"D'accord\",\n yes: \"Oui\",\n no: \"Non\",\n agree: \"Accepter\",\n cancel: \"Annuler\",\n \"yes-exit\": \"Oui, quitter\",\n \"yes-reset\": \"Oui, réinitialiser\",\n \"no-cancel\": \"Non, annuler\",\n \"are-you-sure\": \"Êtes-vous sûr ?\",\n recording: \"Enregistrement...\",\n \"thank-you\": \"Merci\",\n \"sorry-try-again\": \"Désolé, veuillez réessayer\",\n \"error-occurred\": \"Une erreur s'est produite\",\n \"please-try-again\": \"Veuillez réessayer\",\n \"write-a-message\": \"Écrivez un message...\",\n \"send-message\": \"Envoyer le message\",\n connected: \"Connecté\",\n connecting: \"Connexion en cours\",\n reconnecting: \"Reconnexion en cours\",\n reconnected: \"Reconnecté\",\n disconnecting: \"Déconnexion en cours\",\n disconnected: \"Déconnecté\",\n error: \"Erreur\",\n \"persist-session\": \"Conserver la session\",\n settings: \"Paramètres\",\n close: \"Fermer\",\n help: \"Aide\",\n chat: \"Chat\",\n send: \"Envoyer\",\n copy: \"Copier\",\n copied: \"Copié\",\n \"sound-effects\": \"Effets sonores\",\n language: \"Langue\",\n select: \"Sélectionner\",\n agent: \"Agent\",\n user: \"Utilisateur\",\n bot: \"Bot\",\n \"reset-conversation-confirm\":\n \"Êtes-vous sûr de vouloir réinitialiser la conversation ?\",\n \"close-widget\": \"Fermer le widget\",\n \"got-any-questions\": \"Vous avez des questions ? Chattez avec nous !\",\n \"typical-response-time\": \"Nous répondons généralement en moins d'une minute\",\n \"session-closed-lead\": \"Votre problème a été résolu !\",\n \"create-new-ticket\": \"Créer un nouveau ticket\",\n exit: \"Sortie\",\n \"reset-conversation\": \"Réinitialiser la conversation\",\n \"welcome-title\": \"Bienvenue dans notre chat de support\",\n \"welcome-description\":\n \"Nous sommes là pour vous aider ! Commencez une conversation et nous vous répondrons dès que possible.\",\n \"your-name\": \"Votre nom\",\n \"your-email\": \"Votre adresse e-mail\",\n \"start-chat\": \"Parler au support\",\n \"starting-chat\": \"Connexion...\",\n \"hello-greeting\": \"Bonjour ! Comment pouvons-nous vous aider aujourd'hui ?\",\n};\n","import { TranslatableMessages } from \".\";\n\nexport const nlLocale: TranslatableMessages = {\n ok: \"OK\",\n yes: \"Ja\",\n no: \"Nee\",\n agree: \"Akkoord\",\n cancel: \"Annuleren\",\n \"yes-exit\": \"Ja, afsluiten\",\n \"yes-reset\": \"Ja, resetten\",\n \"no-cancel\": \"Nee, annuleren\",\n \"are-you-sure\": \"Weet u het zeker?\",\n recording: \"Opname...\",\n \"thank-you\": \"Dank u\",\n \"sorry-try-again\": \"Sorry, probeer het opnieuw\",\n \"error-occurred\": \"Er is een fout opgetreden\",\n \"please-try-again\": \"Probeer het opnieuw\",\n \"write-a-message\": \"Schrijf een bericht...\",\n \"send-message\": \"Bericht verzenden\",\n connected: \"Verbonden\",\n connecting: \"Verbinding maken\",\n reconnecting: \"Opnieuw verbinding maken\",\n reconnected: \"Opnieuw verbonden\",\n disconnecting: \"Verbinding verbreken\",\n disconnected: \"Verbinding verbroken\",\n error: \"Fout\",\n \"persist-session\": \"Sessie behouden\",\n settings: \"Instellingen\",\n close: \"Sluiten\",\n help: \"Help\",\n chat: \"Chat\",\n send: \"Verzenden\",\n copy: \"Kopiëren\",\n copied: \"Gekopieerd\",\n \"sound-effects\": \"Geluidseffecten\",\n language: \"Taal\",\n select: \"Selecteren\",\n agent: \"Agent\",\n user: \"Gebruiker\",\n bot: \"Bot\",\n \"reset-conversation-confirm\": \"Weet u zeker dat u het gesprek wilt resetten?\",\n \"close-widget\": \"Widget sluiten\",\n \"got-any-questions\": \"Heeft u vragen? Chat met ons!\",\n \"typical-response-time\": \"We reageren doorgaans binnen 1 minuut\",\n \"session-closed-lead\": \"Uw probleem is opgelost!\",\n \"create-new-ticket\": \"Nieuw ticket aanmaken\",\n exit: \"Afsluiten\",\n \"reset-conversation\": \"Gesprek resetten\",\n \"welcome-title\": \"Welkom bij onze supportchat\",\n \"welcome-description\":\n \"We zijn hier om te helpen! Begin een gesprek en we nemen zo snel mogelijk contact met u op.\",\n \"your-name\": \"Uw naam\",\n \"your-email\": \"Uw e-mailadres\",\n \"start-chat\": \"Praat met ondersteuning\",\n \"starting-chat\": \"Verbinding maken...\",\n \"hello-greeting\": \"Hallo! Hoe kunnen we u vandaag helpen?\",\n};\n","import { TranslatableMessages } from \".\";\n\nexport const ptLocale: TranslatableMessages = {\n ok: \"OK\",\n yes: \"Sim\",\n no: \"Não\",\n agree: \"Concordo\",\n cancel: \"Cancelar\",\n \"yes-exit\": \"Sim, sair\",\n \"yes-reset\": \"Sim, redefinir\",\n \"no-cancel\": \"Não, cancelar\",\n \"are-you-sure\": \"Você tem certeza?\",\n recording: \"Gravando...\",\n \"thank-you\": \"Obrigado\",\n \"sorry-try-again\": \"Desculpe, tente novamente\",\n \"error-occurred\": \"Ocorreu um erro\",\n \"please-try-again\": \"Por favor, tente novamente\",\n \"write-a-message\": \"Escreva uma mensagem...\",\n \"send-message\": \"Enviar mensagem\",\n connected: \"Conectado\",\n connecting: \"Conectando\",\n reconnecting: \"Reconectando\",\n reconnected: \"Reconectado\",\n disconnecting: \"Desconectando\",\n disconnected: \"Desconectado\",\n error: \"Erro\",\n \"persist-session\": \"Persistir sessão\",\n settings: \"Configurações\",\n close: \"Fechar\",\n help: \"Ajuda\",\n chat: \"Bate-papo\",\n send: \"Enviar\",\n copy: \"Copiar\",\n copied: \"Copiado\",\n \"sound-effects\": \"Efeitos sonoros\",\n language: \"Idioma\",\n select: \"Selecionar\",\n agent: \"Agente\",\n user: \"Usuário\",\n bot: \"Bot\",\n \"reset-conversation-confirm\":\n \"Você tem certeza de que deseja redefinir a conversa?\",\n \"close-widget\": \"Fechar widget\",\n \"got-any-questions\": \"Tem alguma dúvida? Converse conosco!\",\n \"typical-response-time\": \"Geralmente respondemos em menos de 1 minuto\",\n \"session-closed-lead\": \"Seu problema foi resolvido!\",\n \"create-new-ticket\": \"Criar novo ticket\",\n exit: \"Sair\",\n \"reset-conversation\": \"Redefinir conversa\",\n \"welcome-title\": \"Bem-vindo ao nosso chat de suporte\",\n \"welcome-description\":\n \"Estamos aqui para ajudar! Inicie uma conversa e responderemos o mais rápido possível.\",\n \"your-name\": \"Seu nome\",\n \"your-email\": \"Seu endereço de email\",\n \"start-chat\": \"Falar com o suporte\",\n \"starting-chat\": \"Conectando...\",\n \"hello-greeting\": \"Olá! Como podemos ajudar você hoje?\",\n};\n","import { arLocale } from \"./ar.locale\";\nimport { deLocale } from \"./de.locale\";\nimport { TranslationKeysType, enLocale } from \"./en.locale\";\nimport { frLocale } from \"./fr.locale\";\nimport { nlLocale } from \"./nl.locale\";\nimport { ptLocale } from \"./pt.locale\";\n\nconst locales = {\n en: enLocale,\n ar: arLocale,\n nl: nlLocale,\n fr: frLocale,\n de: deLocale,\n pt: ptLocale,\n} as const;\n\nexport type LangType = keyof typeof locales;\n\nexport function getStr(key: TranslationKeysType, lang: LangType): string {\n const locale = locales[lang];\n return locale ? locale[key] || \"\" : \"\";\n}\n","import {\n CoreOptions,\n createChat,\n createConfig,\n ApiCaller,\n Platform,\n createLogger,\n isStorageAvailable,\n} from \"@core/index\";\nimport { WidgetComponentType } from \"@react/types\";\nimport { createSafeContext } from \"@react/utils/create-safe-context\";\nimport React, { useMemo, useEffect, useState } from \"react\";\nimport { ComponentRegistry } from \"./components\";\nimport { TranslationKeysType } from \"./locales/en.locale\";\nimport { getStr, LangType } from \"./locales\";\nimport { z } from \"zod\";\n\nconst defaultStorage = {\n getItem: async (key: string) => localStorage.getItem(key),\n setItem: async (key: string, value: string) =>\n localStorage.setItem(key, value),\n removeItem: async (key: string) => localStorage.removeItem(key),\n isAvailable: () => true,\n};\n\nconst defaultPlatform: Platform = {\n env: {\n platform: \"web\",\n },\n storage: defaultStorage,\n logger: createLogger({ level: \"debug\" }),\n};\n\ninterface InitializeChatOptions {\n options: CoreOptions;\n platform?: Partial<Platform>;\n}\n\nconst widgetSettingsSchema = z.object({\n persistSession: z.boolean().optional(),\n useSoundEffects: z.boolean().optional(),\n});\n\nfunction useInitializeChat({\n options,\n platform: customPlatform,\n}: InitializeChatOptions) {\n const [widgetSettings, setWidgetSettings] = useState<\n z.infer<typeof widgetSettingsSchema>\n >({\n persistSession: options.settings?.persistSession ?? false,\n useSoundEffects: options.settings?.useSoundEffects ?? false,\n });\n\n const platform = useMemo<Platform>(() => {\n return {\n env: {\n platform: customPlatform?.env?.platform ?? defaultPlatform.env.platform,\n },\n storage: customPlatform?.storage ?? defaultPlatform.storage,\n logger: customPlatform?.logger ?? defaultPlatform.logger,\n audio: customPlatform?.audio ?? defaultPlatform.audio,\n };\n }, [customPlatform]);\n\n const config = useMemo(() => {\n return createConfig(\n {\n ...options,\n settings: widgetSettings,\n },\n platform,\n );\n }, [options, platform, widgetSettings]);\n\n // Load initial settings from storage only once\n useEffect(() => {\n const init = async () => {\n if (isStorageAvailable(platform.storage)) {\n try {\n const settings = await platform.storage.getItem(\n `${options.token}:settings`,\n );\n if (settings) {\n const parsedSettings = widgetSettingsSchema.parse(\n JSON.parse(settings),\n );\n setWidgetSettings((prev) => ({\n ...prev,\n ...parsedSettings,\n }));\n }\n } catch (error) {\n console.error(\"Failed to load settings:\", error);\n }\n }\n };\n init();\n }, [platform.storage, options.token]);\n\n const api = useMemo(() => {\n return new ApiCaller({\n config: config.getConfig(),\n });\n }, [config.config]);\n\n const chat = useMemo(() => {\n return createChat({\n api,\n config,\n platform,\n });\n }, [config, platform, api]);\n useEffect(() => {\n return () => {\n chat.cleanup();\n };\n }, [chat]);\n\n return {\n config,\n chat,\n api,\n widgetSettings,\n setWidgetSettings,\n };\n}\n\ninterface ChatProviderValue extends ReturnType<typeof useInitializeChat> {\n components?: WidgetComponentType[];\n componentStore: ComponentRegistry;\n version: string;\n locale: {\n get: (key: TranslationKeysType, pfx?: string) => string;\n lang: LangType;\n };\n}\n\nconst [useChat, SafeProvider] = createSafeContext<ChatProviderValue>();\n\ninterface ChatProviderProps {\n options: CoreOptions;\n children: React.ReactNode;\n components?: WidgetComponentType[];\n platform?: Partial<Platform>;\n}\n\nfunction ChatProvider({\n options,\n children,\n components,\n platform,\n}: ChatProviderProps) {\n const context = useInitializeChat({ options, platform });\n\n const componentStore = useMemo(\n () =>\n new ComponentRegistry({\n components: components,\n }),\n [components],\n );\n\n const locale = useMemo<ChatProviderValue[\"locale\"]>(() => {\n const config = context.config.getConfig();\n return {\n get: (key: TranslationKeysType, pfx?: string) =>\n getStr(key, config.language as LangType) + (pfx ?? \"\"),\n lang: config.language as LangType,\n };\n }, [context.config.getConfig().language]);\n\n return (\n <SafeProvider\n value={{\n ...context,\n componentStore,\n version: import.meta.env.__VERSION__,\n locale,\n }}\n >\n {children}\n </SafeProvider>\n );\n}\n\nexport { useChat, ChatProvider };\n","import { PubSub } from \"@core/types\";\nimport { useSyncExternalStore } from \"react\";\n\nexport function usePubsub<T>(p: PubSub<T>) {\n return useSyncExternalStore(p.subscribe, p.getState, p.getState);\n}","import { usePubsub } from './usePubsub';\nimport { useChat } from '../ChatProvider';\n\nexport function useChatState() {\n const { chat } = useChat();\n const chatState = usePubsub(chat.chatState);\n return { chatState, chat }\n}","import { useEffect, useState } from 'react';\nimport { useChat } from '../ChatProvider';\nimport { usePubsub } from './usePubsub';\n\nexport function useChatSession() {\n const { chat } = useChat();\n const chatSession = usePubsub(chat.sessionState)\n return {\n chat,\n chatSession\n };\n} ","import { useChat } from \"../ChatProvider\";\n\nexport function useConfig() {\n const { config } = useChat();\n return config;\n}","/**\n * @license React\n * use-sync-external-store-shim.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var e=require(\"react\");function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k=\"function\"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}\nfunction r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u=\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;\n","/**\n * @license React\n * use-sync-external-store-shim.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\n// dispatch for CommonJS interop named imports.\n\nvar useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue;\nvar didWarnOld18Alpha = false;\nvar didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works\n// because of a very particular set of implementation details and assumptions\n// -- change any one of them and it will break. The most important assumption\n// is that updates are always synchronous, because concurrent rendering is\n// only available in versions of React that also have a built-in\n// useSyncExternalStore API. And we only use this shim when the built-in API\n// does not exist.\n//\n// Do not assume that the clever hacks used by this hook also work in general.\n// The point of this shim is to replace the need for hacks by other libraries.\n\nfunction useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n// React do not expose a way to check if we're hydrating. So users of the shim\n// will need to track that themselves and return the correct value\n// from `getSnapshot`.\ngetServerSnapshot) {\n {\n if (!didWarnOld18Alpha) {\n if (React.startTransition !== undefined) {\n didWarnOld18Alpha = true;\n\n error('You are using an outdated, pre-release alpha of React 18 that ' + 'does not support useSyncExternalStore. The ' + 'use-sync-external-store shim will not work correctly. Upgrade ' + 'to a newer pre-release.');\n }\n }\n } // Read the current snapshot from the store on every render. Again, this\n // breaks the rules of React, and only works here because of specific\n // implementation details, most importantly that updates are\n // always synchronous.\n\n\n var value = getSnapshot();\n\n {\n if (!didWarnUncachedGetSnapshot) {\n var cachedValue = getSnapshot();\n\n if (!objectIs(value, cachedValue)) {\n error('The result of getSnapshot should be cached to avoid an infinite loop');\n\n didWarnUncachedGetSnapshot = true;\n }\n }\n } // Because updates are synchronous, we don't queue them. Instead we force a\n // re-render whenever the subscribed state changes by updating an some\n // arbitrary useState hook. Then, during render, we call getSnapshot to read\n // the current value.\n //\n // Because we don't actually use the state returned by the useState hook, we\n // can save a bit of memory by storing other stuff in that slot.\n //\n // To implement the early bailout, we need to track some things on a mutable\n // object. Usually, we would put that in a useRef hook, but we can stash it in\n // our useState hook instead.\n //\n // To force a re-render, we call forceUpdate({inst}). That works because the\n // new object always fails an equality check.\n\n\n var _useState = useState({\n inst: {\n value: value,\n getSnapshot: getSnapshot\n }\n }),\n inst = _useState[0].inst,\n forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated\n // in the layout phase so we can access it during the tearing check that\n // happens on subscribe.\n\n\n useLayoutEffect(function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the\n // commit phase if there was an interleaved mutation. In concurrent mode\n // this can happen all the time, but even in synchronous mode, an earlier\n // effect may have mutated the store.\n\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst: inst\n });\n }\n }, [subscribe, value, getSnapshot]);\n useEffect(function () {\n // Check for changes right before subscribing. Subsequent changes will be\n // detected in the subscription handler.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst: inst\n });\n }\n\n var handleStoreChange = function () {\n // TODO: Because there is no cross-renderer API for batching updates, it's\n // up to the consumer of this library to wrap their subscription event\n // with unstable_batchedUpdates. Should we try to detect when this isn't\n // the case and print a warning in development?\n // The store changed. Check if the snapshot changed since the last time we\n // read from the store.\n if (checkIfSnapshotChanged(inst)) {\n // Force a re-render.\n forceUpdate({\n inst: inst\n });\n }\n }; // Subscribe to the store and return a clean-up function.\n\n\n return subscribe(handleStoreChange);\n }, [subscribe]);\n useDebugValue(value);\n return value;\n}\n\nfunction checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n var prevValue = inst.value;\n\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(prevValue, nextValue);\n } catch (error) {\n return true;\n }\n}\n\nfunction useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {\n // Note: The shim does not use getServerSnapshot, because pre-18 versions of\n // React do not expose a way to check if we're hydrating. So users of the shim\n // will need to track that themselves and return the correct value\n // from `getSnapshot`.\n return getSnapshot();\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\n\nvar isServerEnvironment = !canUseDOM;\n\nvar shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;\nvar useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;\n\nexports.useSyncExternalStore = useSyncExternalStore$2;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.min.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","import React, { useEffect, useLayoutEffect, createContext, useContext, useMemo, useRef, createElement } from 'react';\n\n// Shared state between server components and client components\nconst noop = ()=>{};\n// Using noop() as the undefined value as undefined can be replaced\n// by something else. Prettier ignore and extra parentheses are necessary here\n// to ensure that tsc doesn't remove the __NOINLINE__ comment.\n// prettier-ignore\nconst UNDEFINED = /*#__NOINLINE__*/ noop();\nconst OBJECT = Object;\nconst isUndefined = (v)=>v === UNDEFINED;\nconst isFunction = (v)=>typeof v == 'function';\nconst mergeObjects = (a, b)=>({\n ...a,\n ...b\n });\nconst isPromiseLike = (x)=>isFunction(x.then);\n\n// use WeakMap to store the object->key mapping\n// so the objects can be garbage collected.\n// WeakMap uses a hashtable under the hood, so the lookup\n// complexity is almost O(1).\nconst table = new WeakMap();\n// counter of the key\nlet counter = 0;\n// A stable hash implementation that supports:\n// - Fast and ensures unique hash properties\n// - Handles unserializable values\n// - Handles object key ordering\n// - Generates short results\n//\n// This is not a serialization function, and the result is not guaranteed to be\n// parsable.\nconst stableHash = (arg)=>{\n const type = typeof arg;\n const constructor = arg && arg.constructor;\n const isDate = constructor == Date;\n let result;\n let index;\n if (OBJECT(arg) === arg && !isDate && constructor != RegExp) {\n // Object/function, not null/date/regexp. Use WeakMap to store the id first.\n // If it's already hashed, directly return the result.\n result = table.get(arg);\n if (result) return result;\n // Store the hash first for circular reference detection before entering the\n // recursive `stableHash` calls.\n // For other objects like set and map, we use this id directly as the hash.\n result = ++counter + '~';\n table.set(arg, result);\n if (constructor == Array) {\n // Array.\n result = '@';\n for(index = 0; index < arg.length; index++){\n result += stableHash(arg[index]) + ',';\n }\n table.set(arg, result);\n }\n if (constructor == OBJECT) {\n // Object, sort keys.\n result = '#';\n const keys = OBJECT.keys(arg).sort();\n while(!isUndefined(index = keys.pop())){\n if (!isUndefined(arg[index])) {\n result += index + ':' + stableHash(arg[index]) + ',';\n }\n }\n table.set(arg, result);\n }\n } else {\n result = isDate ? arg.toJSON() : type == 'symbol' ? arg.toString() : type == 'string' ? JSON.stringify(arg) : '' + arg;\n }\n return result;\n};\n\n// Global state used to deduplicate requests and store listeners\nconst SWRGlobalState = new WeakMap();\n\nconst EMPTY_CACHE = {};\nconst INITIAL_CACHE = {};\nconst STR_UNDEFINED = 'undefined';\n// NOTE: Use the function to guarantee it's re-evaluated between jsdom and node runtime for tests.\nconst isWindowDefined = typeof window != STR_UNDEFINED;\nconst isDocumentDefined = typeof document != STR_UNDEFINED;\nconst hasRequestAnimationFrame = ()=>isWindowDefined && typeof window['requestAnimationFrame'] != STR_UNDEFINED;\nconst createCacheHelper = (cache, key)=>{\n const state = SWRGlobalState.get(cache);\n return [\n // Getter\n ()=>!isUndefined(key) && cache.get(key) || EMPTY_CACHE,\n // Setter\n (info)=>{\n if (!isUndefined(key)) {\n const prev = cache.get(key);\n // Before writing to the store, we keep the value in the initial cache\n // if it's not there yet.\n if (!(key in INITIAL_CACHE)) {\n INITIAL_CACHE[key] = prev;\n }\n state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE);\n }\n },\n // Subscriber\n state[6],\n // Get server cache snapshot\n ()=>{\n if (!isUndefined(key)) {\n // If the cache was updated on the client, we return the stored initial value.\n if (key in INITIAL_CACHE) return INITIAL_CACHE[key];\n }\n // If we haven't done any client-side updates, we return the current value.\n return !isUndefined(key) && cache.get(key) || EMPTY_CACHE;\n }\n ];\n} // export { UNDEFINED, OBJECT, isUndefined, isFunction, mergeObjects, isPromiseLike }\n;\n\n/**\n * Due to the bug https://bugs.chromium.org/p/chromium/issues/detail?id=678075,\n * it's not reliable to detect if the browser is currently online or offline\n * based on `navigator.onLine`.\n * As a workaround, we always assume it's online on the first load, and change\n * the status upon `online` or `offline` events.\n */ let online = true;\nconst isOnline = ()=>online;\n// For node and React Native, `add/removeEventListener` doesn't exist on window.\nconst [onWindowEvent, offWindowEvent] = isWindowDefined && window.addEventListener ? [\n window.addEventListener.bind(window),\n window.removeEventListener.bind(window)\n] : [\n noop,\n noop\n];\nconst isVisible = ()=>{\n const visibilityState = isDocumentDefined && document.visibilityState;\n return isUndefined(visibilityState) || visibilityState !== 'hidden';\n};\nconst initFocus = (callback)=>{\n // focus revalidate\n if (isDocumentDefined) {\n document.addEventListener('visibilitychange', callback);\n }\n onWindowEvent('focus', callback);\n return ()=>{\n if (isDocumentDefined) {\n document.removeEventListener('visibilitychange', callback);\n }\n offWindowEvent('focus', callback);\n };\n};\nconst initReconnect = (callback)=>{\n // revalidate on reconnected\n const onOnline = ()=>{\n online = true;\n callback();\n };\n // nothing to revalidate, just update the status\n const onOffline = ()=>{\n online = false;\n };\n onWindowEvent('online', onOnline);\n onWindowEvent('offline', onOffline);\n return ()=>{\n offWindowEvent('online', onOnline);\n offWindowEvent('offline', onOffline);\n };\n};\nconst preset = {\n isOnline,\n isVisible\n};\nconst defaultConfigOptions = {\n initFocus,\n initReconnect\n};\n\nconst IS_REACT_LEGACY = !React.useId;\nconst IS_SERVER = !isWindowDefined || 'Deno' in window;\n// Polyfill requestAnimationFrame\nconst rAF = (f)=>hasRequestAnimationFrame() ? window['requestAnimationFrame'](f) : setTimeout(f, 1);\n// React currently throws a warning when using useLayoutEffect on the server.\n// To get around it, we can conditionally useEffect on the server (no-op) and\n// useLayoutEffect in the browser.\nconst useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect;\n// This assignment is to extend the Navigator type to use effectiveType.\nconst navigatorConnection = typeof navigator !== 'undefined' && navigator.connection;\n// Adjust the config based on slow connection status (<= 70Kbps).\nconst slowConnection = !IS_SERVER && navigatorConnection && ([\n 'slow-2g',\n '2g'\n].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);\n\nconst serialize = (key)=>{\n if (isFunction(key)) {\n try {\n key = key();\n } catch (err) {\n // dependencies not ready\n key = '';\n }\n }\n // Use the original key as the argument of fetcher. This can be a string or an\n // array of values.\n const args = key;\n // If key is not falsy, or not an empty array, hash it.\n key = typeof key == 'string' ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : '';\n return [\n key,\n args\n ];\n};\n\n// Global timestamp.\nlet __timestamp = 0;\nconst getTimestamp = ()=>++__timestamp;\n\nconst FOCUS_EVENT = 0;\nconst RECONNECT_EVENT = 1;\nconst MUTATE_EVENT = 2;\nconst ERROR_REVALIDATE_EVENT = 3;\n\nvar events = {\n __proto__: null,\n ERROR_REVALIDATE_EVENT: ERROR_REVALIDATE_EVENT,\n FOCUS_EVENT: FOCUS_EVENT,\n MUTATE_EVENT: MUTATE_EVENT,\n RECONNECT_EVENT: RECONNECT_EVENT\n};\n\nasync function internalMutate(...args) {\n const [cache, _key, _data, _opts] = args;\n // When passing as a boolean, it's explicitly used to disable/enable\n // revalidation.\n const options = mergeObjects({\n populateCache: true,\n throwOnError: true\n }, typeof _opts === 'boolean' ? {\n revalidate: _opts\n } : _opts || {});\n let populateCache = options.populateCache;\n const rollbackOnErrorOption = options.rollbackOnError;\n let optimisticData = options.optimisticData;\n const rollbackOnError = (error)=>{\n return typeof rollbackOnErrorOption === 'function' ? rollbackOnErrorOption(error) : rollbackOnErrorOption !== false;\n };\n const throwOnError = options.throwOnError;\n // If the second argument is a key filter, return the mutation results for all\n // filtered keys.\n if (isFunction(_key)) {\n const keyFilter = _key;\n const matchedKeys = [];\n const it = cache.keys();\n for (const key of it){\n if (// Skip the special useSWRInfinite and useSWRSubscription keys.\n !/^\\$(inf|sub)\\$/.test(key) && keyFilter(cache.get(key)._k)) {\n matchedKeys.push(key);\n }\n }\n return Promise.all(matchedKeys.map(mutateByKey));\n }\n return mutateByKey(_key);\n async function mutateByKey(_k) {\n // Serialize key\n const [key] = serialize(_k);\n if (!key) return;\n const [get, set] = createCacheHelper(cache, key);\n const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache);\n const startRevalidate = ()=>{\n const revalidators = EVENT_REVALIDATORS[key];\n const revalidate = isFunction(options.revalidate) ? options.revalidate(get().data, _k) : options.revalidate !== false;\n if (revalidate) {\n // Invalidate the key by deleting the concurrent request markers so new\n // requests will not be deduped.\n delete FETCH[key];\n delete PRELOAD[key];\n if (revalidators && revalidators[0]) {\n return revalidators[0](MUTATE_EVENT).then(()=>get().data);\n }\n }\n return get().data;\n };\n // If there is no new data provided, revalidate the key with current state.\n if (args.length < 3) {\n // Revalidate and broadcast state.\n return startRevalidate();\n }\n let data = _data;\n let error;\n // Update global timestamps.\n const beforeMutationTs = getTimestamp();\n MUTATION[key] = [\n beforeMutationTs,\n 0\n ];\n const hasOptimisticData = !isUndefined(optimisticData);\n const state = get();\n // `displayedData` is the current value on screen. It could be the optimistic value\n // that is going to be overridden by a `committedData`, or get reverted back.\n // `committedData` is the validated value that comes from a fetch or mutation.\n const displayedData = state.data;\n const currentData = state._c;\n const committedData = isUndefined(currentData) ? displayedData : currentData;\n // Do optimistic data update.\n if (hasOptimisticData) {\n optimisticData = isFunction(optimisticData) ? optimisticData(committedData, displayedData) : optimisticData;\n // When we set optimistic data, backup the current committedData data in `_c`.\n set({\n data: optimisticData,\n _c: committedData\n });\n }\n if (isFunction(data)) {\n // `data` is a function, call it passing current cache value.\n try {\n data = data(committedData);\n } catch (err) {\n // If it throws an error synchronously, we shouldn't update the cache.\n error = err;\n }\n }\n // `data` is a promise/thenable, resolve the final data first.\n if (data && isPromiseLike(data)) {\n // This means that the mutation is async, we need to check timestamps to\n // avoid race conditions.\n data = await data.catch((err)=>{\n error = err;\n });\n // Check if other mutations have occurred since we've started this mutation.\n // If there's a race we don't update cache or broadcast the change,\n // just return the data.\n if (beforeMutationTs !== MUTATION[key][0]) {\n if (error) throw error;\n return data;\n } else if (error && hasOptimisticData && rollbackOnError(error)) {\n // Rollback. Always populate the cache in this case but without\n // transforming the data.\n populateCache = true;\n // Reset data to be the latest committed data, and clear the `_c` value.\n set({\n data: committedData,\n _c: UNDEFINED\n });\n }\n }\n // If we should write back the cache after request.\n if (populateCache) {\n if (!error) {\n // Transform the result into data.\n if (isFunction(populateCache)) {\n const populateCachedData = populateCache(data, committedData);\n set({\n data: populateCachedData,\n error: UNDEFINED,\n _c: UNDEFINED\n });\n } else {\n // Only update cached data and reset the error if there's no error. Data can be `undefined` here.\n set({\n data,\n error: UNDEFINED,\n _c: UNDEFINED\n });\n }\n }\n }\n // Reset the timestamp to mark the mutation has ended.\n MUTATION[key][1] = getTimestamp();\n // Update existing SWR Hooks' internal states:\n Promise.resolve(startRevalidate()).then(()=>{\n // The mutation and revalidation are ended, we can clear it since the data is\n // not an optimistic value anymore.\n set({\n _c: UNDEFINED\n });\n });\n // Throw error or return data\n if (error) {\n if (throwOnError) throw error;\n return;\n }\n return data;\n }\n}\n\nconst revalidateAllKeys = (revalidators, type)=>{\n for(const key in revalidators){\n if (revalidators[key][0]) revalidators[key][0](type);\n }\n};\nconst initCache = (provider, options)=>{\n // The global state for a specific provider will be used to deduplicate\n // requests and store listeners. As well as a mutate function that is bound to\n // the cache.\n // The provider's global state might be already initialized. Let's try to get the\n // global state associated with the provider first.\n if (!SWRGlobalState.has(provider)) {\n const opts = mergeObjects(defaultConfigOptions, options);\n // If there's no global state bound to the provider, create a new one with the\n // new mutate function.\n const EVENT_REVALIDATORS = {};\n const mutate = internalMutate.bind(UNDEFINED, provider);\n let unmount = noop;\n const subscriptions = {};\n const subscribe = (key, callback)=>{\n const subs = subscriptions[key] || [];\n subscriptions[key] = subs;\n subs.push(callback);\n return ()=>subs.splice(subs.indexOf(callback), 1);\n };\n const setter = (key, value, prev)=>{\n provider.set(key, value);\n const subs = subscriptions[key];\n if (subs) {\n for (const fn of subs){\n fn(value, prev);\n }\n }\n };\n const initProvider = ()=>{\n if (!SWRGlobalState.has(provider)) {\n // Update the state if it's new, or if the provider has been extended.\n SWRGlobalState.set(provider, [\n EVENT_REVALIDATORS,\n {},\n {},\n {},\n mutate,\n setter,\n subscribe\n ]);\n if (!IS_SERVER) {\n // When listening to the native events for auto revalidations,\n // we intentionally put a delay (setTimeout) here to make sure they are\n // fired after immediate JavaScript executions, which can be\n // React's state updates.\n // This avoids some unnecessary revalidations such as\n // https://github.com/vercel/swr/issues/1680.\n const releaseFocus = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));\n const releaseReconnect = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));\n unmount = ()=>{\n releaseFocus && releaseFocus();\n releaseReconnect && releaseReconnect();\n // When un-mounting, we need to remove the cache provider from the state\n // storage too because it's a side-effect. Otherwise, when re-mounting we\n // will not re-register those event listeners.\n SWRGlobalState.delete(provider);\n };\n }\n }\n };\n initProvider();\n // This is a new provider, we need to initialize it and setup DOM events\n // listeners for `focus` and `reconnect` actions.\n // We might want to inject an extra layer on top of `provider` in the future,\n // such as key serialization, auto GC, etc.\n // For now, it's just a `Map` interface without any modifications.\n return [\n provider,\n mutate,\n initProvider,\n unmount\n ];\n }\n return [\n provider,\n SWRGlobalState.get(provider)[4]\n ];\n};\n\n// error retry\nconst onErrorRetry = (_, __, config, revalidate, opts)=>{\n const maxRetryCount = config.errorRetryCount;\n const currentRetryCount = opts.retryCount;\n // Exponential backoff\n const timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;\n if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {\n return;\n }\n setTimeout(revalidate, timeout, opts);\n};\nconst compare = (currentData, newData)=>stableHash(currentData) == stableHash(newData);\n// Default cache provider\nconst [cache, mutate] = initCache(new Map());\n// Default config\nconst defaultConfig = mergeObjects({\n // events\n onLoadingSlow: noop,\n onSuccess: noop,\n onError: noop,\n onErrorRetry,\n onDiscarded: noop,\n // switches\n revalidateOnFocus: true,\n revalidateOnReconnect: true,\n revalidateIfStale: true,\n shouldRetryOnError: true,\n // timeouts\n errorRetryInterval: slowConnection ? 10000 : 5000,\n focusThrottleInterval: 5 * 1000,\n dedupingInterval: 2 * 1000,\n loadingTimeout: slowConnection ? 5000 : 3000,\n // providers\n compare,\n isPaused: ()=>false,\n cache,\n mutate,\n fallback: {}\n}, // use web preset by default\npreset);\n\nconst mergeConfigs = (a, b)=>{\n // Need to create a new object to avoid mutating the original here.\n const v = mergeObjects(a, b);\n // If two configs are provided, merge their `use` and `fallback` options.\n if (b) {\n const { use: u1, fallback: f1 } = a;\n const { use: u2, fallback: f2 } = b;\n if (u1 && u2) {\n v.use = u1.concat(u2);\n }\n if (f1 && f2) {\n v.fallback = mergeObjects(f1, f2);\n }\n }\n return v;\n};\n\nconst SWRConfigContext = createContext({});\nconst SWRConfig = (props)=>{\n const { value } = props;\n const parentConfig = useContext(SWRConfigContext);\n const isFunctionalConfig = isFunction(value);\n const config = useMemo(()=>isFunctionalConfig ? value(parentConfig) : value, [\n isFunctionalConfig,\n parentConfig,\n value\n ]);\n // Extend parent context values and middleware.\n const extendedConfig = useMemo(()=>isFunctionalConfig ? config : mergeConfigs(parentConfig, config), [\n isFunctionalConfig,\n parentConfig,\n config\n ]);\n // Should not use the inherited provider.\n const provider = config && config.provider;\n // initialize the cache only on first access.\n const cacheContextRef = useRef(UNDEFINED);\n if (provider && !cacheContextRef.current) {\n cacheContextRef.current = initCache(provider(extendedConfig.cache || cache), config);\n }\n const cacheContext = cacheContextRef.current;\n // Override the cache if a new provider is given.\n if (cacheContext) {\n extendedConfig.cache = cacheContext[0];\n extendedConfig.mutate = cacheContext[1];\n }\n // Unsubscribe events.\n useIsomorphicLayoutEffect(()=>{\n if (cacheContext) {\n cacheContext[2] && cacheContext[2]();\n return cacheContext[3];\n }\n }, []);\n return createElement(SWRConfigContext.Provider, mergeObjects(props, {\n value: extendedConfig\n }));\n};\n\nconst INFINITE_PREFIX = '$inf$';\n\n// @ts-expect-error\nconst enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;\nconst use = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];\nconst setupDevTools = ()=>{\n if (enableDevtools) {\n // @ts-expect-error\n window.__SWR_DEVTOOLS_REACT__ = React;\n }\n};\n\nconst normalize = (args)=>{\n return isFunction(args[1]) ? [\n args[0],\n args[1],\n args[2] || {}\n ] : [\n args[0],\n null,\n (args[1] === null ? args[2] : args[1]) || {}\n ];\n};\n\nconst useSWRConfig = ()=>{\n return mergeObjects(defaultConfig, useContext(SWRConfigContext));\n};\n\nconst preload = (key_, fetcher)=>{\n const [key, fnArg] = serialize(key_);\n const [, , , PRELOAD] = SWRGlobalState.get(cache);\n // Prevent preload to be called multiple times before used.\n if (PRELOAD[key]) return PRELOAD[key];\n const req = fetcher(fnArg);\n PRELOAD[key] = req;\n return req;\n};\nconst middleware = (useSWRNext)=>(key_, fetcher_, config)=>{\n // fetcher might be a sync function, so this should not be an async function\n const fetcher = fetcher_ && ((...args)=>{\n const [key] = serialize(key_);\n const [, , , PRELOAD] = SWRGlobalState.get(cache);\n if (key.startsWith(INFINITE_PREFIX)) {\n // we want the infinite fetcher to be called.\n // handling of the PRELOAD cache happens there.\n return fetcher_(...args);\n }\n const req = PRELOAD[key];\n if (isUndefined(req)) return fetcher_(...args);\n delete PRELOAD[key];\n return req;\n });\n return useSWRNext(key_, fetcher, config);\n };\n\nconst BUILT_IN_MIDDLEWARE = use.concat(middleware);\n\n// It's tricky to pass generic types as parameters, so we just directly override\n// the types here.\nconst withArgs = (hook)=>{\n return function useSWRArgs(...args) {\n // Get the default and inherited configuration.\n const fallbackConfig = useSWRConfig();\n // Normalize arguments.\n const [key, fn, _config] = normalize(args);\n // Merge configurations.\n const config = mergeConfigs(fallbackConfig, _config);\n // Apply middleware\n let next = hook;\n const { use } = config;\n const middleware = (use || []).concat(BUILT_IN_MIDDLEWARE);\n for(let i = middleware.length; i--;){\n next = middleware[i](next);\n }\n return next(key, fn || config.fetcher || null, config);\n };\n};\n\n// Add a callback function to a list of keyed callback functions and return\n// the unsubscribe function.\nconst subscribeCallback = (key, callbacks, callback)=>{\n const keyedRevalidators = callbacks[key] || (callbacks[key] = []);\n keyedRevalidators.push(callback);\n return ()=>{\n const index = keyedRevalidators.indexOf(callback);\n if (index >= 0) {\n // O(1): faster than splice\n keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1];\n keyedRevalidators.pop();\n }\n };\n};\n\n// Create a custom hook with a middleware\nconst withMiddleware = (useSWR, middleware)=>{\n return (...args)=>{\n const [key, fn, config] = normalize(args);\n const uses = (config.use || []).concat(middleware);\n return useSWR(key, fn, {\n ...config,\n use: uses\n });\n };\n};\n\nsetupDevTools();\n\nexport { INFINITE_PREFIX, IS_REACT_LEGACY, IS_SERVER, OBJECT, SWRConfig, SWRGlobalState, UNDEFINED, cache, compare, createCacheHelper, defaultConfig, defaultConfigOptions, getTimestamp, hasRequestAnimationFrame, initCache, internalMutate, isDocumentDefined, isFunction, isPromiseLike, isUndefined, isWindowDefined, mergeConfigs, mergeObjects, mutate, noop, normalize, preload, preset, rAF, events as revalidateEvents, serialize, slowConnection, stableHash, subscribeCallback, useIsomorphicLayoutEffect, useSWRConfig, withArgs, withMiddleware };\n","import 'client-only';\nimport ReactExports, { useRef, useMemo, useCallback, useDebugValue } from 'react';\nimport { useSyncExternalStore } from 'use-sync-external-store/shim/index.js';\nimport { serialize, OBJECT, SWRConfig as SWRConfig$1, defaultConfig, withArgs, SWRGlobalState, createCacheHelper, isUndefined, getTimestamp, UNDEFINED, isFunction, revalidateEvents, internalMutate, useIsomorphicLayoutEffect, subscribeCallback, IS_SERVER, rAF, IS_REACT_LEGACY, mergeObjects } from 'swr/_internal';\nexport { mutate, preload, useSWRConfig } from 'swr/_internal';\n\nconst unstable_serialize = (key)=>serialize(key)[0];\n\n/// <reference types=\"react/experimental\" />\nconst use = ReactExports.use || ((promise)=>{\n if (promise.status === 'pending') {\n throw promise;\n } else if (promise.status === 'fulfilled') {\n return promise.value;\n } else if (promise.status === 'rejected') {\n throw promise.reason;\n } else {\n promise.status = 'pending';\n promise.then((v)=>{\n promise.status = 'fulfilled';\n promise.value = v;\n }, (e)=>{\n promise.status = 'rejected';\n promise.reason = e;\n });\n throw promise;\n }\n});\nconst WITH_DEDUPE = {\n dedupe: true\n};\nconst useSWRHandler = (_key, fetcher, config)=>{\n const { cache, compare, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData } = config;\n const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache);\n // `key` is the identifier of the SWR internal state,\n // `fnArg` is the argument/arguments parsed from the key, which will be passed\n // to the fetcher.\n // All of them are derived from `_key`.\n const [key, fnArg] = serialize(_key);\n // If it's the initial render of this hook.\n const initialMountedRef = useRef(false);\n // If the hook is unmounted already. This will be used to prevent some effects\n // to be called after unmounting.\n const unmountedRef = useRef(false);\n // Refs to keep the key and config.\n const keyRef = useRef(key);\n const fetcherRef = useRef(fetcher);\n const configRef = useRef(config);\n const getConfig = ()=>configRef.current;\n const isActive = ()=>getConfig().isVisible() && getConfig().isOnline();\n const [getCache, setCache, subscribeCache, getInitialCache] = createCacheHelper(cache, key);\n const stateDependencies = useRef({}).current;\n const fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData;\n const isEqual = (prev, current)=>{\n for(const _ in stateDependencies){\n const t = _;\n if (t === 'data') {\n if (!compare(prev[t], current[t])) {\n if (!isUndefined(prev[t])) {\n return false;\n }\n if (!compare(returnedData, current[t])) {\n return false;\n }\n }\n } else {\n if (current[t] !== prev[t]) {\n return false;\n }\n }\n }\n return true;\n };\n const getSnapshot = useMemo(()=>{\n const shouldStartRequest = (()=>{\n if (!key) return false;\n if (!fetcher) return false;\n // If `revalidateOnMount` is set, we take the value directly.\n if (!isUndefined(revalidateOnMount)) return revalidateOnMount;\n // If it's paused, we skip revalidation.\n if (getConfig().isPaused()) return false;\n if (suspense) return false;\n if (!isUndefined(revalidateIfStale)) return revalidateIfStale;\n return true;\n })();\n // Get the cache and merge it with expected states.\n const getSelectedCache = (state)=>{\n // We only select the needed fields from the state.\n const snapshot = mergeObjects(state);\n delete snapshot._k;\n if (!shouldStartRequest) {\n return snapshot;\n }\n return {\n isValidating: true,\n isLoading: true,\n ...snapshot\n };\n };\n const cachedData = getCache();\n const initialData = getInitialCache();\n const clientSnapshot = getSelectedCache(cachedData);\n const serverSnapshot = cachedData === initialData ? clientSnapshot : getSelectedCache(initialData);\n // To make sure that we are returning the same object reference to avoid\n // unnecessary re-renders, we keep the previous snapshot and use deep\n // comparison to check if we need to return a new one.\n let memorizedSnapshot = clientSnapshot;\n return [\n ()=>{\n const newSnapshot = getSelectedCache(getCache());\n const compareResult = isEqual(newSnapshot, memorizedSnapshot);\n if (compareResult) {\n // Mentally, we should always return the `memorizedSnapshot` here\n // as there's no change between the new and old snapshots.\n // However, since the `isEqual` function only compares selected fields,\n // the values of the unselected fields might be changed. That's\n // simply because we didn't track them.\n // To support the case in https://github.com/vercel/swr/pull/2576,\n // we need to update these fields in the `memorizedSnapshot` too\n // with direct mutations to ensure the snapshot is always up-to-date\n // even for the unselected fields, but only trigger re-renders when\n // the selected fields are changed.\n memorizedSnapshot.data = newSnapshot.data;\n memorizedSnapshot.isLoading = newSnapshot.isLoading;\n memorizedSnapshot.isValidating = newSnapshot.isValidating;\n memorizedSnapshot.error = newSnapshot.error;\n return memorizedSnapshot;\n } else {\n memorizedSnapshot = newSnapshot;\n return newSnapshot;\n }\n },\n ()=>serverSnapshot\n ];\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n cache,\n key\n ]);\n // Get the current state that SWR should return.\n const cached = useSyncExternalStore(useCallback((callback)=>subscribeCache(key, (current, prev)=>{\n if (!isEqual(prev, current)) callback();\n }), // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n cache,\n key\n ]), getSnapshot[0], getSnapshot[1]);\n const isInitialMount = !initialMountedRef.current;\n const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0;\n const cachedData = cached.data;\n const data = isUndefined(cachedData) ? fallback : cachedData;\n const error = cached.error;\n // Use a ref to store previously returned data. Use the initial data as its initial value.\n const laggyDataRef = useRef(data);\n const returnedData = keepPreviousData ? isUndefined(cachedData) ? laggyDataRef.current : cachedData : data;\n // - Suspense mode and there's stale data for the initial render.\n // - Not suspense mode and there is no fallback data and `revalidateIfStale` is enabled.\n // - `revalidateIfStale` is enabled but `data` is not defined.\n const shouldDoInitialRevalidation = (()=>{\n // if a key already has revalidators and also has error, we should not trigger revalidation\n if (hasRevalidator && !isUndefined(error)) return false;\n // If `revalidateOnMount` is set, we take the value directly.\n if (isInitialMount && !isUndefined(revalidateOnMount)) return revalidateOnMount;\n // If it's paused, we skip revalidation.\n if (getConfig().isPaused()) return false;\n // Under suspense mode, it will always fetch on render if there is no\n // stale data so no need to revalidate immediately mount it again.\n // If data exists, only revalidate if `revalidateIfStale` is true.\n if (suspense) return isUndefined(data) ? false : revalidateIfStale;\n // If there is no stale data, we need to revalidate when mount;\n // If `revalidateIfStale` is set to true, we will always revalidate.\n return isUndefined(data) || revalidateIfStale;\n })();\n // Resolve the default validating state:\n // If it's able to validate, and it should revalidate when mount, this will be true.\n const defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation);\n const isValidating = isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating;\n const isLoading = isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading;\n // The revalidation function is a carefully crafted wrapper of the original\n // `fetcher`, to correctly handle the many edge cases.\n const revalidate = useCallback(async (revalidateOpts)=>{\n const currentFetcher = fetcherRef.current;\n if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {\n return false;\n }\n let newData;\n let startAt;\n let loading = true;\n const opts = revalidateOpts || {};\n // If there is no ongoing concurrent request, or `dedupe` is not set, a\n // new request should be initiated.\n const shouldStartNewRequest = !FETCH[key] || !opts.dedupe;\n /*\n For React 17\n Do unmount check for calls:\n If key has changed during the revalidation, or the component has been\n unmounted, old dispatch and old event callbacks should not take any\n effect\n\n For React 18\n only check if key has changed\n https://github.com/reactwg/react-18/discussions/82\n */ const callbackSafeguard = ()=>{\n if (IS_REACT_LEGACY) {\n return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;\n }\n return key === keyRef.current;\n };\n // The final state object when the request finishes.\n const finalState = {\n isValidating: false,\n isLoading: false\n };\n const finishRequestAndUpdateState = ()=>{\n setCache(finalState);\n };\n const cleanupState = ()=>{\n // Check if it's still the same request before deleting it.\n const requestInfo = FETCH[key];\n if (requestInfo && requestInfo[1] === startAt) {\n delete FETCH[key];\n }\n };\n // Start fetching. Change the `isValidating` state, update the cache.\n const initialState = {\n isValidating: true\n };\n // It is in the `isLoading` state, if and only if there is no cached data.\n // This bypasses fallback data and laggy data.\n if (isUndefined(getCache().data)) {\n initialState.isLoading = true;\n }\n try {\n if (shouldStartNewRequest) {\n setCache(initialState);\n // If no cache is being rendered currently (it shows a blank page),\n // we trigger the loading slow event.\n if (config.loadingTimeout && isUndefined(getCache().data)) {\n setTimeout(()=>{\n if (loading && callbackSafeguard()) {\n getConfig().onLoadingSlow(key, config);\n }\n }, config.loadingTimeout);\n }\n // Start the request and save the timestamp.\n // Key must be truthy if entering here.\n FETCH[key] = [\n currentFetcher(fnArg),\n getTimestamp()\n ];\n }\n [newData, startAt] = FETCH[key];\n newData = await newData;\n if (shouldStartNewRequest) {\n // If the request isn't interrupted, clean it up after the\n // deduplication interval.\n setTimeout(cleanupState, config.dedupingInterval);\n }\n // If there're other ongoing request(s), started after the current one,\n // we need to ignore the current one to avoid possible race conditions:\n // req1------------------>res1 (current one)\n // req2---------------->res2\n // the request that fired later will always be kept.\n // The timestamp maybe be `undefined` or a number\n if (!FETCH[key] || FETCH[key][1] !== startAt) {\n if (shouldStartNewRequest) {\n if (callbackSafeguard()) {\n getConfig().onDiscarded(key);\n }\n }\n return false;\n }\n // Clear error.\n finalState.error = UNDEFINED;\n // If there're other mutations(s), that overlapped with the current revalidation:\n // case 1:\n // req------------------>res\n // mutate------>end\n // case 2:\n // req------------>res\n // mutate------>end\n // case 3:\n // req------------------>res\n // mutate-------...---------->\n // we have to ignore the revalidation result (res) because it's no longer fresh.\n // meanwhile, a new revalidation should be triggered when the mutation ends.\n const mutationInfo = MUTATION[key];\n if (!isUndefined(mutationInfo) && // case 1\n (startAt <= mutationInfo[0] || // case 2\n startAt <= mutationInfo[1] || // case 3\n mutationInfo[1] === 0)) {\n finishRequestAndUpdateState();\n if (shouldStartNewRequest) {\n if (callbackSafeguard()) {\n getConfig().onDiscarded(key);\n }\n }\n return false;\n }\n // Deep compare with the latest state to avoid extra re-renders.\n // For local state, compare and assign.\n const cacheData = getCache().data;\n // Since the compare fn could be custom fn\n // cacheData might be different from newData even when compare fn returns True\n finalState.data = compare(cacheData, newData) ? cacheData : newData;\n // Trigger the successful callback if it's the original request.\n if (shouldStartNewRequest) {\n if (callbackSafeguard()) {\n getConfig().onSuccess(newData, key, config);\n }\n }\n } catch (err) {\n cleanupState();\n const currentConfig = getConfig();\n const { shouldRetryOnError } = currentConfig;\n // Not paused, we continue handling the error. Otherwise, discard it.\n if (!currentConfig.isPaused()) {\n // Get a new error, don't use deep comparison for errors.\n finalState.error = err;\n // Error event and retry logic. Only for the actual request, not\n // deduped ones.\n if (shouldStartNewRequest && callbackSafeguard()) {\n currentConfig.onError(err, key, currentConfig);\n if (shouldRetryOnError === true || isFunction(shouldRetryOnError) && shouldRetryOnError(err)) {\n if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) {\n // If it's inactive, stop. It will auto-revalidate when\n // refocusing or reconnecting.\n // When retrying, deduplication is always enabled.\n currentConfig.onErrorRetry(err, key, currentConfig, (_opts)=>{\n const revalidators = EVENT_REVALIDATORS[key];\n if (revalidators && revalidators[0]) {\n revalidators[0](revalidateEvents.ERROR_REVALIDATE_EVENT, _opts);\n }\n }, {\n retryCount: (opts.retryCount || 0) + 1,\n dedupe: true\n });\n }\n }\n }\n }\n }\n // Mark loading as stopped.\n loading = false;\n // Update the current hook's state.\n finishRequestAndUpdateState();\n return true;\n }, // `setState` is immutable, and `eventsCallback`, `fnArg`, and\n // `keyValidating` are depending on `key`, so we can exclude them from\n // the deps array.\n //\n // FIXME:\n // `fn` and `config` might be changed during the lifecycle,\n // but they might be changed every render like this.\n // `useSWR('key', () => fetch('/api/'), { suspense: true })`\n // So we omit the values from the deps array\n // even though it might cause unexpected behaviors.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n key,\n cache\n ]);\n // Similar to the global mutate but bound to the current cache and key.\n // `cache` isn't allowed to change during the lifecycle.\n const boundMutate = useCallback(// Use callback to make sure `keyRef.current` returns latest result every time\n (...args)=>{\n return internalMutate(cache, keyRef.current, ...args);\n }, // eslint-disable-next-line react-hooks/exhaustive-deps\n []);\n // The logic for updating refs.\n useIsomorphicLayoutEffect(()=>{\n fetcherRef.current = fetcher;\n configRef.current = config;\n // Handle laggy data updates. If there's cached data of the current key,\n // it'll be the correct reference.\n if (!isUndefined(cachedData)) {\n laggyDataRef.current = cachedData;\n }\n });\n // After mounted or key changed.\n useIsomorphicLayoutEffect(()=>{\n if (!key) return;\n const softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE);\n // Expose revalidators to global event listeners. So we can trigger\n // revalidation from the outside.\n let nextFocusRevalidatedAt = 0;\n const onRevalidate = (type, opts = {})=>{\n if (type == revalidateEvents.FOCUS_EVENT) {\n const now = Date.now();\n if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {\n nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;\n softRevalidate();\n }\n } else if (type == revalidateEvents.RECONNECT_EVENT) {\n if (getConfig().revalidateOnReconnect && isActive()) {\n softRevalidate();\n }\n } else if (type == revalidateEvents.MUTATE_EVENT) {\n return revalidate();\n } else if (type == revalidateEvents.ERROR_REVALIDATE_EVENT) {\n return revalidate(opts);\n }\n return;\n };\n const unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);\n // Mark the component as mounted and update corresponding refs.\n unmountedRef.current = false;\n keyRef.current = key;\n initialMountedRef.current = true;\n // Keep the original key in the cache.\n setCache({\n _k: fnArg\n });\n // Trigger a revalidation\n if (shouldDoInitialRevalidation) {\n if (isUndefined(data) || IS_SERVER) {\n // Revalidate immediately.\n softRevalidate();\n } else {\n // Delay the revalidate if we have data to return so we won't block\n // rendering.\n rAF(softRevalidate);\n }\n }\n return ()=>{\n // Mark it as unmounted.\n unmountedRef.current = true;\n unsubEvents();\n };\n }, [\n key\n ]);\n // Polling\n useIsomorphicLayoutEffect(()=>{\n let timer;\n function next() {\n // Use the passed interval\n // ...or invoke the function with the updated data to get the interval\n const interval = isFunction(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval;\n // We only start the next interval if `refreshInterval` is not 0, and:\n // - `force` is true, which is the start of polling\n // - or `timer` is not 0, which means the effect wasn't canceled\n if (interval && timer !== -1) {\n timer = setTimeout(execute, interval);\n }\n }\n function execute() {\n // Check if it's OK to execute:\n // Only revalidate when the page is visible, online, and not errored.\n if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) {\n revalidate(WITH_DEDUPE).then(next);\n } else {\n // Schedule the next interval to check again.\n next();\n }\n }\n next();\n return ()=>{\n if (timer) {\n clearTimeout(timer);\n timer = -1;\n }\n };\n }, [\n refreshInterval,\n refreshWhenHidden,\n refreshWhenOffline,\n key\n ]);\n // Display debug info in React DevTools.\n useDebugValue(returnedData);\n // In Suspense mode, we can't return the empty `data` state.\n // If there is an `error`, the `error` needs to be thrown to the error boundary.\n // If there is no `error`, the `revalidation` promise needs to be thrown to\n // the suspense boundary.\n if (suspense && isUndefined(data) && key) {\n // SWR should throw when trying to use Suspense on the server with React 18,\n // without providing any initial data. See:\n // https://github.com/vercel/swr/issues/1832\n if (!IS_REACT_LEGACY && IS_SERVER) {\n throw new Error('Fallback data is required when using suspense in SSR.');\n }\n // Always update fetcher and config refs even with the Suspense mode.\n fetcherRef.current = fetcher;\n configRef.current = config;\n unmountedRef.current = false;\n const req = PRELOAD[key];\n if (!isUndefined(req)) {\n const promise = boundMutate(req);\n use(promise);\n }\n if (isUndefined(error)) {\n const promise = revalidate(WITH_DEDUPE);\n if (!isUndefined(returnedData)) {\n promise.status = 'fulfilled';\n promise.value = true;\n }\n use(promise);\n } else {\n throw error;\n }\n }\n return {\n mutate: boundMutate,\n get data () {\n stateDependencies.data = true;\n return returnedData;\n },\n get error () {\n stateDependencies.error = true;\n return error;\n },\n get isValidating () {\n stateDependencies.isValidating = true;\n return isValidating;\n },\n get isLoading () {\n stateDependencies.isLoading = true;\n return isLoading;\n }\n };\n};\nconst SWRConfig = OBJECT.defineProperty(SWRConfig$1, 'defaultValue', {\n value: defaultConfig\n});\n/**\n * A hook to fetch data.\n *\n * @link https://swr.vercel.app\n * @example\n * ```jsx\n * import useSWR from 'swr'\n * function Profile() {\n * const { data, error, isLoading } = useSWR('/api/user', fetcher)\n * if (error) return <div>failed to load</div>\n * if (isLoading) return <div>loading...</div>\n * return <div>hello {data.name}!</div>\n * }\n * ```\n */ const useSWR = withArgs(useSWRHandler);\n\nexport { SWRConfig, useSWR as default, unstable_serialize };\n","import useSWR from \"swr\";\nimport { useConfig } from \"./useConfig\";\nimport { useChat } from \"../ChatProvider\";\n\nfunction usePreludeData() {\n const { api } = useChat();\n const config = useConfig();\n return useSWR([config.config.apiUrl], api.widgetPrelude);\n}\n\nexport { usePreludeData };\n","import { useChat } from \"../ChatProvider\";\n\nexport function useLocale() {\n const { locale } = useChat();\n return locale;\n}","import { useEffect, useMemo, useState } from 'react';\nimport { useChat } from '../ChatProvider';\nimport { v4 } from 'uuid';\n\nconst uploadAbortControllers: Map<string, AbortController> = new Map();\n\ninterface FileWithProgress {\n status: 'pending' | 'uploading' | 'success' | 'error';\n id: string;\n file: File;\n fileUrl?: string;\n progress: number;\n error?: string;\n}\n\nfunction useUploadFiles() {\n const [files, setFiles] = useState<FileWithProgress[]>([]);\n const { api } = useChat();\n function appendFiles(files: File[]) {\n const newFiles = files.map((file) => ({\n file,\n id: v4(),\n status: 'pending' as const,\n progress: 0\n }));\n\n setFiles((prev) => [...prev, ...newFiles]);\n newFiles.forEach(uploadFile);\n }\n\n function updateFileById(id: string, update: Partial<FileWithProgress>) {\n setFiles((prev) =>\n prev.map((f) => (f.id === id ? { ...f, ...update } : f))\n );\n }\n\n function removeFileById(id: string) {\n setFiles((prev) => prev.filter((f) => f.id !== id));\n }\n\n const uploadFile = async (fileItem: FileWithProgress) => {\n const controller = new AbortController();\n uploadAbortControllers.set(fileItem.id, controller);\n\n setFiles((prev) =>\n prev.map((f) =>\n f.id === fileItem.id ? { ...f, status: 'uploading', progress: 0 } : f\n )\n );\n\n const { data, error } = await api.uploadFile({\n file: fileItem,\n abortSignal: controller.signal\n });\n\n if (data) {\n updateFileById(fileItem.id, {\n status: 'success',\n fileUrl: data.fileUrl,\n progress: 100\n });\n } else {\n if (!controller.signal.aborted) {\n updateFileById(fileItem.id, {\n status: 'error',\n error: error.message || 'Upload failed',\n progress: 0\n });\n }\n }\n uploadAbortControllers.delete(fileItem.id);\n };\n\n const handleCancelUpload = (fileId: string) => {\n const controller = uploadAbortControllers.get(fileId);\n if (controller) {\n controller.abort();\n uploadAbortControllers.delete(fileId);\n }\n removeFileById(fileId);\n };\n\n const successFiles = useMemo(() => {\n return files.filter((f) => f.status === 'success' && f.fileUrl);\n }, [files]);\n\n function emptyTheFiles() {\n uploadAbortControllers.forEach((controller) => controller.abort());\n uploadAbortControllers.clear();\n setFiles([]);\n }\n\n useEffect(() => {\n return () => {\n uploadAbortControllers.forEach((controller) => controller.abort());\n uploadAbortControllers.clear();\n };\n }, []);\n\n return {\n allFiles: files,\n appendFiles,\n handleCancelUpload,\n successFiles,\n emptyTheFiles,\n getFileById: (id: string) => files.find((f) => f.id === id),\n getUploadProgress: (id: string) =>\n files.find((f) => f.id === id)?.progress ?? 0,\n getUploadStatus: (id: string) => files.find((f) => f.id === id)?.status,\n hasErrors: files.some((f) => f.status === 'error'),\n isUploading: files.some((f) => f.status === 'uploading')\n };\n}\n\nexport { useUploadFiles, type FileWithProgress };\n","import { useChat } from '../ChatProvider';\nimport { usePubsub } from './usePubsub';\n\nexport function useContact() {\n const { chat } = useChat();\n const contactState = usePubsub(chat.contactState);\n\n return {\n contactState,\n contactManager: chat.contactManager\n };\n}\n"],"names":["createSafeContext","init","context","createContext","ctx","useContext","ComponentRegistry","opts","__publicField","data","components","c","com","index","key","getFallback","_a","arLocale","deLocale","enLocale","frLocale","nlLocale","ptLocale","locales","getStr","lang","locale","defaultStorage","value","defaultPlatform","createLogger","widgetSettingsSchema","z","useInitializeChat","options","customPlatform","widgetSettings","setWidgetSettings","useState","_b","platform","useMemo","config","createConfig","useEffect","isStorageAvailable","settings","parsedSettings","prev","error","api","ApiCaller","chat","createChat","useChat","SafeProvider","ChatProvider","children","componentStore","pfx","jsx","usePubsub","p","useSyncExternalStore","useChatState","useChatSession","chatSession","useConfig","require$$0","h","a","b","k","l","m","n","q","d","f","g","r","t","u","useSyncExternalStoreShim_production_min","React","ReactSharedInternals","format","_len2","args","_key2","printWarning","level","ReactDebugCurrentFrame","stack","argsWithFormat","item","is","x","y","objectIs","useLayoutEffect","useDebugValue","didWarnOld18Alpha","didWarnUncachedGetSnapshot","subscribe","getSnapshot","getServerSnapshot","cachedValue","_useState","inst","forceUpdate","checkIfSnapshotChanged","handleStoreChange","latestGetSnapshot","prevValue","nextValue","useSyncExternalStore$1","canUseDOM","isServerEnvironment","shim","useSyncExternalStore$2","useSyncExternalStoreShim_development","shimModule","require$$1","noop","UNDEFINED","OBJECT","isUndefined","v","isFunction","mergeObjects","isPromiseLike","table","counter","stableHash","arg","type","constructor","isDate","result","keys","SWRGlobalState","EMPTY_CACHE","INITIAL_CACHE","STR_UNDEFINED","isWindowDefined","isDocumentDefined","hasRequestAnimationFrame","createCacheHelper","cache","state","info","online","isOnline","onWindowEvent","offWindowEvent","isVisible","visibilityState","initFocus","callback","initReconnect","onOnline","onOffline","preset","defaultConfigOptions","IS_REACT_LEGACY","IS_SERVER","rAF","useIsomorphicLayoutEffect","navigatorConnection","slowConnection","serialize","__timestamp","getTimestamp","FOCUS_EVENT","RECONNECT_EVENT","MUTATE_EVENT","ERROR_REVALIDATE_EVENT","events","internalMutate","_key","_data","_opts","populateCache","rollbackOnErrorOption","optimisticData","rollbackOnError","throwOnError","keyFilter","matchedKeys","it","mutateByKey","_k","get","set","EVENT_REVALIDATORS","MUTATION","FETCH","PRELOAD","startRevalidate","revalidators","beforeMutationTs","hasOptimisticData","displayedData","currentData","committedData","err","populateCachedData","revalidateAllKeys","initCache","provider","mutate","unmount","subscriptions","subs","setter","fn","initProvider","releaseFocus","releaseReconnect","onErrorRetry","_","__","revalidate","maxRetryCount","currentRetryCount","timeout","compare","newData","defaultConfig","mergeConfigs","u1","f1","u2","f2","SWRConfigContext","INFINITE_PREFIX","enableDevtools","use","setupDevTools","normalize","useSWRConfig","middleware","useSWRNext","key_","fetcher_","req","BUILT_IN_MIDDLEWARE","withArgs","hook","fallbackConfig","_config","next","i","subscribeCallback","callbacks","keyedRevalidators","ReactExports","promise","e","WITH_DEDUPE","useSWRHandler","fetcher","suspense","fallbackData","revalidateOnMount","revalidateIfStale","refreshInterval","refreshWhenHidden","refreshWhenOffline","keepPreviousData","fnArg","initialMountedRef","useRef","unmountedRef","keyRef","fetcherRef","configRef","getConfig","isActive","getCache","setCache","subscribeCache","getInitialCache","stateDependencies","fallback","isEqual","current","returnedData","shouldStartRequest","getSelectedCache","snapshot","cachedData","initialData","clientSnapshot","serverSnapshot","memorizedSnapshot","newSnapshot","cached","useCallback","isInitialMount","hasRevalidator","laggyDataRef","shouldDoInitialRevalidation","defaultValidatingState","isValidating","isLoading","revalidateOpts","currentFetcher","startAt","loading","shouldStartNewRequest","callbackSafeguard","finalState","finishRequestAndUpdateState","cleanupState","requestInfo","initialState","mutationInfo","cacheData","currentConfig","shouldRetryOnError","revalidateEvents","boundMutate","softRevalidate","nextFocusRevalidatedAt","unsubEvents","now","timer","interval","execute","useSWR","usePreludeData","useLocale","uploadAbortControllers","useUploadFiles","files","setFiles","appendFiles","newFiles","file","v4","uploadFile","updateFileById","id","update","removeFileById","fileItem","controller","handleCancelUpload","fileId","successFiles","emptyTheFiles","useContact"],"mappings":";;;;;;;;AAEO,SAASA,GAA0BC,GAAe;AACvD,QAAMC,IAAUC,GAAuB,CAAA,CAAa;AAU7C,SAAA,CARgB,MAAM;AACrB,UAAAC,IAAMC,GAAWH,CAAO;AAC9B,QAAIE,MAAQ;AACJ,YAAA,IAAI,MAAM,+CAA+C;AAE1D,WAAAA;AAAA,EAAA,GAGeF,EAAQ,QAAQ;AAC1C;ACZO,MAAMI,GAAkB;AAAA,EAY7B,YAAYC,GAA8C;AAX1D,IAAAC,GAAA,oBAAoC;AAAA,MAClC;AAAA,QACE,KAAK;AAAA,QACL,WAAW,CAACC,MAAS;AAAA,MACvB;AAAA,MACA;AAAA,QACE,KAAK;AAAA,QACL,WAAW,CAACA,MAAS;AAAA,MACvB;AAAA,IAAA;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ACc,MAAeA,EAAW,MAAO,CAAA,GACjEd,EAAuB,MAAM;AAAA,EAAA,GAE9B,CAAE,CAAA,GAEE;AAAA,IACL,UAAUE;AAAA,IACV,aAAAE;AAAA,IACA,oBAAAW;AAAA,IACA,cAAAE;AAAA,IACA,eAAAC;AAAA,IACA,aAAa,CAACR,MAAeR,EAAM,KAAK,CAAClQ,MAAMA,EAAE,OAAO0Q,CAAE;AAAA,IAC1D,mBAAmB,CAACA;;AAClB,eAAAxU,IAAAgU,EAAM,KAAK,CAAClQ,MAAMA,EAAE,OAAO0Q,CAAE,MAA7B,gBAAAxU,EAAgC,aAAY;AAAA;AAAA,IAC9C,iBAAiB,CAACwU,MAAe;;AAAA,cAAAxU,IAAAgU,EAAM,KAAK,CAAClQ,MAAMA,EAAE,OAAO0Q,CAAE,MAA7B,gBAAAxU,EAAgC;AAAA;AAAA,IACjE,WAAWgU,EAAM,KAAK,CAAClQ,MAAMA,EAAE,WAAW,OAAO;AAAA,IACjD,aAAakQ,EAAM,KAAK,CAAClQ,MAAMA,EAAE,WAAW,WAAW;AAAA,EAAA;AAE3D;AC7GO,SAASmR,KAAa;AACnB,QAAA,EAAE,MAAA7S,MAASE;AAGV,SAAA;AAAA,IACH,cAHiBO,GAAUT,EAAK,YAAY;AAAA,IAI5C,gBAAgBA,EAAK;AAAA,EAAA;AAE7B;","x_google_ignoreList":[14,15,16,17,18]}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var X=Object.defineProperty;var k=s=>{throw TypeError(s)};var K=(s,e,t)=>e in s?X(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var E=(s,e,t)=>K(s,typeof e!="symbol"?e+"":e,t),$=(s,e,t)=>e.has(s)||k("Cannot "+t);var h=(s,e,t)=>($(s,e,"read from private field"),t?t.call(s):e.get(s)),F=(s,e,t)=>e.has(s)?k("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),v=(s,e,t,n)=>($(s,e,"write to private field"),n?n.call(s,t):e.set(s,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("lodash.isequal"),I=require("./genUuid-DdeSE04H.cjs");require("whatwg-fetch");var j=(s=>(s.INIT="init",s.STATE_CHANGE="stateChange",s.BEFORE_UPDATE="beforeUpdate",s.AFTER_UPDATE="afterUpdate",s.DESTROY="destroy",s.ERROR="error",s))(j||{}),P,M;class U{constructor(e){E(this,"subscribers",new Set);F(this,P);E(this,"initialState");F(this,M);E(this,"lifecycleListeners",new Map);E(this,"emitLifecycle",(e,t)=>{const n=this.lifecycleListeners.get(e);if(n){const f={type:e,timestamp:Date.now(),data:t};n.forEach(i=>{try{i(f)}catch(r){console.error("Error in lifecycle listener:",r)}})}});E(this,"notifySubscribers",e=>{Array.from(this.subscribers).forEach(n=>{try{n(e)}catch(f){this.emitLifecycle("error",{error:f}),console.error("Error in subscriber:",f)}})});E(this,"subscribe",e=>(this.subscribers.add(e),()=>{this.subscribers.delete(e)}));E(this,"onLifecycle",(e,t)=>{this.lifecycleListeners.has(e)||this.lifecycleListeners.set(e,new Set);const n=this.lifecycleListeners.get(e);return n.add(t),()=>{n.delete(t),n.size===0&&this.lifecycleListeners.delete(e)}});E(this,"getState",()=>h(this,P));E(this,"setState",e=>{this.emitLifecycle("beforeUpdate",{previousState:h(this,P),nextState:e}),V(h(this,P),e)||(v(this,P,e),v(this,M,Date.now()),this.emitLifecycle("stateChange",{state:e}),this.notifySubscribers(e)),this.emitLifecycle("afterUpdate",{state:e})});E(this,"setStatePartial",e=>{if(e==null)return;const t={...h(this,P),...e};this.setState(t)});E(this,"clear",()=>{this.emitLifecycle("destroy"),this.subscribers=new Set,this.lifecycleListeners=new Map});E(this,"reset",()=>{this.setState(this.initialState)});E(this,"lastUpdated",()=>h(this,M));v(this,P,e),this.initialState=e,v(this,M,Date.now()),this.emitLifecycle("init",{initialState:h(this,P)})}}P=new WeakMap,M=new WeakMap;function z(s){return new U(s)}class w extends Error{constructor(e){super(e),this.name="OpenCXError"}}class Y extends w{constructor(e="Connection failed"){super(e),this.name="ConnectionError"}}class Q extends w{constructor(e="Authentication failed"){super(e),this.name="AuthenticationError"}}class B extends w{constructor(e="Session error occurred"){super(e),this.name="SessionError"}}class W extends B{constructor(e="Session not defined"){super(e),this.name="SessionNotDefinedError"}}class Z extends w{constructor(e="Transport error occurred"){super(e),this.name="TransportError"}}class ee extends w{constructor(e="File upload failed"){super(e),this.name="FileUploadError"}}class H extends w{constructor(e="Storage is not available"){super(e),this.name="StorageNotAvailableError"}}class J extends w{constructor(e="External ID is not defined"){super(e),this.name="ExternalIdNotDefinedError"}}function O(s){if(!s)return!1;try{return typeof s.isAvailable=="function"?s.isAvailable():!0}catch{return!1}}async function N(s,e){try{return{success:!0,result:await s(),error:null}}catch(t){return console.error(e,t),{success:!1,result:null,error:{message:t instanceof Error?t.message||"Unknown error":(t==null?void 0:t.toString())||"Unknown error",code:"STORAGE_OPERATION_FAILED",context:e}}}}function se(s={}){const{level:e="info",prefix:t="[openCx]",enabled:n=!0}=s;let f=e;const i={debug:0,info:1,warn:2,error:3};function r(u){return n&&i[u]>=i[f]}function l(u){return`${t} ${u}`}function c(u){return u.map(a=>{if(a instanceof Error)return{name:a.name,message:a.message,stack:a.stack};if(typeof a=="object")try{return JSON.stringify(a,null,2)}catch{return a}return a})}return{debug(u,...a){r("debug")&&console.debug(l(u),...c(a))},info(u,...a){r("info")&&console.info(l(u),...c(a))},warn(u,...a){r("warn")&&console.warn(l(u),...c(a))},error(u,...a){r("error")&&console.error(l(u),...c(a))},setLevel(u){f=u}}}function te(s){if(!s)return!1;try{return typeof s.isAvailable=="function"?s.isAvailable():!0}catch{return!1}}async function re(s,e){try{return await s(),{success:!0,error:null}}catch(t){return console.error(e,t),{success:!1,error:{message:t instanceof Error?t.message||"Unknown error":(t==null?void 0:t.toString())||"Unknown error",code:"AUDIO_OPERATION_FAILED",context:e}}}}const C={SESSION:1e4,MESSAGES:5e3};function q(s){const e={id:s.publicId,timestamp:s.sentAt||"",attachments:s.attachments||void 0};return s.sender.kind==="user"?{...e,type:"FROM_USER",content:s.content.text||"",deliveredAt:s.sentAt||""}:s.sender.kind==="agent"?{id:s.publicId,type:"FROM_AGENT",component:s.type,data:{text:s.content.text},timestamp:s.sentAt||"",attachments:s.attachments||void 0}:{...e,type:"FROM_BOT",component:"TEXT",agent:{id:null,name:s.sender.name||"",is_ai:s.sender.kind==="ai",profile_picture:s.sender.avatar},data:{message:s.content.text}}}function ae(s,e,t){async function n(l){var o;const c=e.getState().messages;if(c.length===0){t==null||t.debug("No messages yet, fetching all history",{sessionId:l.id});const m=await s.getSessionHistory(l.id,"");m&&m.length>0&&e.setStatePartial({messages:m.map(q)});return}const u=(o=e.getState().messages.at(-1))==null?void 0:o.timestamp;t==null||t.debug("Fetching history messages after timestamp",{sessionId:l.id,lastMessageTimestamp:u,currentMessageCount:c.length});const a=await s.getSessionHistory(l.id,u);if(a&&a.length>0){const m=a.map(q).filter(p=>!c.some(y=>y.id===p.id));m.length>0&&(t==null||t.debug("Adding new messages to state",{count:m.length,messageIds:m.map(p=>p.id),messageTypes:m.map(p=>p.type)}),e.setStatePartial({messages:[...c,...m]}))}}function f(l,c){return{id:I.genUuid(),type:"FROM_USER",content:l,deliveredAt:new Date().toISOString(),attachments:c,timestamp:new Date().toISOString()}}function i(l){if(l.success&&l.autopilotResponse)return{type:"FROM_BOT",id:l.autopilotResponse.id||I.genUuid(),timestamp:new Date().toISOString(),component:"TEXT",data:{message:l.autopilotResponse.value.content}};if(l.success&&l.uiResponse){const c=l.uiResponse.value;return{type:"FROM_BOT",id:I.genUuid(),timestamp:new Date().toISOString(),component:c.name,data:c.request_response}}return null}function r(l){return{type:"FROM_BOT",id:I.genUuid(),timestamp:new Date().toISOString(),component:"TEXT",data:{message:l,variant:"error"}}}return{fetchHistoryMessages:n,addUserMessage:f,addBotMessage:i,addErrorMessage:r}}function ne(s,e,t,n,f,i){var _,x;const r=(_=i.platform)==null?void 0:_.logger;let l=null;const c=(x=i.platform)==null?void 0:x.storage,u=f.getSettings().persistSession;if(u&&!O(c))throw new H;if(u&&!f.getConfig().user.external_id)throw new J("session persistence is enabled but external id is not defined");const a=`${f.getConfig().user.external_id}:${f.getConfig().token}:session`;async function o(){if(c)try{r==null||r.debug("Attempting to restore session from storage");const d=await c.getItem(a);if(d){const g=JSON.parse(d);r==null||r.info("Session restored from storage",{sessionId:g.id}),e.setState(g),await n.fetchHistoryMessages(g),p()}}catch(d){r==null||r.error("Error restoring session from storage:",d)}}function m(){c&&(r==null||r.debug("Setting up session persistence"),e.subscribe(async d=>{try{d?(await c.setItem(a,JSON.stringify(d)),r==null||r.debug("Session persisted to storage",{sessionId:d.id})):(await c.removeItem(a),r==null||r.debug("Session removed from storage"))}catch(g){r==null||r.error("Error persisting session:",g),t.setStatePartial({error:{hasError:!0,message:g instanceof Error?g.message:"Failed to persist session",code:"SESSION_PERSISTENCE_FAILED"}})}}))}function p(){if(l)return;r==null||r.debug("Starting polling");const d=[];d.push(setInterval(async()=>{const g=e.getState();if(g!=null&&g.id)try{const S=new Date;t.setStatePartial({polling:{...t.getState().polling,session:{isPolling:!0,lastPollTime:S.toISOString(),nextPollTime:new Date(S.getTime()+C.SESSION).toISOString(),error:{hasError:!1}}}});const R=await s.getSession(g.id);R&&e.setState(R),t.setStatePartial({polling:{...t.getState().polling,session:{...t.getState().polling.session,isPolling:!1}}})}catch(S){r==null||r.error("Error polling session:",S),t.setStatePartial({polling:{...t.getState().polling,session:{...t.getState().polling.session,isPolling:!1,error:{hasError:!0,message:S instanceof Error?S.message:"Failed to poll session",code:"SESSION_POLLING_FAILED"}}}})}},C.SESSION)),d.push(setInterval(async()=>{const g=e.getState();if(g!=null&&g.id)try{const S=new Date;t.setStatePartial({polling:{...t.getState().polling,messages:{isPolling:!0,lastPollTime:S.toISOString(),nextPollTime:new Date(S.getTime()+C.MESSAGES).toISOString(),error:{hasError:!1}}}}),await n.fetchHistoryMessages(g),t.setStatePartial({polling:{...t.getState().polling,messages:{...t.getState().polling.messages,isPolling:!1}}})}catch(S){r==null||r.error("Error polling messages:",S),t.setStatePartial({polling:{...t.getState().polling,messages:{...t.getState().polling.messages,isPolling:!1,error:{hasError:!0,message:S instanceof Error?S.message:"Failed to poll messages",code:"MESSAGES_POLLING_FAILED"}}}})}},C.MESSAGES)),l=()=>{r==null||r.debug("Stopping polling"),d.forEach(clearInterval),t.setStatePartial({polling:{session:{isPolling:!1,lastPollTime:null,nextPollTime:null,error:{hasError:!1}},messages:{isPolling:!1,lastPollTime:null,nextPollTime:null,error:{hasError:!1}}}})}}async function y(){try{r==null||r.info("Creating new session"),t.setStatePartial({loading:{isLoading:!0,reason:"creating_session"},error:{hasError:!1}});const d=await s.createSession();return r==null||r.info("Session created successfully",{sessionId:d.id}),e.setState(d),p(),d}catch(d){r==null||r.error("Failed to create session:",d);const g={hasError:!0,message:d instanceof Error?d.message:"Failed to create session",code:"SESSION_CREATION_FAILED"};return t.setStatePartial({error:g}),null}finally{t.setStatePartial({loading:{isLoading:!1,reason:null}})}}async function D(){var g;const d=e.getState();if(d!=null&&d.id)try{l&&(l(),l=null),e.setState(null),u&&c&&await c.removeItem(a),t.setState({messages:[],keyboard:null,loading:{isLoading:!1,reason:null},error:{hasError:!1},polling:{session:{isPolling:!1,lastPollTime:null,nextPollTime:null,error:{hasError:!1}},messages:{isPolling:!1,lastPollTime:null,nextPollTime:null,error:{hasError:!1}}}}),(g=i.onSessionDestroy)==null||g.call(i)}catch(S){console.error("Error clearing session:",S),t.setStatePartial({error:{hasError:!0,message:S instanceof Error?S.message:"Failed to clear session",code:"SESSION_CLEAR_FAILED"}})}}function L(d=!1){try{l&&(l(),l=null),d&&u&&c&&O(c)&&c.removeItem(a),t.setState({messages:[],keyboard:null,loading:{isLoading:!1,reason:null},error:{hasError:!1},polling:{session:{isPolling:!1,lastPollTime:null,nextPollTime:null,error:{hasError:!1}},messages:{isPolling:!1,lastPollTime:null,nextPollTime:null,error:{hasError:!1}}}}),e.setState(null),t.clear(),e.clear()}catch(g){console.error("Error in cleanup:",g),t.setStatePartial({error:{hasError:!0,message:g instanceof Error?g.message:"Failed to cleanup",code:"SESSION_CLEAR_FAILED"}})}}async function T(d){return s.getSession(d)}async function A(){const d=e.getState();if(!(d!=null&&d.id))return;const g=await T(d.id);return g&&e.setState(g),g}return u&&O(c)&&(o(),m()),{createSession:y,clearSession:D,cleanup:L,startPolling:p,fetchSession:T,refetchSession:A,sessionStorageKey:a}}function oe(s){var c;const e=(c=s.platform)==null?void 0:c.logger,t={messages:[],keyboard:null,loading:{isLoading:!1,reason:null},error:{hasError:!1},polling:{session:{isPolling:!1,lastPollTime:null,nextPollTime:null,error:{hasError:!1}},messages:{isPolling:!1,lastPollTime:null,nextPollTime:null,error:{hasError:!1}}}},n=new U(t),f=new U(null),i=ae(s.api,n,e),r=ne(s.api,f,n,i,s.config,s);async function l(u,a){var p;let o=f.getState(),m=!1;if(!(o!=null&&o.id)){if(e==null||e.debug("No active session, creating new session"),o=await r.createSession(),!o)return{success:!1,createdSession:m};m=!0}o.assignee.kind==="ai"&&(o=await r.refetchSession()??o);try{e==null||e.debug("Sending message",{sessionId:o.id}),o.assignee.kind==="ai"?n.setStatePartial({loading:{isLoading:!0,reason:"sending_message_to_bot"},error:{hasError:!1}}):n.setStatePartial({loading:{isLoading:!0,reason:"sending_message_to_agent"},error:{hasError:!1}});const y=i.addUserMessage(u.content,u.attachments||void 0),D=n.getState().messages;n.setStatePartial({messages:[...D,y]});const L=s.config.getConfig(),T=await s.api.handleMessage({uuid:u.uuid||I.genUuid(),bot_token:L.token,headers:L.headers,query_params:L.queryParams,session_id:o.id,user:L.user,...u},a);if(T.success){e==null||e.debug("Message sent successfully");const A=i.addBotMessage(T);if(A){const _=n.getState().messages;n.setStatePartial({messages:[..._,A]})}return{success:!0,createdSession:m,botMessage:A}}else{e==null||e.warn("Message send failed",T.error);const A=i.addErrorMessage(((p=T.error)==null?void 0:p.message)||"Unknown error occurred"),_=n.getState().messages;return n.setStatePartial({messages:[..._,A]}),{success:!1,createdSession:m,error:T.error}}}catch(y){return e==null||e.error("Error sending message:",y),n.setStatePartial({error:{hasError:!0,message:y instanceof Error?y.message:"Failed to send message",code:"MESSAGE_SEND_FAILED"}}),{success:!1,createdSession:m,error:y}}finally{n.setStatePartial({loading:{isLoading:!1,reason:null}})}}return{chatState:n,sessionState:f,sendMessage:l,createSession:r.createSession,clearSession:r.clearSession,cleanup:r.cleanup,initialState:t,sessionStorageKey:r.sessionStorageKey}}function ie(s){const e=s.config.getConfig();s.config.getConfig;const t=`${e.token}:contact:${e.user.external_id}`,n=O(s.platform.storage)?s.platform.storage:void 0;let f=null;n&&N(async()=>{const a=await n.getItem(t);return a?JSON.parse(a):null},"Error loading contact from storage").then(a=>{a.success&&(f=a.result)});const i=new U({contact:f,loading:{isLoading:!1,reason:null},error:{hasError:!1}});O(n)&&i.subscribe(a=>{N(async()=>{a.contact?await n.setItem(t,JSON.stringify(a.contact)):n.removeItem(t)},"Error persisting contact state").then(o=>{o.success||i.setStatePartial({error:{hasError:!0,message:o.error.message,code:"CONTACT_PERSISTENCE_FAILED"}})})});async function r(){try{if(i.setStatePartial({loading:{isLoading:!0,reason:"loading_contact"},error:{hasError:!1}}),n){const a=await N(async()=>{const o=await n.getItem(t);return o?JSON.parse(o):null},"Error loading contact");if(!a.success)throw a.error;return i.setStatePartial({contact:a.result,error:{hasError:!1}}),a.result}return i.getState().contact}catch(a){return i.setStatePartial({error:{hasError:!0,message:a instanceof Error?a.message:"Failed to load contact",code:"CONTACT_LOAD_FAILED"}}),null}finally{i.setStatePartial({loading:{isLoading:!1,reason:null}})}}async function l(a){try{i.setStatePartial({loading:{isLoading:!0,reason:"saving_contact"},error:{hasError:!1}});const o=i.getState().contact,m={id:a.id||(o==null?void 0:o.id)||"",name:a.name??(o==null?void 0:o.name)??null,created_at:a.created_at||(o==null?void 0:o.created_at)||new Date().toISOString(),avatar_url:a.avatar_url??(o==null?void 0:o.avatar_url)??null,email:a.email??(o==null?void 0:o.email)??null};if(O(n)){const p=await N(()=>n.setItem(t,JSON.stringify(m)),"Error saving contact");if(!p.success)throw p.error}return i.setStatePartial({contact:m,error:{hasError:!1}}),m}catch(o){return i.setStatePartial({error:{hasError:!0,message:o instanceof Error?o.message:"Failed to save contact",code:"CONTACT_SAVE_FAILED"}}),null}finally{i.setStatePartial({loading:{isLoading:!1,reason:null}})}}function c(){var o;return!((o=i.getState().contact)!=null&&o.id)&&e.collectUserData?{should:!0,reason:"No contact id and collectUserData is true"}:{should:!1}}async function u(){try{if(i.setStatePartial({loading:{isLoading:!0,reason:"cleaning_up"},error:{hasError:!1}}),n){const a=await N(()=>n.removeItem(t),"Error removing contact data");if(!a.success)throw a.error}i.setState({contact:null,loading:{isLoading:!1,reason:null},error:{hasError:!1}}),i.clear()}catch(a){console.error("Error cleaning up contact:",a),i.setStatePartial({error:{hasError:!0,message:a instanceof Error?a.message:"Failed to cleanup contact data",code:"CONTACT_CLEANUP_FAILED"}})}finally{i.setStatePartial({loading:{isLoading:!1,reason:null}})}}return{contactState:i,shouldCollectData:c,loadContact:r,saveContact:l,cleanup:u}}const le={messageArrived:"https://cloud.opencopilot.so/sfx/notification3.mp3"},G={primaryColor:"hsl(211,65%,59%)",triggerOffset:"20px"},ce=1e3*3;function ue(s){var t,n,f,i,r,l,c,u,a;if(!s.token)throw new Error("Token is required");if(s.pollingInterval&&s.pollingInterval<ce)throw new Error("Polling interval must be at least 3 seconds");const e={...s,collectUserData:s.collectUserData??!1,apiUrl:s.apiUrl??"https://api.open.cx/backend",pollingInterval:s.pollingInterval??3e3,headers:s.headers??{},queryParams:s.queryParams??{},pathParams:s.pathParams??{},bot:{name:((t=s.bot)==null?void 0:t.name)??"Bot",avatarUrl:(n=s.bot)==null?void 0:n.avatarUrl,id:((f=s.bot)==null?void 0:f.id)??null,is_ai:((i=s.bot)==null?void 0:i.is_ai)??!0},contactToken:s.contactToken,debug:s.debug??!1,language:s.language??"en",user:s.user??{},soundEffectFiles:{messageArrived:((r=s.soundEffectFiles)==null?void 0:r.messageArrived)??le.messageArrived},theme:{primaryColor:((l=s.theme)==null?void 0:l.primaryColor)??G.primaryColor,triggerOffset:((c=s.theme)==null?void 0:c.triggerOffset)??G.triggerOffset},settings:{persistSession:((u=s.settings)==null?void 0:u.persistSession)??!1,useSoundEffects:((a=s.settings)==null?void 0:a.useSoundEffects)??!1}};return{getConfig:()=>e,getApiConfig:()=>({apiUrl:e.apiUrl,token:e.token,headers:e.headers,queryParams:e.queryParams,pathParams:e.pathParams}),getBotConfig:()=>e.bot,getThemeConfig:()=>e.theme,getSettings:()=>e.settings,getSoundEffects:()=>e.soundEffectFiles,getUser:()=>e.user,getLanguage:()=>e.language,getDebugMode:()=>e.debug}}function fe(s={},e=globalThis.fetch){const t=[],n=[],f=[],i=async(r,l={})=>{let c={...s,...l,headers:{...s.headers,...l.headers}};try{for(const m of t)c=await m(c);const u=c.params?"?"+new URLSearchParams(c.params).toString():"",a=c.baseURL?`${c.baseURL}${r}${u}`.replace(/([^:]\/)\/+/g,"$1"):`${r}${u}`;let o=await e(a,c);for(const m of n)o=await m(o);return o}catch(u){let a=u;for(const o of f)a=await o(a);throw a}};return i.interceptors={request:{use:r=>(t.push(r),t.length-1),eject:r=>{t.splice(r,1)}},response:{use:(r,l)=>(n.push(r),l&&f.push(l),n.length-1),eject:r=>{n.splice(r,1),f.splice(r,1)}}},i}var b;class de{constructor(e){F(this,b);this.options=e;const t=this.options.config.user,n={claim:"",value:""};t!=null&&t.email?(n.claim="email",n.value=t.email):t!=null&&t.phone&&(n.claim="phone",n.value=t.phone);const f={"X-Bot-Token":this.options.config.token,"X-Consumer-Id":`${n.claim}:${n.value}`,"Content-Type":"application/json",Accept:"application/json"};this.options.config.contactToken&&(f.Authorization=`Bearer ${this.options.config.contactToken}`),v(this,b,fe({baseURL:`${this.options.config.apiUrl}/widget/v2`,headers:f}))}async me(){return(await h(this,b).call(this,"/me")).json()}async widgetPrelude(){return(await h(this,b).call(this,"/prelude")).json()}async handleMessage(e,t){return(await h(this,b).call(this,"/chat/send",{method:"POST",body:JSON.stringify(e),signal:t})).json()}async getSessionHistory(e,t){const n=new URLSearchParams({lastMessageTimestamp:t||""}),f=`/session/history/${e}?${n.toString()}`;return(await h(this,b).call(this,f,{method:"GET"})).json()}async createSession(){return(await h(this,b).call(this,"/create-session",{method:"POST"})).json()}async getSession(e){return(await h(this,b).call(this,`/session/${e}`,{method:"GET"})).json()}}b=new WeakMap;exports.MessageTypeEnum=I.MessageTypeEnum;exports.chatAttachmentSchema=I.chatAttachmentSchema;exports.ApiCaller=de;exports.AuthenticationError=Q;exports.ConnectionError=Y;exports.ExternalIdNotDefinedError=J;exports.FileUploadError=ee;exports.LifecycleEvent=j;exports.OpenCXError=w;exports.PubSub=U;exports.SessionError=B;exports.SessionNotDefinedError=W;exports.StorageNotAvailableError=H;exports.TransportError=Z;exports.createChat=oe;exports.createConfig=ue;exports.createContact=ie;exports.createLogger=se;exports.createPubSub=z;exports.isAudioAvailable=te;exports.isStorageAvailable=O;exports.safeAudioOperation=re;exports.safeStorageOperation=N;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./api-BEtFfKMB.cjs");exports.ApiCaller=r.ApiCaller;exports.AuthenticationError=r.AuthenticationError;exports.ConnectionError=r.ConnectionError;exports.ExternalIdNotDefinedError=r.ExternalIdNotDefinedError;exports.FileUploadError=r.FileUploadError;exports.LifecycleEvent=r.LifecycleEvent;exports.OpenCXError=r.OpenCXError;exports.PubSub=r.PubSub;exports.SessionError=r.SessionError;exports.SessionNotDefinedError=r.SessionNotDefinedError;exports.StorageNotAvailableError=r.StorageNotAvailableError;exports.TransportError=r.TransportError;exports.createChat=r.createChat;exports.createConfig=r.createConfig;exports.createContactHandler=r.createContactHandler;exports.createLogger=r.createLogger;exports.createPubSub=r.createPubSub;exports.isAudioAvailable=r.isAudioAvailable;exports.isStorageAvailable=r.isStorageAvailable;exports.safeAudioOperation=r.safeAudioOperation;exports.safeStorageOperation=r.safeStorageOperation;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../core/types/pub-sub.ts","../core/errors/index.ts","../core/platform/storage.ts","../core/platform/logger.ts","../core/platform/audio.ts","../core/client/chat.ts","../core/client/contact.ts","../core/client/config.ts","../core/utils/create-fetch.ts","../core/client/api.ts"],"sourcesContent":["import isEqual from 'lodash.isequal';\n\nexport type Subscriber<T> = (data: T) => void\n\nexport enum LifecycleEvent {\n INIT = 'init',\n STATE_CHANGE = 'stateChange',\n BEFORE_UPDATE = 'beforeUpdate',\n AFTER_UPDATE = 'afterUpdate',\n DESTROY = 'destroy',\n ERROR = 'error'\n}\n\ntype LifecycleListener = (event: { type: LifecycleEvent; timestamp: number; data?: any }) => void;\n\nexport class PubSub<S> {\n private subscribers = new Set<Subscriber<S>>();\n #state: S;\n private initialState: S;\n #lastUpdated: number | null;\n private lifecycleListeners: Map<LifecycleEvent, Set<LifecycleListener>> = new Map();\n\n constructor(state: S) {\n this.#state = state;\n this.initialState = state;\n this.#lastUpdated = Date.now();\n this.emitLifecycle(LifecycleEvent.INIT, { initialState: this.#state });\n }\n\n private emitLifecycle = (event: LifecycleEvent, data?: any) => {\n const listeners = this.lifecycleListeners.get(event);\n if (listeners) {\n const eventData = {\n type: event,\n timestamp: Date.now(),\n data\n };\n listeners.forEach(listener => {\n try {\n listener(eventData);\n } catch (error) {\n console.error('Error in lifecycle listener:', error);\n }\n });\n }\n }\n\n private notifySubscribers = (state: S) => {\n const subscribersArray = Array.from(this.subscribers);\n subscribersArray.forEach(callback => {\n try {\n callback(state);\n } catch (error) {\n this.emitLifecycle(LifecycleEvent.ERROR, { error });\n console.error('Error in subscriber:', error);\n }\n });\n }\n\n /**\n * Subscribe to state changes\n * @param callback Function to call when state changes\n * @returns Unsubscribe function\n */\n subscribe = (callback: Subscriber<S>): () => void => {\n this.subscribers.add(callback);\n // Don't call the callback immediately with current state\n return () => {\n this.subscribers.delete(callback);\n };\n }\n\n onLifecycle = (event: LifecycleEvent, listener: LifecycleListener): () => void => {\n if (!this.lifecycleListeners.has(event)) {\n this.lifecycleListeners.set(event, new Set());\n }\n const listeners = this.lifecycleListeners.get(event)!;\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n this.lifecycleListeners.delete(event);\n }\n };\n }\n\n /**\n * Get the current state\n */\n getState = (): S => {\n return this.#state;\n }\n\n /**\n * Set the state and notify subscribers if the state changes\n * @param newState The new state to set\n */\n setState = (newState: S): void => {\n this.emitLifecycle(LifecycleEvent.BEFORE_UPDATE, {\n previousState: this.#state,\n nextState: newState\n });\n\n if (!isEqual(this.#state, newState)) {\n this.#state = newState;\n this.#lastUpdated = Date.now();\n this.emitLifecycle(LifecycleEvent.STATE_CHANGE, { state: newState });\n this.notifySubscribers(newState);\n }\n\n this.emitLifecycle(LifecycleEvent.AFTER_UPDATE, { state: newState });\n }\n\n setStatePartial = (_s: Partial<S>): void => {\n if (_s === undefined || _s === null) return;\n const newState = { ...this.#state, ..._s };\n this.setState(newState);\n }\n\n /**\n * Clear all subscriptions\n */\n clear = (): void => {\n this.emitLifecycle(LifecycleEvent.DESTROY);\n this.subscribers = new Set(); // Create a new Set instead of just clearing\n this.lifecycleListeners = new Map();\n }\n\n reset = (): void => {\n this.setState(this.initialState);\n }\n\n lastUpdated = (): number | null => {\n return this.#lastUpdated;\n }\n}\n\nexport function createPubSub<S>(state: S): PubSub<S> {\n return new PubSub<S>(state);\n}","export class OpenCXError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OpenCXError\";\n }\n}\n\nexport class ConnectionError extends OpenCXError {\n constructor(message = \"Connection failed\") {\n super(message);\n this.name = \"ConnectionError\";\n }\n}\n\nexport class AuthenticationError extends OpenCXError {\n constructor(message = \"Authentication failed\") {\n super(message);\n this.name = \"AuthenticationError\";\n }\n}\n\nexport class SessionError extends OpenCXError {\n constructor(message = \"Session error occurred\") {\n super(message);\n this.name = \"SessionError\";\n }\n}\n\nexport class SessionNotDefinedError extends SessionError {\n constructor(message = \"Session not defined\") {\n super(message);\n this.name = \"SessionNotDefinedError\";\n }\n}\n\nexport class TransportError extends OpenCXError {\n constructor(message = \"Transport error occurred\") {\n super(message);\n this.name = \"TransportError\";\n }\n}\n\nexport class FileUploadError extends OpenCXError {\n constructor(message = \"File upload failed\") {\n super(message);\n this.name = \"FileUploadError\";\n }\n}\n\nexport class StorageNotAvailableError extends OpenCXError {\n constructor(message = \"Storage is not available\") {\n super(message);\n this.name = \"StorageNotAvailableError\";\n }\n}\n\nexport class ExternalIdNotDefinedError extends OpenCXError {\n constructor(message = \"External ID is not defined\") {\n super(message);\n this.name = \"ExternalIdNotDefinedError\";\n }\n}\n","/**\n * Platform-agnostic storage interface that can be implemented\n * for different environments (web, mobile, desktop, etc.)\n */\nexport interface Storage {\n /**\n * Retrieves the value associated with the given key\n * @param key The key to look up\n * @returns The stored value or null if not found\n */\n getItem(key: string): Promise<string | null>;\n\n /**\n * Stores a value with the given key\n * @param key The key to store under\n * @param value The value to store\n */\n setItem(key: string, value: string): Promise<void>;\n\n /**\n * Removes the value associated with the given key\n * @param key The key to remove\n */\n removeItem(key: string): Promise<void>;\n\n /**\n * Checks if the storage is available and working\n * @returns true if storage is available and working\n */\n isAvailable?(): boolean;\n}\n\n/**\n * Helper function to check if storage is available and working\n */\nexport function isStorageAvailable(storage: Storage | undefined): storage is Storage {\n if (!storage) return false;\n try {\n return typeof storage.isAvailable === 'function'\n ? storage.isAvailable()\n : true; // If isAvailable is not implemented, assume storage is available\n } catch {\n return false;\n }\n}\n\n/**\n * Type for the result of a safe storage operation\n */\nexport type StorageOperationResult<T> =\n | { success: true; result: T; error: null }\n | { success: false; result: null; error: { message: string; code: string; context: string } };\n\n/**\n * Helper function to safely perform storage operations\n */\nexport async function safeStorageOperation<T>(\n operation: () => Promise<T>,\n errorContext: string\n): Promise<StorageOperationResult<T>> {\n try {\n const result = await operation();\n return { success: true, result, error: null };\n } catch (error) {\n console.error(errorContext, error);\n return {\n success: false,\n result: null,\n error: {\n message: error instanceof Error\n ? (error.message || 'Unknown error')\n : (error?.toString() || 'Unknown error'),\n code: 'STORAGE_OPERATION_FAILED',\n context: errorContext\n }\n };\n }\n} ","export type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\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 setLevel(level: LogLevel): void;\n}\n\nexport type LoggerOptions = {\n level?: LogLevel;\n prefix?: string;\n enabled?: boolean;\n};\n\nexport function createLogger(options: LoggerOptions = {}): Logger {\n const {\n level = 'info',\n prefix = '[openCx]',\n enabled = true\n } = options;\n\n let currentLevel = level;\n const levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3\n };\n\n function shouldLog(messageLevel: LogLevel): boolean {\n return enabled && levels[messageLevel] >= levels[currentLevel];\n }\n\n function formatMessage(message: string): string {\n return `${prefix} ${message}`;\n }\n\n function formatArgs(args: any[]): any[] {\n return args.map(arg => {\n if (arg instanceof Error) {\n return {\n name: arg.name,\n message: arg.message,\n stack: arg.stack\n };\n }\n if (typeof arg === 'object') {\n try {\n return JSON.stringify(arg, null, 2);\n } catch {\n return arg;\n }\n }\n return arg;\n });\n }\n\n return {\n debug(message: string, ...args: any[]) {\n if (shouldLog('debug')) {\n console.debug(formatMessage(message), ...formatArgs(args));\n }\n },\n\n info(message: string, ...args: any[]) {\n if (shouldLog('info')) {\n console.info(formatMessage(message), ...formatArgs(args));\n }\n },\n\n warn(message: string, ...args: any[]) {\n if (shouldLog('warn')) {\n console.warn(formatMessage(message), ...formatArgs(args));\n }\n },\n\n error(message: string, ...args: any[]) {\n if (shouldLog('error')) {\n console.error(formatMessage(message), ...formatArgs(args));\n }\n },\n\n setLevel(level: LogLevel) {\n currentLevel = level;\n }\n };\n} ","/**\n * Platform-agnostic audio interface that can be implemented\n * for different environments (web, mobile, desktop, etc.)\n */\nexport interface Audio {\n /**\n * Plays a notification sound\n * @returns Promise that resolves when the sound finishes playing or rejects on error\n */\n playNotification(): Promise<void>;\n\n /**\n * Checks if audio playback is available and working\n * @returns true if audio is available and working\n */\n isAvailable?(): boolean;\n}\n\n/**\n * Helper function to check if audio is available and working\n */\nexport function isAudioAvailable(audio: Audio | undefined): audio is Audio {\n if (!audio) return false;\n try {\n return typeof audio.isAvailable === 'function'\n ? audio.isAvailable()\n : true; // If isAvailable is not implemented, assume audio is available\n } catch {\n return false;\n }\n}\n\n/**\n * Type for the result of a safe audio operation\n */\nexport type AudioOperationResult =\n | { success: true; error: null }\n | { success: false; error: { message: string; code: string; context: string } };\n\n/**\n * Helper function to safely perform audio operations\n */\nexport async function safeAudioOperation(\n operation: () => Promise<void>,\n errorContext: string\n): Promise<AudioOperationResult> {\n try {\n await operation();\n return { success: true, error: null };\n } catch (error) {\n console.error(errorContext, error);\n return {\n success: false,\n error: {\n message: error instanceof Error\n ? (error.message || 'Unknown error')\n : (error?.toString() || 'Unknown error'),\n code: 'AUDIO_OPERATION_FAILED',\n context: errorContext\n }\n };\n }\n}\n","import { PubSub } from \"../types/pub-sub\";\nimport { MessageType } from \"../types\";\nimport { ApiCaller } from \"./api\";\nimport { genUuid } from \"../utils/genUuid\";\nimport { HandleContactMessageOutputSchema, HttpChatInputSchema, WidgetHistorySchema, WidgetSessionSchema } from \"../types/schemas-v2\";\nimport { LoadingState, ErrorState, SomeOptional } from \"../types/helpers\";\nimport { ConfigInstance } from \"./config\";\nimport { Platform, isStorageAvailable } from \"../platform\";\nimport { Logger } from \"../platform/logger\";\nimport { ExternalIdNotDefinedError, StorageNotAvailableError } from \"@core/errors\";\n\n// Constants\nconst POLLING_INTERVALS = {\n SESSION: 10000, // every 10 seconds\n MESSAGES: 5000 // every 5 seconds\n} as const;\n\n// Types\nexport type PollingType = 'session' | 'messages';\n\nexport type PollingState = {\n isPolling: boolean;\n lastPollTime: string | null;\n nextPollTime: string | null;\n error: ErrorState;\n};\n\nexport type PollingStates = {\n [K in PollingType]: PollingState;\n};\n\nexport type ChatState = {\n messages: MessageType[];\n keyboard: { options: string[] } | null;\n loading: LoadingState;\n error: ErrorState;\n polling: PollingStates;\n};\n\ntype ChatOptions = {\n api: ApiCaller;\n config: ConfigInstance;\n onSessionDestroy?: () => void;\n platform: Platform;\n};\n\n// Message Mapping\nfunction mapHistoryToMessage(history: WidgetHistorySchema): MessageType {\n const commonFields = {\n id: history.publicId,\n timestamp: history.sentAt || \"\",\n attachments: history.attachments || undefined\n };\n\n if (history.sender.kind === 'user') {\n return {\n ...commonFields,\n type: \"FROM_USER\",\n content: history.content.text || \"\",\n deliveredAt: history.sentAt || \"\",\n };\n }\n\n if (history.sender.kind === 'agent') {\n return {\n id: history.publicId,\n type: \"FROM_AGENT\",\n component: history.type,\n data: {\n text: history.content.text\n },\n timestamp: history.sentAt || \"\",\n attachments: history.attachments || undefined\n }\n }\n\n return {\n ...commonFields,\n type: \"FROM_BOT\",\n component: 'TEXT',\n agent: {\n id: null,\n name: history.sender.name || '',\n is_ai: history.sender.kind === 'ai',\n profile_picture: history.sender.avatar\n },\n data: {\n message: history.content.text\n },\n };\n}\n\n// Message Handling\nfunction createMessageHandler(api: ApiCaller, state: PubSub<ChatState>, logger?: Logger) {\n async function fetchHistoryMessages(session: WidgetSessionSchema) {\n const messages = state.getState().messages;\n if (messages.length === 0) {\n logger?.debug('No messages yet, fetching all history', { sessionId: session.id });\n const response = await api.getSessionHistory(session.id, \"\");\n if (response && response.length > 0) {\n state.setStatePartial({\n messages: response.map(mapHistoryToMessage)\n });\n }\n return;\n }\n const lastMessageTimestamp = state.getState().messages.at(-1)?.timestamp\n logger?.debug('Fetching history messages after timestamp', {\n sessionId: session.id,\n lastMessageTimestamp,\n currentMessageCount: messages.length\n });\n\n const response = await api.getSessionHistory(session.id, lastMessageTimestamp);\n\n if (response && response.length > 0) {\n // Map and filter out any potential duplicates by ID\n const newMessages = response\n .map(mapHistoryToMessage)\n .filter(newMsg => !messages.some(existingMsg => existingMsg.id === newMsg.id));\n\n if (newMessages.length > 0) {\n logger?.debug('Adding new messages to state', {\n count: newMessages.length,\n messageIds: newMessages.map(m => m.id),\n messageTypes: newMessages.map(m => m.type)\n });\n state.setStatePartial({\n messages: [...messages, ...newMessages]\n });\n }\n }\n }\n\n function addUserMessage(content: string, attachments?: any[]) {\n return {\n id: genUuid(),\n type: \"FROM_USER\" as const,\n content,\n deliveredAt: new Date().toISOString(),\n attachments,\n timestamp: new Date().toISOString()\n };\n }\n\n function addBotMessage(response: HandleContactMessageOutputSchema) {\n if (response.success && response.autopilotResponse) {\n return {\n type: \"FROM_BOT\" as const,\n id: response.autopilotResponse.id || genUuid(),\n timestamp: new Date().toISOString(),\n component: \"TEXT\",\n data: {\n message: response.autopilotResponse.value.content,\n }\n };\n }\n\n if (response.success && response.uiResponse) {\n const uiVal = response.uiResponse.value;\n return {\n type: \"FROM_BOT\" as const,\n id: genUuid(),\n timestamp: new Date().toISOString(),\n component: uiVal.name,\n data: uiVal.request_response,\n };\n }\n\n return null;\n }\n\n function addErrorMessage(message: string) {\n return {\n type: \"FROM_BOT\" as const,\n id: genUuid(),\n timestamp: new Date().toISOString(),\n component: \"TEXT\",\n data: {\n message,\n variant: \"error\"\n }\n };\n }\n\n return {\n fetchHistoryMessages,\n addUserMessage,\n addBotMessage,\n addErrorMessage\n };\n}\n\n// Session Management\nfunction createSessionManager(\n api: ApiCaller,\n sessionState: PubSub<WidgetSessionSchema | null>,\n chatState: PubSub<ChatState>,\n messageHandler: ReturnType<typeof createMessageHandler>,\n config: ConfigInstance,\n options: ChatOptions\n) {\n const logger = options.platform?.logger;\n let stopPolling: (() => void) | null = null;\n const storage = options.platform?.storage;\n const persistSession = config.getSettings().persistSession;\n\n if (persistSession && !isStorageAvailable(storage)) {\n throw new StorageNotAvailableError()\n }\n\n if (persistSession && !config.getConfig().user.external_id) {\n throw new ExternalIdNotDefinedError(\"session persistence is enabled but external id is not defined\")\n }\n\n const sessionStorageKey = `${config.getConfig().user.external_id}:${config.getConfig().token}:session`;\n /**\n * Restores the session from storage\n */\n async function restoreSession() {\n if (!storage) return;\n try {\n logger?.debug('Attempting to restore session from storage');\n const storedSession = await storage.getItem(sessionStorageKey);\n if (storedSession) {\n const session = JSON.parse(storedSession) as WidgetSessionSchema;\n logger?.info('Session restored from storage', { sessionId: session.id });\n sessionState.setState(session);\n await messageHandler.fetchHistoryMessages(session);\n startPolling();\n }\n } catch (error) {\n logger?.error('Error restoring session from storage:', error);\n }\n }\n\n /**\n * Sets up session persistence\n */\n function setupSessionPersistence() {\n if (!storage) return;\n logger?.debug('Setting up session persistence');\n sessionState.subscribe(async (session) => {\n try {\n if (session) {\n await storage.setItem(sessionStorageKey, JSON.stringify(session));\n logger?.debug('Session persisted to storage', { sessionId: session.id });\n } else {\n await storage.removeItem(sessionStorageKey);\n logger?.debug('Session removed from storage');\n }\n } catch (error) {\n logger?.error('Error persisting session:', error);\n chatState.setStatePartial({\n error: {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to persist session',\n code: 'SESSION_PERSISTENCE_FAILED'\n }\n });\n }\n });\n }\n\n /**\n * Starts polling for the session and messages\n */\n function startPolling() {\n if (stopPolling) return;\n\n logger?.debug('Starting polling');\n const intervals: NodeJS.Timeout[] = [];\n\n // Poll session\n intervals.push(\n setInterval(async () => {\n const session = sessionState.getState();\n if (!session?.id) return;\n\n try {\n const now = new Date();\n chatState.setStatePartial({\n polling: {\n ...chatState.getState().polling,\n session: {\n isPolling: true,\n lastPollTime: now.toISOString(),\n nextPollTime: new Date(now.getTime() + POLLING_INTERVALS.SESSION).toISOString(),\n error: { hasError: false }\n }\n }\n });\n\n const response = await api.getSession(session.id);\n if (response) {\n sessionState.setState(response);\n }\n\n chatState.setStatePartial({\n polling: {\n ...chatState.getState().polling,\n session: {\n ...chatState.getState().polling.session,\n isPolling: false\n }\n }\n });\n } catch (error) {\n logger?.error('Error polling session:', error);\n chatState.setStatePartial({\n polling: {\n ...chatState.getState().polling,\n session: {\n ...chatState.getState().polling.session,\n isPolling: false,\n error: {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to poll session',\n code: 'SESSION_POLLING_FAILED'\n }\n }\n }\n });\n }\n }, POLLING_INTERVALS.SESSION)\n );\n\n // Poll messages\n intervals.push(\n setInterval(async () => {\n const session = sessionState.getState();\n if (!session?.id) return;\n try {\n const now = new Date();\n chatState.setStatePartial({\n polling: {\n ...chatState.getState().polling,\n messages: {\n isPolling: true,\n lastPollTime: now.toISOString(),\n nextPollTime: new Date(now.getTime() + POLLING_INTERVALS.MESSAGES).toISOString(),\n error: { hasError: false }\n }\n }\n });\n\n await messageHandler.fetchHistoryMessages(session);\n\n chatState.setStatePartial({\n polling: {\n ...chatState.getState().polling,\n messages: {\n ...chatState.getState().polling.messages,\n isPolling: false\n }\n }\n });\n } catch (error) {\n logger?.error('Error polling messages:', error);\n chatState.setStatePartial({\n polling: {\n ...chatState.getState().polling,\n messages: {\n ...chatState.getState().polling.messages,\n isPolling: false,\n error: {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to poll messages',\n code: 'MESSAGES_POLLING_FAILED'\n }\n }\n }\n });\n }\n }, POLLING_INTERVALS.MESSAGES)\n );\n\n stopPolling = () => {\n logger?.debug('Stopping polling');\n intervals.forEach(clearInterval);\n // Reset polling states\n chatState.setStatePartial({\n polling: {\n session: {\n isPolling: false,\n lastPollTime: null,\n nextPollTime: null,\n error: { hasError: false }\n },\n messages: {\n isPolling: false,\n lastPollTime: null,\n nextPollTime: null,\n error: { hasError: false }\n }\n }\n });\n };\n }\n\n /**\n * Creates a new session\n * @returns The session\n */\n async function createSession() {\n try {\n logger?.info('Creating new session');\n chatState.setStatePartial({\n loading: { isLoading: true, reason: 'creating_session' },\n error: { hasError: false }\n });\n\n const session = await api.createSession();\n logger?.info('Session created successfully', { sessionId: session.id });\n sessionState.setState(session);\n startPolling();\n return session;\n } catch (error) {\n logger?.error('Failed to create session:', error);\n const errorState = {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to create session',\n code: 'SESSION_CREATION_FAILED' as const\n };\n chatState.setStatePartial({ error: errorState });\n return null;\n } finally {\n chatState.setStatePartial({\n loading: { isLoading: false, reason: null }\n });\n }\n }\n\n /**\n * Clears the session and stops polling\n */\n async function clearSession() {\n const session = sessionState.getState();\n if (!session?.id) return;\n\n try {\n if (stopPolling) {\n stopPolling();\n stopPolling = null;\n }\n sessionState.setState(null);\n\n if (persistSession && storage) {\n await storage.removeItem(sessionStorageKey);\n }\n\n chatState.setState({\n messages: [],\n keyboard: null,\n loading: { isLoading: false, reason: null },\n error: { hasError: false },\n polling: {\n session: {\n isPolling: false,\n lastPollTime: null,\n nextPollTime: null,\n error: { hasError: false }\n },\n messages: {\n isPolling: false,\n lastPollTime: null,\n nextPollTime: null,\n error: { hasError: false }\n }\n }\n });\n\n options.onSessionDestroy?.();\n } catch (error) {\n console.error(\"Error clearing session:\", error);\n chatState.setStatePartial({\n error: {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to clear session',\n code: 'SESSION_CLEAR_FAILED'\n }\n });\n }\n }\n\n /**\n * Cleans up the session and stops polling\n */\n function cleanup(removeSession = false) {\n try {\n if (stopPolling) {\n stopPolling();\n stopPolling = null;\n }\n\n if (removeSession && persistSession && storage && isStorageAvailable(storage)) {\n storage.removeItem(sessionStorageKey);\n }\n\n chatState.setState({\n messages: [],\n keyboard: null,\n loading: { isLoading: false, reason: null },\n error: { hasError: false },\n polling: {\n session: {\n isPolling: false,\n lastPollTime: null,\n nextPollTime: null,\n error: { hasError: false }\n },\n messages: {\n isPolling: false,\n lastPollTime: null,\n nextPollTime: null,\n error: { hasError: false }\n }\n }\n });\n\n sessionState.setState(null);\n chatState.clear();\n sessionState.clear();\n } catch (error) {\n console.error(\"Error in cleanup:\", error);\n chatState.setStatePartial({\n error: {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to cleanup',\n code: 'SESSION_CLEAR_FAILED'\n }\n });\n }\n }\n\n /**\n * Fetches the session from the API\n * @param id - The ID of the session to fetch\n * @returns The session\n */\n async function fetchSession(id: string) {\n return api.getSession(id);\n }\n\n /**\n * Refetches the session and updates the state\n */\n async function refetchSession() {\n const session = sessionState.getState();\n if (!session?.id) return;\n const newSession = await fetchSession(session.id);\n if (newSession) {\n sessionState.setState(newSession);\n }\n return newSession;\n }\n\n // Initialize session if persistence is enabled\n if (persistSession && isStorageAvailable(storage)) {\n restoreSession();\n setupSessionPersistence();\n }\n\n return {\n createSession,\n clearSession,\n cleanup,\n startPolling,\n fetchSession,\n refetchSession,\n sessionStorageKey\n };\n}\nexport type SendMessageInput = SomeOptional<Omit<HttpChatInputSchema, \"bot_token\">, \"session_id\" | \"user\">\n// Main Chat Function\nexport function createChat(options: ChatOptions) {\n const logger = options.platform?.logger;\n const initialState = <ChatState>{\n messages: [],\n keyboard: null,\n loading: { isLoading: false, reason: null },\n error: { hasError: false },\n polling: {\n session: {\n isPolling: false,\n lastPollTime: null,\n nextPollTime: null,\n error: { hasError: false }\n },\n messages: {\n isPolling: false,\n lastPollTime: null,\n nextPollTime: null,\n error: { hasError: false }\n }\n }\n }\n const state = new PubSub<ChatState>(initialState);\n\n const sessionState = new PubSub<WidgetSessionSchema | null>(null);\n const messageHandler = createMessageHandler(options.api, state, logger);\n const sessionManager = createSessionManager(\n options.api,\n sessionState,\n state,\n messageHandler,\n options.config,\n options\n );\n\n async function sendMessage(input: SendMessageInput, abort?: AbortSignal) {\n let session = sessionState.getState();\n let createdSession = false;\n\n if (!session?.id) {\n logger?.debug('No active session, creating new session');\n session = await sessionManager.createSession();\n if (!session) return {\n success: false,\n createdSession,\n }\n createdSession = true;\n }\n\n if (session.assignee.kind === 'ai') {\n session = (await sessionManager.refetchSession()) ?? session;\n }\n\n try {\n logger?.debug('Sending message', { sessionId: session.id });\n if (session.assignee.kind === 'ai') {\n state.setStatePartial({\n loading: { isLoading: true, reason: 'sending_message_to_bot' },\n error: { hasError: false }\n });\n } else {\n state.setStatePartial({\n loading: { isLoading: true, reason: 'sending_message_to_agent' },\n error: { hasError: false }\n });\n }\n\n const userMessage = messageHandler.addUserMessage(input.content, input.attachments || undefined);\n const currentMessages = state.getState().messages;\n state.setStatePartial({\n messages: [...currentMessages, userMessage]\n });\n\n const config = options.config.getConfig();\n const data = await options.api.handleMessage({\n uuid: input.uuid || genUuid(),\n bot_token: config.token,\n headers: config.headers,\n query_params: config.queryParams,\n session_id: session.id,\n user: config.user,\n ...input,\n }, abort);\n\n if (data.success) {\n logger?.debug('Message sent successfully');\n const botMessage = messageHandler.addBotMessage(data);\n if (botMessage) {\n const updatedMessages = state.getState().messages;\n state.setStatePartial({\n messages: [...updatedMessages, botMessage]\n });\n }\n return {\n success: true,\n createdSession,\n botMessage\n }\n } else {\n logger?.warn('Message send failed', data.error);\n const errorMessage = messageHandler.addErrorMessage(data.error?.message || \"Unknown error occurred\");\n const currentMessages = state.getState().messages;\n state.setStatePartial({\n messages: [...currentMessages, errorMessage]\n });\n return {\n success: false,\n createdSession,\n error: data.error\n }\n }\n } catch (error) {\n logger?.error('Error sending message:', error);\n state.setStatePartial({\n error: {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to send message',\n code: 'MESSAGE_SEND_FAILED'\n }\n });\n return {\n success: false,\n createdSession,\n error\n }\n } finally {\n state.setStatePartial({\n loading: { isLoading: false, reason: null }\n });\n }\n }\n\n return {\n chatState: state,\n sessionState,\n sendMessage,\n createSession: sessionManager.createSession,\n clearSession: sessionManager.clearSession,\n cleanup: sessionManager.cleanup,\n initialState,\n sessionStorageKey: sessionManager.sessionStorageKey\n };\n} ","import { PubSub } from \"../types/pub-sub\";\nimport { ApiCaller } from \"./api\";\nimport { Platform, isStorageAvailable, safeStorageOperation } from \"../platform\";\nimport { LoadingState, ErrorState } from \"../types/helpers\";\nimport { ConfigInstance } from \"./config\";\nimport { ConsumerType } from \"@core/types/schemas\";\n\ntype ContactState = {\n contact: ConsumerType | null;\n loading: LoadingState;\n error: ErrorState;\n};\n\nexport type CreateContactOptions = {\n api: ApiCaller;\n platform: Platform;\n config: ConfigInstance\n};\n\nexport function createContact(options: CreateContactOptions) {\n const config = options.config.getConfig();\n options.config.getConfig\n const storageKey = `${config.token}:contact:${config.user.external_id}`;\n const storage = isStorageAvailable(options.platform.storage) ? options.platform.storage : undefined;\n\n // Initialize state from storage if available\n let initialContact: ConsumerType | null = null;\n if (storage) {\n safeStorageOperation(\n async () => {\n const stored = await storage.getItem(storageKey);\n return stored ? JSON.parse(stored) : null;\n },\n \"Error loading contact from storage\"\n ).then((result) => {\n if (result.success) {\n initialContact = result.result;\n }\n });\n }\n\n const state = new PubSub<ContactState>({\n contact: initialContact,\n loading: { isLoading: false, reason: null },\n error: { hasError: false }\n });\n\n // Subscribe to state changes to persist\n if (isStorageAvailable(storage)) {\n state.subscribe((currentState) => {\n safeStorageOperation(\n async () => {\n if (currentState.contact) {\n await storage.setItem(storageKey, JSON.stringify(currentState.contact));\n } else {\n storage.removeItem(storageKey);\n }\n },\n \"Error persisting contact state\"\n ).then((result) => {\n if (!result.success) {\n state.setStatePartial({\n error: {\n hasError: true,\n message: result.error.message,\n code: 'CONTACT_PERSISTENCE_FAILED'\n }\n });\n }\n });\n });\n }\n\n async function loadContact() {\n try {\n state.setStatePartial({\n loading: { isLoading: true, reason: 'loading_contact' },\n error: { hasError: false }\n });\n\n if (storage) {\n const result = await safeStorageOperation(\n async () => {\n const stored = await storage.getItem(storageKey);\n return stored ? JSON.parse(stored) : null;\n },\n \"Error loading contact\"\n );\n\n if (!result.success) {\n throw result.error;\n }\n\n state.setStatePartial({\n contact: result.result,\n error: { hasError: false }\n });\n\n return result.result;\n }\n\n return state.getState().contact;\n } catch (error) {\n state.setStatePartial({\n error: {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to load contact',\n code: 'CONTACT_LOAD_FAILED'\n }\n });\n return null;\n } finally {\n state.setStatePartial({\n loading: { isLoading: false, reason: null }\n });\n }\n }\n\n async function saveContact(contactData: Partial<ConsumerType>) {\n try {\n state.setStatePartial({\n loading: { isLoading: true, reason: 'saving_contact' },\n error: { hasError: false }\n });\n\n const currentContact = state.getState().contact;\n const updatedContact: ConsumerType = {\n id: contactData.id || currentContact?.id || '',\n name: contactData.name ?? currentContact?.name ?? null,\n created_at: contactData.created_at || currentContact?.created_at || new Date().toISOString(),\n avatar_url: contactData.avatar_url ?? currentContact?.avatar_url ?? null,\n email: contactData.email ?? currentContact?.email ?? null\n };\n\n if (isStorageAvailable(storage)) {\n const result = await safeStorageOperation(\n () => storage.setItem(storageKey, JSON.stringify(updatedContact)),\n \"Error saving contact\"\n );\n\n if (!result.success) {\n throw result.error;\n }\n }\n\n state.setStatePartial({\n contact: updatedContact,\n error: { hasError: false }\n });\n\n return updatedContact;\n } catch (error) {\n state.setStatePartial({\n error: {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to save contact',\n code: 'CONTACT_SAVE_FAILED'\n }\n });\n return null;\n } finally {\n state.setStatePartial({\n loading: { isLoading: false, reason: null }\n });\n }\n }\n\n function shouldCollectData(): { should: boolean; reason?: string } {\n const currentState = state.getState();\n\n if (!currentState.contact?.id && config.collectUserData) {\n return {\n should: true,\n reason: \"No contact id and collectUserData is true\"\n };\n }\n\n return {\n should: false\n };\n }\n\n async function cleanup() {\n try {\n state.setStatePartial({\n loading: { isLoading: true, reason: 'cleaning_up' },\n error: { hasError: false }\n });\n\n if (storage) {\n const result = await safeStorageOperation(\n () => storage.removeItem(storageKey),\n \"Error removing contact data\"\n );\n\n if (!result.success) {\n throw result.error;\n }\n }\n\n state.setState({\n contact: null,\n loading: { isLoading: false, reason: null },\n error: { hasError: false }\n });\n\n state.clear();\n } catch (error) {\n console.error(\"Error cleaning up contact:\", error);\n state.setStatePartial({\n error: {\n hasError: true,\n message: error instanceof Error ? error.message : 'Failed to cleanup contact data',\n code: 'CONTACT_CLEANUP_FAILED'\n }\n });\n } finally {\n state.setStatePartial({\n loading: { isLoading: false, reason: null }\n });\n }\n }\n\n return {\n contactState: state,\n shouldCollectData,\n loadContact,\n saveContact,\n cleanup,\n };\n} ","import { CoreOptions } from \"../types\";\n\nconst DEFAULT_SOUND_EFFECTS = {\n messageArrived: \"https://cloud.opencopilot.so/sfx/notification3.mp3\"\n};\n\nconst DEFAULT_THEME = {\n primaryColor: \"hsl(211,65%,59%)\",\n triggerOffset: \"20px\"\n};\n\nexport type NormalizedConfig = Required<Omit<CoreOptions, 'contactToken'>> & {\n contactToken: string | undefined | null;\n soundEffectFiles: {\n messageArrived: string;\n };\n theme: {\n primaryColor: string;\n triggerOffset: string;\n };\n settings: {\n persistSession: boolean;\n useSoundEffects: boolean;\n };\n};\n\nexport type ConfigInstance = {\n getConfig: () => NormalizedConfig;\n getApiConfig: () => {\n apiUrl: string;\n token: string;\n headers: Record<string, string>;\n queryParams: Record<string, string>;\n pathParams: Record<string, string>;\n };\n getBotConfig: () => NormalizedConfig['bot'];\n getThemeConfig: () => NormalizedConfig['theme'];\n getSettings: () => NormalizedConfig['settings'];\n getSoundEffects: () => NormalizedConfig['soundEffectFiles'];\n getUser: () => NormalizedConfig['user'];\n getLanguage: () => string;\n getDebugMode: () => boolean;\n};\n\nconst MIN_POLLING_INTERVAL = 1000 * 3;\n\nexport function createConfig(options: CoreOptions): ConfigInstance {\n if (!options.token) {\n throw new Error(\"Token is required\");\n }\n\n if (options.pollingInterval && options.pollingInterval < MIN_POLLING_INTERVAL) {\n throw new Error(\"Polling interval must be at least 3 seconds\");\n }\n\n const normalizedConfig: NormalizedConfig = {\n ...options,\n collectUserData: options.collectUserData ?? false,\n apiUrl: options.apiUrl ?? \"https://api.open.cx/backend\",\n pollingInterval: options.pollingInterval ?? 3000,\n headers: options.headers ?? {},\n queryParams: options.queryParams ?? {},\n pathParams: options.pathParams ?? {},\n bot: {\n name: options.bot?.name ?? \"Bot\",\n avatarUrl: options.bot?.avatarUrl,\n id: options.bot?.id ?? null,\n is_ai: options.bot?.is_ai ?? true\n },\n contactToken: options.contactToken,\n debug: options.debug ?? false,\n language: options.language ?? \"en\",\n user: options.user ?? {},\n soundEffectFiles: {\n messageArrived: options.soundEffectFiles?.messageArrived ?? DEFAULT_SOUND_EFFECTS.messageArrived\n },\n theme: {\n primaryColor: options.theme?.primaryColor ?? DEFAULT_THEME.primaryColor,\n triggerOffset: options.theme?.triggerOffset ?? DEFAULT_THEME.triggerOffset\n },\n settings: {\n persistSession: options.settings?.persistSession ?? false,\n useSoundEffects: options.settings?.useSoundEffects ?? false\n },\n };\n\n return {\n getConfig: () => normalizedConfig,\n getApiConfig: () => ({\n apiUrl: normalizedConfig.apiUrl,\n token: normalizedConfig.token,\n headers: normalizedConfig.headers,\n queryParams: normalizedConfig.queryParams,\n pathParams: normalizedConfig.pathParams\n }),\n getBotConfig: () => normalizedConfig.bot,\n getThemeConfig: () => normalizedConfig.theme,\n getSettings: () => normalizedConfig.settings,\n getSoundEffects: () => normalizedConfig.soundEffectFiles,\n getUser: () => normalizedConfig.user,\n getLanguage: () => normalizedConfig.language,\n getDebugMode: () => normalizedConfig.debug\n };\n} ","import \"whatwg-fetch\";\ntype RequestInterceptor = (config: RequestConfig) => RequestConfig | Promise<RequestConfig>;\ntype ResponseInterceptor = (response: Response) => Response | Promise<Response>;\ntype ErrorInterceptor = (error: any) => any;\n\ninterface RequestConfig extends RequestInit {\n baseURL?: string;\n headers?: HeadersInit;\n params?: Record<string, string>;\n}\n\nexport interface CustomFetch {\n (url: string, config?: RequestConfig): Promise<Response>;\n interceptors: {\n request: {\n use: (interceptor: RequestInterceptor) => number;\n eject: (id: number) => void;\n };\n response: {\n use: (interceptor: ResponseInterceptor, errorInterceptor?: ErrorInterceptor) => number;\n eject: (id: number) => void;\n };\n };\n}\n\ntype Fetch = typeof globalThis.fetch;\n\nexport function createFetch(defaultConfig: RequestConfig = {}, fetch: Fetch = globalThis.fetch): CustomFetch {\n const requestInterceptors: RequestInterceptor[] = [];\n const responseInterceptors: ResponseInterceptor[] = [];\n const errorInterceptors: ErrorInterceptor[] = [];\n\n const customFetch: CustomFetch = async (url: string, config: RequestConfig = {}) => {\n // Merge configs\n let mergedConfig: RequestConfig = {\n ...defaultConfig,\n ...config,\n headers: {\n ...defaultConfig.headers,\n ...config.headers,\n },\n };\n\n try {\n // Apply request interceptors\n for (const interceptor of requestInterceptors) {\n mergedConfig = await interceptor(mergedConfig);\n }\n\n // Handle URL params\n const queryParams = mergedConfig.params\n ? '?' + new URLSearchParams(mergedConfig.params).toString()\n : '';\n\n // Construct full URL\n const fullUrl = mergedConfig.baseURL\n ? `${mergedConfig.baseURL}${url}${queryParams}`.replace(/([^:]\\/)\\/+/g, '$1')\n : `${url}${queryParams}`;\n\n // Make the fetch call\n let response = await fetch(fullUrl, mergedConfig);\n\n // Apply response interceptors\n for (const interceptor of responseInterceptors) {\n response = await interceptor(response);\n }\n\n return response;\n } catch (error) {\n // Apply error interceptors\n let processedError = error;\n for (const interceptor of errorInterceptors) {\n processedError = await interceptor(processedError);\n }\n throw processedError;\n }\n };\n\n // Add interceptors management\n customFetch.interceptors = {\n request: {\n use: (interceptor: RequestInterceptor) => {\n requestInterceptors.push(interceptor);\n return requestInterceptors.length - 1;\n },\n eject: (id: number) => {\n requestInterceptors.splice(id, 1);\n },\n },\n response: {\n use: (interceptor: ResponseInterceptor, errorInterceptor?: ErrorInterceptor) => {\n responseInterceptors.push(interceptor);\n if (errorInterceptor) {\n errorInterceptors.push(errorInterceptor);\n }\n return responseInterceptors.length - 1;\n },\n eject: (id: number) => {\n responseInterceptors.splice(id, 1);\n errorInterceptors.splice(id, 1);\n },\n },\n };\n\n return customFetch;\n}\n\n// Helper method to handle JSON responses\nexport async function handleJsonResponse<T>(response: Response): Promise<T> {\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n return response.json();\n}\n\n// Usage example:\n/*\nconst api = createFetch({\n baseURL: 'https://api.example.com',\n headers: {\n 'Content-Type': 'application/json',\n },\n});\n\n// Add request interceptor\napi.interceptors.request.use((config) => {\n config.headers = {\n ...config.headers,\n 'Authorization': `Bearer ${getToken()}`,\n };\n return config;\n});\n\n// Add response interceptor\napi.interceptors.response.use(\n async (response) => {\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n return response;\n },\n (error) => {\n console.error('Request failed:', error);\n throw error;\n }\n);\n*/\n","import { createFetch, CustomFetch } from \"../utils/create-fetch\";\nimport { HandleContactMessageOutputSchema, HttpChatInputSchema, WidgetHistorySchema, WidgetPreludeSchema, WidgetSessionSchema } from \"../types/schemas-v2\";\nimport { NormalizedConfig } from \"./config\";\nimport { ConsumerType } from \"@core/types/schemas\";\n\nexport interface ApiCallerOptions {\n config: NormalizedConfig;\n}\n\nexport class ApiCaller {\n #fetch: CustomFetch\n constructor(private readonly options: ApiCallerOptions) {\n const user = this.options.config.user;\n const consumerHeader = {\n claim: '',\n value: ''\n }\n\n if (user?.email) {\n consumerHeader.claim = 'email';\n consumerHeader.value = user.email;\n }\n\n else if (user?.phone) {\n consumerHeader.claim = 'phone';\n consumerHeader.value = user.phone;\n }\n\n const headers: Record<string, string> = {\n 'X-Bot-Token': this.options.config.token,\n 'X-Consumer-Id': `${consumerHeader.claim}:${consumerHeader.value}`,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n }\n\n // Only add Authorization header if contactToken exists\n if (this.options.config.contactToken) {\n headers['Authorization'] = `Bearer ${this.options.config.contactToken}`\n }\n\n this.#fetch = createFetch({\n baseURL: `${this.options.config.apiUrl}/widget/v2`,\n headers\n })\n }\n\n async me(): Promise<{\n contactId: string;\n contactName: string;\n }> {\n // GET /me\n const response = await this.#fetch('/me')\n return response.json()\n }\n\n async widgetPrelude(): Promise<WidgetPreludeSchema> {\n // GET /prelude\n const response = await this.#fetch('/prelude')\n return response.json()\n }\n\n async handleMessage(message: HttpChatInputSchema, abortSignal?: AbortSignal) {\n // POST /chat/send\n const response = await this.#fetch('/chat/send', {\n method: \"POST\",\n body: JSON.stringify(message),\n signal: abortSignal\n })\n return response.json() as Promise<HandleContactMessageOutputSchema>\n }\n\n async getSessionHistory(sessionId: string, lastMessageTimestamp?: string): Promise<WidgetHistorySchema[]> {\n // session/history/:sessionId\n const queryParams = new URLSearchParams({\n lastMessageTimestamp: lastMessageTimestamp || ''\n })\n\n const url = `/session/history/${sessionId}?${queryParams.toString()}`\n\n const response = await this.#fetch(url, {\n method: 'GET'\n })\n\n return response.json()\n }\n\n async createSession(): Promise<WidgetSessionSchema> {\n // POST /create-session\n const response = await this.#fetch('/create-session', {\n method: 'POST'\n })\n return response.json()\n }\n\n async getSession(sessionId: string): Promise<WidgetSessionSchema> {\n // GET /session/:sessionId\n const response = await this.#fetch(`/session/${sessionId}`, {\n method: 'GET'\n })\n return response.json()\n }\n}\n"],"names":["LifecycleEvent","PubSub","state","__publicField","__privateAdd","_state","_lastUpdated","event","data","listeners","eventData","listener","error","callback","__privateGet","newState","isEqual","__privateSet","_s","createPubSub","OpenCXError","message","ConnectionError","AuthenticationError","SessionError","SessionNotDefinedError","TransportError","FileUploadError","StorageNotAvailableError","ExternalIdNotDefinedError","isStorageAvailable","storage","safeStorageOperation","operation","errorContext","createLogger","options","level","prefix","enabled","currentLevel","levels","shouldLog","messageLevel","formatMessage","formatArgs","args","arg","isAudioAvailable","audio","safeAudioOperation","POLLING_INTERVALS","mapHistoryToMessage","history","commonFields","createMessageHandler","api","logger","fetchHistoryMessages","session","messages","response","lastMessageTimestamp","_a","newMessages","newMsg","existingMsg","m","addUserMessage","content","attachments","genUuid","addBotMessage","uiVal","addErrorMessage","createSessionManager","sessionState","chatState","messageHandler","config","stopPolling","_b","persistSession","sessionStorageKey","restoreSession","storedSession","startPolling","setupSessionPersistence","intervals","now","createSession","errorState","clearSession","cleanup","removeSession","fetchSession","id","refetchSession","newSession","createChat","initialState","sessionManager","sendMessage","input","abort","createdSession","userMessage","currentMessages","botMessage","updatedMessages","errorMessage","createContact","storageKey","initialContact","stored","result","currentState","loadContact","saveContact","contactData","currentContact","updatedContact","shouldCollectData","DEFAULT_SOUND_EFFECTS","DEFAULT_THEME","MIN_POLLING_INTERVAL","createConfig","normalizedConfig","_c","_d","_e","_f","_g","_h","_i","createFetch","defaultConfig","fetch","requestInterceptors","responseInterceptors","errorInterceptors","customFetch","url","mergedConfig","interceptor","queryParams","fullUrl","processedError","errorInterceptor","ApiCaller","_fetch","user","consumerHeader","headers","abortSignal","sessionId"],"mappings":"ypBAIY,IAAAA,GAAAA,IACRA,EAAA,KAAO,OACPA,EAAA,aAAe,cACfA,EAAA,cAAgB,eAChBA,EAAA,aAAe,cACfA,EAAA,QAAU,UACVA,EAAA,MAAQ,QANAA,IAAAA,GAAA,CAAA,CAAA,MAWL,MAAMC,CAAU,CAOnB,YAAYC,EAAU,CANdC,EAAA,uBAAkB,KAC1BC,EAAA,KAAAC,GACQF,EAAA,qBACRC,EAAA,KAAAE,GACQH,EAAA,8BAAsE,KAStEA,EAAA,qBAAgB,CAACI,EAAuBC,IAAe,CAC3D,MAAMC,EAAY,KAAK,mBAAmB,IAAIF,CAAK,EACnD,GAAIE,EAAW,CACX,MAAMC,EAAY,CACd,KAAMH,EACN,UAAW,KAAK,IAAI,EACpB,KAAAC,CAAA,EAEJC,EAAU,QAAoBE,GAAA,CACtB,GAAA,CACAA,EAASD,CAAS,QACbE,EAAO,CACJ,QAAA,MAAM,+BAAgCA,CAAK,CACvD,CAAA,CACH,CACL,CAAA,GAGIT,EAAA,yBAAqBD,GAAa,CACb,MAAM,KAAK,KAAK,WAAW,EACnC,QAAoBW,GAAA,CAC7B,GAAA,CACAA,EAASX,CAAK,QACTU,EAAO,CACZ,KAAK,cAAc,QAAsB,CAAE,MAAAA,CAAO,CAAA,EAC1C,QAAA,MAAM,uBAAwBA,CAAK,CAC/C,CAAA,CACH,CAAA,GAQLT,EAAA,iBAAaU,IACJ,KAAA,YAAY,IAAIA,CAAQ,EAEtB,IAAM,CACJ,KAAA,YAAY,OAAOA,CAAQ,CAAA,IAIxCV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